answer
stringlengths
17
10.2M
package edu.umd.cs.findbugs.anttask; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; import org.apache.tools.ant.types.Path; import org.apache.tools.ant.types.Reference; import org.apache.tools.ant.taskdefs.Java; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * FindBugs in Java class files. This task can take the following * arguments: * <ul> * <li>auxClasspath (classpath or classpathRef) * <li>home (findbugs install dir) * <li>quietErrors (boolean - default false) * <li>reportLevel (enum low|medium|high) * <li>sort (boolean default true) * <li>debug (boolean default false) * <li>output (enum text|xml - default xml) * <li>visitors (collection - comma seperated) * <li>omitVisitors (collection - comma seperated) * <li>excludeFilter (filter filename) * <li>includeFilter (filter filename) * <li>projectFile (project filename) * <li>jvmargs (any additional jvm arguments) * </ul> * Of these arguments, the <b>home</b> is required. * <b>projectFile</b> is required if nested &lt;class&gt; are not * specified. the &lt;class&gt; tag defines the location of either a * class, jar file, zip file, or directory containing classes * <p> * * @author Mike Fagan <a href="mailto:mfagan@tde.com">mfagan@tde.com</a> * * @version $Revision: 2.0 * * @since Ant 1.5 * * @ant.task category="utility" */ public class FindBugsTask extends Task { private static final String FAIL_MSG = "Findbugs found errors; see the error output for details."; private static final String FINDBUGS_JAR = "findbugs.jar"; private static final long TIMEOUT = 300000; //five minutes private boolean debug = false; private boolean sorted = true; private boolean quietErrors = false; private File homeDir = null; private File projectFile = null; private File excludeFile = null; private File includeFile = null; private Path auxClasspath = null; private String outputFormat = "xml"; private String reportLevel = null; private String jvmargs = ""; private String visitors = null; private String omitVisitors = null; private List classLocations = new ArrayList(); //define the inner class to store class locations public class ClassLocation { File classLocation = null; public void setLocation( File location ) { classLocation = location; } public File getLocation( ) { return classLocation; } public String toString( ) { return classLocation!=null?classLocation.toString():""; } } /** * Set any specific jvm args */ public void setJvmargs(String args) { this.jvmargs = args; } /** * Set the specific visitors to use */ public void setVisitors(String commaSeperatedString) { this.visitors = commaSeperatedString; } /** * Set the specific visitors to use */ public void setOmitVisitors(String commaSeperatedString) { this.omitVisitors = commaSeperatedString; } /** * Set the home directory into which findbugs was installed */ public void setHome(File homeDir) { this.homeDir = homeDir; } /** * Set the output format */ public void setOutput(String format) { this.outputFormat = format; } /** * Set the report level */ public void setReportLevel(String level) { this.reportLevel = level; } /** * Set the sorted flag */ public void setSort(boolean flag) { this.sorted = flag; } /** * Set the quietError flag */ public void setQuietErrors(boolean flag) { this.quietErrors = flag; } /** * Set the debug flag */ public void setDebug(boolean flag) { this.debug = flag; } /** * Set the exclude filter file */ public void setExcludeFilter(File filterFile) { this.excludeFile = filterFile; } /** * Set the exclude filter file */ public void setIncludeFilter(File filterFile) { this.includeFile = filterFile; } /** * Set the project file */ public void setProjectFile(File projectFile) { this.projectFile = projectFile; } /** * the auxclasspath to use. */ public void setAuxClasspath(Path src) { if (auxClasspath == null) { auxClasspath = src; } else { auxClasspath.append(src); } } /** * Path to use for auxclasspath. */ public Path createAuxClasspath() { if (auxClasspath == null) { auxClasspath = new Path(project); } return auxClasspath.createPath(); } /** * Adds a reference to a auxclasspath defined elsewhere. */ public void setAuxClasspathRef(Reference r) { createAuxClasspath().setRefid(r); } /** * Add a class location */ public ClassLocation createClass() { ClassLocation cl = new ClassLocation(); classLocations.add( cl ); return cl; } public void execute() throws BuildException { checkParameters(); execFindbugs(); } /** * Check that all required attributes have been set * * @since Ant 1.5 */ private void checkParameters() { if ( homeDir == null ) { throw new BuildException( "home attribute must be defined for task <" + getTaskName() + "/>", getLocation() ); } if ( projectFile == null && classLocations.size() == 0 ) { throw new BuildException( "either projectfile or <class/> child " + "elements must be defined for task <" + getTaskName() + "/>", getLocation() ); } if ( outputFormat != null && !( outputFormat.trim().equalsIgnoreCase("xml" ) || outputFormat.trim().equalsIgnoreCase("text" ) ) ) { throw new BuildException( "output attribute must be either " + "'text' or 'xml' for task <" + getTaskName() + "/>", getLocation() ); } if ( reportLevel != null && !( reportLevel.trim().equalsIgnoreCase("low" ) || reportLevel.trim().equalsIgnoreCase("medium" ) || reportLevel.trim().equalsIgnoreCase("high" ) ) ) { throw new BuildException( "reportlevel attribute must be either " + "'low' or 'medium' or 'high' for task <" + getTaskName() + "/>", getLocation() ); } } /** * Create a new JVM to do the work. * * @since Ant 1.5 */ private void execFindbugs() throws BuildException { Java findbugsEngine = (Java) project.createTask("java"); findbugsEngine.setTaskName( getTaskName() ); findbugsEngine.setFork( true ); findbugsEngine.setDir( new File(homeDir + File.separator + "lib")); findbugsEngine.setJar( new File( homeDir + File.separator + "lib" + File.separator + FINDBUGS_JAR ) ); findbugsEngine.setTimeout( new Long( TIMEOUT ) ); findbugsEngine.createJvmarg().setLine( jvmargs ); StringBuffer sb = new StringBuffer( 1024 ); sb.append( "-home " + homeDir ); if ( debug ) sb.append( " -debug"); if ( sorted ) sb.append( " -sortByClass"); if ( outputFormat != null && outputFormat.trim().equalsIgnoreCase("xml") ) { sb.append( " -xml"); } if ( quietErrors ) sb.append( " -quiet" ); if ( reportLevel != null ) sb.append( " -" + reportLevel.trim().toLowerCase() ); if ( projectFile != null ) sb.append( " -project " + projectFile ); if ( excludeFile != null) sb.append( " -exclude " + excludeFile ); if ( includeFile != null) sb.append( " -include " + includeFile ); if ( visitors != null) sb.append( " -visitors " + visitors ); if ( omitVisitors != null ) sb.append( " -omitvisitors " + omitVisitors ); if ( auxClasspath != null ) sb.append( " -auxclasspath " + auxClasspath ); sb.append( " -exitcode" ); Iterator itr = classLocations.iterator(); while ( itr.hasNext() ) { sb.append( " " + itr.next().toString() ); } findbugsEngine.createArg().setLine( sb.toString() ); if ( findbugsEngine.executeJava() != 0 ) { throw new BuildException("Execution of findbugs failed."); } } } // vim:ts=4
package edu.umd.cs.findbugs.anttask; import edu.umd.cs.findbugs.ExitCodes; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; import org.apache.tools.ant.types.Path; import org.apache.tools.ant.types.Reference; import org.apache.tools.ant.taskdefs.Java; import java.io.File; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * FindBugs in Java class files. This task can take the following * arguments: * <ul> * <li>auxClasspath (classpath or classpathRef) * <li>home (findbugs install dir) * <li>quietErrors (boolean - default false) * <li>failOnError (boolean - default false) * <li>reportLevel (enum low|medium|high) * <li>sort (boolean default true) * <li>debug (boolean default false) * <li>output (enum text|xml - default xml) * <li>outputFile (name of output file to create) * <li>visitors (collection - comma seperated) * <li>omitVisitors (collection - comma seperated) * <li>excludeFilter (filter filename) * <li>includeFilter (filter filename) * <li>projectFile (project filename) * <li>jvmargs (any additional jvm arguments) * <li>classpath (classpath for running FindBugs) * <li>pluginList (list of plugin Jar files to load) * <li>systemProperty (a system property to set) * <li>workHard (boolean default false) * </ul> * Of these arguments, the <b>home</b> is required. * <b>projectFile</b> is required if nested &lt;class&gt; are not * specified. the &lt;class&gt; tag defines the location of either a * class, jar file, zip file, or directory containing classes * <p> * * @author Mike Fagan <a href="mailto:mfagan@tde.com">mfagan@tde.com</a> * * @version $Revision: 1.25 $ * * @since Ant 1.5 * * @ant.task category="utility" */ public class FindBugsTask extends Task { private static final String FINDBUGS_JAR = "findbugs.jar"; private static final long DEFAULT_TIMEOUT = 600000; // ten minutes private boolean debug = false; private boolean conserveSpace = false; private boolean sorted = true; private boolean quietErrors = false; private boolean failOnError = false; private boolean workHard = false; private File homeDir = null; private File projectFile = null; private File excludeFile = null; private File includeFile = null; private Path auxClasspath = null; private Path sourcePath = null; private String outputFormat = "xml"; private String reportLevel = null; private String jvmargs = ""; private String visitors = null; private String omitVisitors = null; private String outputFileName = null; private List classLocations = new ArrayList(); private long timeout = DEFAULT_TIMEOUT; private Path classpath = null; private Path pluginList = null; private List systemPropertyList = new ArrayList(); private Java findbugsEngine = null; //define the inner class to store class locations public class ClassLocation { File classLocation = null; public void setLocation( File location ) { classLocation = location; } public File getLocation( ) { return classLocation; } public String toString( ) { return classLocation!=null?classLocation.toString():""; } } // A System property to set when FindBugs is run public class SystemProperty { private String name; private String value; public SystemProperty() { } public void setName(String name) { this.name = name; } public void setValue(String value) { this.value = value; } public String getName() { return name; } public String getValue() { return value; } } /** * Set any specific jvm args */ public void setJvmargs(String args) { this.jvmargs = args; } /** * Set the workHard flag. * * @param workHard true if we want findbugs to run with workHard option enabled */ public void setWorkHard(boolean workHard){ this.workHard = workHard; } /** * Set the specific visitors to use */ public void setVisitors(String commaSeperatedString) { this.visitors = commaSeperatedString; } /** * Set the specific visitors to use */ public void setOmitVisitors(String commaSeperatedString) { this.omitVisitors = commaSeperatedString; } /** * Set the home directory into which findbugs was installed */ public void setHome(File homeDir) { this.homeDir = homeDir; } /** * Set the output format */ public void setOutput(String format) { this.outputFormat = format; } /** * Set the report level */ public void setReportLevel(String level) { this.reportLevel = level; } /** * Set the sorted flag */ public void setSort(boolean flag) { this.sorted = flag; } /** * Set the quietErrors flag */ public void setQuietErrors(boolean flag) { this.quietErrors = flag; } /** * Set the failOnError flag */ public void setFailOnError(boolean flag) { this.failOnError = flag; } /** * Set the debug flag */ public void setDebug(boolean flag) { this.debug = flag; } /** * Set the conserveSpace flag. */ public void setConserveSpace(boolean flag) { this.conserveSpace = flag; } /** * Set the exclude filter file */ public void setExcludeFilter(File filterFile) { this.excludeFile = filterFile; } /** * Set the exclude filter file */ public void setIncludeFilter(File filterFile) { this.includeFile = filterFile; } /** * Set the project file */ public void setProjectFile(File projectFile) { this.projectFile = projectFile; } /** * the auxclasspath to use. */ public void setAuxClasspath(Path src) { if (auxClasspath == null) { auxClasspath = src; } else { auxClasspath.append(src); } } /** * Path to use for auxclasspath. */ public Path createAuxClasspath() { if (auxClasspath == null) { auxClasspath = new Path(project); } return auxClasspath.createPath(); } /** * Adds a reference to a sourcepath defined elsewhere. */ public void setAuxClasspathRef(Reference r) { createAuxClasspath().setRefid(r); } /** * the sourcepath to use. */ public void setSourcePath(Path src) { if (sourcePath == null) { sourcePath = src; } else { sourcePath.append(src); } } /** * Path to use for sourcepath. */ public Path createSourcePath() { if (sourcePath == null) { sourcePath = new Path(project); } return sourcePath.createPath(); } /** * Adds a reference to a source path defined elsewhere. */ public void setSourcePathRef(Reference r) { createSourcePath().setRefid(r); } /** * Add a class location */ public ClassLocation createClass() { ClassLocation cl = new ClassLocation(); classLocations.add( cl ); return cl; } /** * Set name of output file. */ public void setOutputFile(String outputFileName) { this.outputFileName = outputFileName; } /** * Set timeout in milliseconds. * @param timeout the timeout */ public void setTimeout(long timeout) { this.timeout = timeout; } public void execute() throws BuildException { checkParameters(); try { execFindbugs(); } catch (BuildException e) { if (failOnError) { throw e; } } } /** * the classpath to use. */ public void setClasspath(Path src) { if (classpath == null) { classpath = src; } else { classpath.append(src); } } /** * Path to use for classpath. */ public Path createClasspath() { if (classpath == null) { classpath = new Path(project); } return classpath.createPath(); } /** * Adds a reference to a classpath defined elsewhere. */ public void setClasspathRef(Reference r) { createClasspath().setRefid(r); } /** * the plugin list to use. */ public void setPluginList(Path src) { if (pluginList == null) { pluginList = src; } else { pluginList.append(src); } } /** * Path to use for plugin list. */ public Path createPluginList() { if (pluginList == null) { pluginList = new Path(project); } return pluginList.createPath(); } /** * Adds a reference to a plugin list defined elsewhere. */ public void setPluginListRef(Reference r) { createPluginList().setRefid(r); } /** * Create a SystemProperty (to handle &lt;systemProperty&gt; elements). */ public SystemProperty createSystemProperty() { SystemProperty systemProperty = new SystemProperty(); systemPropertyList.add(systemProperty); return systemProperty; } /** * Check that all required attributes have been set * * @since Ant 1.5 */ private void checkParameters() { if ( homeDir == null && (classpath == null || pluginList == null) ) { throw new BuildException( "either home attribute or " + "classpath and pluginList attributes " + " must be defined for task <" + getTaskName() + "/>", getLocation() ); } if (pluginList != null) { // Make sure that all plugins are actually Jar files. String[] pluginFileList = pluginList.list(); for (int i = 0; i < pluginFileList.length; ++i) { String pluginFile = pluginFileList[i]; if (!pluginFile.endsWith(".jar")) { throw new BuildException("plugin file " + pluginFile + " is not a Jar file " + "in task <" + getTaskName() + "/>", getLocation()); } } } if ( projectFile == null && classLocations.size() == 0 ) { throw new BuildException( "either projectfile or <class/> child " + "elements must be defined for task <" + getTaskName() + "/>", getLocation() ); } if ( outputFormat != null && !( outputFormat.trim().equalsIgnoreCase("xml" ) || outputFormat.trim().equalsIgnoreCase("text" ) || outputFormat.trim().equalsIgnoreCase("xdocs" ) || outputFormat.trim().equalsIgnoreCase("emacs") ) ) { throw new BuildException( "output attribute must be either " + "'text', 'xml', 'xdocs' or 'emacs' for task <" + getTaskName() + "/>", getLocation() ); } if ( reportLevel != null && !( reportLevel.trim().equalsIgnoreCase("low" ) || reportLevel.trim().equalsIgnoreCase("medium" ) || reportLevel.trim().equalsIgnoreCase("high" ) ) ) { throw new BuildException( "reportlevel attribute must be either " + "'low' or 'medium' or 'high' for task <" + getTaskName() + "/>", getLocation() ); } if ( excludeFile != null && includeFile != null ) { throw new BuildException("only one of excludeFile and includeFile " + " attributes may be used in task <" + getTaskName() + "/>", getLocation()); } for (Iterator i = systemPropertyList.iterator(); i.hasNext(); ) { SystemProperty systemProperty = (SystemProperty) i.next(); if (systemProperty.getName() == null || systemProperty.getValue() == null) throw new BuildException("systemProperty elements must have name and value attributes"); } } /** * Add an argument to the JVM used to execute FindBugs. * @param arg the argument */ private void addArg(String arg) { findbugsEngine.createArg().setValue(arg); } /** * Create a new JVM to do the work. * * @since Ant 1.5 */ private void execFindbugs() throws BuildException { findbugsEngine = (Java) project.createTask("java"); findbugsEngine.setTaskName( getTaskName() ); findbugsEngine.setFork( true ); findbugsEngine.setTimeout( new Long( timeout ) ); if ( workHard ){ jvmargs = jvmargs + " -Dfindbugs.workHard=true"; } if ( debug ) jvmargs = jvmargs + " -Dfindbugs.debug=true"; if ( conserveSpace ) jvmargs = jvmargs + " -Dfindbugs.conserveSpace=true"; findbugsEngine.createJvmarg().setLine( jvmargs ); // Add JVM arguments for system properties for (Iterator i = systemPropertyList.iterator(); i.hasNext(); ) { SystemProperty systemProperty = (SystemProperty) i.next(); String jvmArg = "-D" + systemProperty.getName() + "=" + systemProperty.getValue(); findbugsEngine.createJvmarg().setValue(jvmArg); } if (homeDir != null) { // Use findbugs.home to locate findbugs.jar and the standard // plugins. This is the usual means of initialization. findbugsEngine.setJar( new File( homeDir + File.separator + "lib" + File.separator + FINDBUGS_JAR ) ); addArg("-home"); addArg(homeDir.getPath()); } else { // Use an explicitly specified classpath and list of plugin Jars // to initialize. This is useful for other tools which may have // FindBugs installed using a non-standard directory layout. findbugsEngine.setClasspath(classpath); findbugsEngine.setClassname("edu.umd.cs.findbugs.FindBugs"); addArg("-pluginList"); addArg(pluginList.toString()); } if ( sorted ) addArg("-sortByClass"); if ( outputFormat != null && !outputFormat.trim().equalsIgnoreCase("text") ) { addArg("-" + outputFormat.trim().toLowerCase()); } if ( quietErrors ) addArg("-quiet"); if ( reportLevel != null ) addArg("-" + reportLevel.trim().toLowerCase()); if ( projectFile != null ) { addArg("-project"); addArg(projectFile.getPath()); } if ( excludeFile != null ) { addArg("-exclude"); addArg(excludeFile.getPath()); } if ( includeFile != null) { addArg("-include"); addArg(includeFile.getPath()); } if ( visitors != null) { addArg("-visitors"); addArg(visitors); } if ( omitVisitors != null ) { addArg("-omitVisitors"); addArg(omitVisitors); } if ( auxClasspath != null ) { addArg("-auxclasspath"); addArg(auxClasspath.toString()); } if ( sourcePath != null) { addArg("-sourcepath"); addArg(sourcePath.toString()); } if ( outputFileName != null ) { addArg("-outputFile"); addArg(outputFileName); } addArg("-exitcode"); Iterator itr = classLocations.iterator(); while ( itr.hasNext() ) { addArg(itr.next().toString()); } log("Running FindBugs..."); int rc = findbugsEngine.executeJava(); if ((rc & ExitCodes.ERROR_FLAG) != 0) { throw new BuildException("Execution of findbugs failed."); } if ((rc & ExitCodes.MISSING_CLASS_FLAG) != 0) { log("Classes needed for analysis were missing"); } if (outputFileName != null) { log("Output saved to " + outputFileName); } } } // vim:ts=4
package test.http.router.handler; import com.firefly.client.http2.*; import com.firefly.codec.http2.frame.SettingsFrame; import com.firefly.codec.http2.model.*; import com.firefly.codec.http2.stream.HTTP2Configuration; import com.firefly.codec.http2.stream.HTTPConnection; import com.firefly.codec.http2.stream.HTTPOutputStream; import com.firefly.server.http2.HTTP2Server; import com.firefly.server.http2.ServerHTTPHandler; import com.firefly.utils.concurrent.FuturePromise; import com.firefly.utils.io.BufferUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.Phaser; import static com.firefly.utils.io.BufferUtils.toBuffer; import static org.hamcrest.Matchers.is; /** * @author Pengtao Qiu */ public class TestH2cUpgrade extends AbstractHTTPHandlerTest { @Test public void test() throws Exception { Phaser phaser = new Phaser(5); HTTP2Server server = createServer(); HTTP2Client client = createClient(phaser); phaser.arriveAndAwaitAdvance(); server.stop(); client.stop(); } private static class TestH2cHandler extends ClientHTTPHandler.Adapter { protected final ByteBuffer[] buffers; protected final List<ByteBuffer> contentList = new ArrayList<>(); public TestH2cHandler() { buffers = null; } public TestH2cHandler(ByteBuffer[] buffers) { this.buffers = buffers; } @Override public void continueToSendData(MetaData.Request request, MetaData.Response response, HTTPOutputStream output, HTTPConnection connection) { System.out.println("client received 100 continue"); if (buffers != null) { System.out.println("buffers: " + buffers.length); try (HTTPOutputStream out = output) { for (ByteBuffer buf : buffers) { out.write(buf); } } catch (IOException e) { e.printStackTrace(); } System.out.println("client sends buffers completely"); } } @Override public boolean content(ByteBuffer item, MetaData.Request request, MetaData.Response response, HTTPOutputStream output, HTTPConnection connection) { System.out.println("client received data: " + BufferUtils.toUTF8String(item)); contentList.add(item); return false; } @Override public boolean headerComplete(MetaData.Request request, MetaData.Response response, HTTPOutputStream output, HTTPConnection connection) { System.out.println("client received response: " + response); return false; } } private HTTP2Client createClient(Phaser phaser) throws Exception { final HTTP2Configuration http2Configuration = new HTTP2Configuration(); http2Configuration.setFlowControlStrategy("simple"); http2Configuration.getTcpConfiguration().setTimeout(60 * 1000); HTTP2Client client = new HTTP2Client(http2Configuration); FuturePromise<HTTPClientConnection> promise = new FuturePromise<>(); client.connect(host, port, promise); final HTTPClientConnection httpConnection = promise.get(); HTTPClientRequest request = new HTTPClientRequest("GET", "/index"); Map<Integer, Integer> settings = new HashMap<>(); settings.put(SettingsFrame.HEADER_TABLE_SIZE, http2Configuration.getMaxDynamicTableSize()); settings.put(SettingsFrame.INITIAL_WINDOW_SIZE, http2Configuration.getInitialStreamSendWindow()); SettingsFrame settingsFrame = new SettingsFrame(settings, false); FuturePromise<HTTP2ClientConnection> http2Promise = new FuturePromise<>(); httpConnection.upgradeHTTP2(request, settingsFrame, http2Promise, new TestH2cHandler() { @Override public boolean messageComplete(MetaData.Request request, MetaData.Response response, HTTPOutputStream output, HTTPConnection connection) { System.out.println("client System.out.println("client received frame: " + response.getStatus() + ", " + response.getReason()); System.out.println(response.getFields()); System.out.println("client Assert.assertThat(response.getStatus(), is(HttpStatus.SWITCHING_PROTOCOLS_101)); Assert.assertThat(response.getFields().get(HttpHeader.UPGRADE), is("h2c")); phaser.arrive(); return true; } }); HTTP2ClientConnection clientConnection = http2Promise.get(); HttpFields fields = new HttpFields(); fields.put(HttpHeader.USER_AGENT, "Firefly Client 1.0"); MetaData.Request post = new MetaData.Request("POST", HttpScheme.HTTP, new HostPortHttpField(host + ":" + port), "/data", HttpVersion.HTTP_1_1, fields); clientConnection.sendRequestWithContinuation(post, new TestH2cHandler(new ByteBuffer[]{ ByteBuffer.wrap("hello world!".getBytes("UTF-8")), ByteBuffer.wrap("big hello world!".getBytes("UTF-8"))}) { @Override public boolean messageComplete(MetaData.Request request, MetaData.Response response, HTTPOutputStream output, HTTPConnection connection) { try { return dataComplete(phaser, BufferUtils.toString(contentList), response); } catch (Exception e) { e.printStackTrace(); return true; } } }); fields = new HttpFields(); fields.put(HttpHeader.USER_AGENT, "Firefly Client 1.0"); MetaData.Request post2 = new MetaData.Request("POST", HttpScheme.HTTP, new HostPortHttpField(host + ":" + port), "/data", HttpVersion.HTTP_1_1, fields); clientConnection.send(post2, new ByteBuffer[]{ ByteBuffer.wrap("test data 2".getBytes("UTF-8")), ByteBuffer.wrap("finished test data 2".getBytes("UTF-8"))}, new TestH2cHandler() { @Override public boolean messageComplete(MetaData.Request request, MetaData.Response response, HTTPOutputStream output, HTTPConnection connection) { try { return dataComplete(phaser, BufferUtils.toString(contentList), response); } catch (Exception e) { e.printStackTrace(); return true; } } }); MetaData.Request get = new MetaData.Request("GET", HttpScheme.HTTP, new HostPortHttpField(host + ":" + port), "/test2", HttpVersion.HTTP_1_1, new HttpFields()); clientConnection.send(get, new TestH2cHandler() { @Override public boolean messageComplete(MetaData.Request request, MetaData.Response response, HTTPOutputStream output, HTTPConnection connection) { System.out.println("client System.out.println("client received frame: " + response.getStatus() + ", " + response.getReason()); System.out.println(response.getFields()); System.out.println("client Assert.assertThat(response.getStatus(), is(HttpStatus.NOT_FOUND_404)); phaser.arrive(); return true; } }); return client; } public boolean dataComplete(Phaser phaser, String content, MetaData.Response response) { System.out.println("client System.out.println("client received frame: " + response.getStatus() + ", " + response.getReason()); System.out.println(response.getFields()); System.out.println(content); System.out.println("client Assert.assertThat(response.getStatus(), is(HttpStatus.OK_200)); try { Assert.assertThat(content, is("Receive data stream successful. Thank you!")); } catch (Exception e) { e.printStackTrace(); } phaser.arrive(); return true; } private HTTP2Server createServer() { final HTTP2Configuration http2Configuration = new HTTP2Configuration(); http2Configuration.setFlowControlStrategy("simple"); http2Configuration.getTcpConfiguration().setTimeout(60 * 1000); HTTP2Server server = new HTTP2Server(host, port, http2Configuration, new ServerHTTPHandler.Adapter() { @Override public boolean accept100Continue(MetaData.Request request, MetaData.Response response, HTTPOutputStream output, HTTPConnection connection) { System.out.println("Server received expect continue "); return false; } @Override public boolean content(ByteBuffer item, MetaData.Request request, MetaData.Response response, HTTPOutputStream output, HTTPConnection connection) { System.out.println("Server received data: " + BufferUtils.toString(item, StandardCharsets.UTF_8)); return false; } @Override public boolean messageComplete(MetaData.Request request, MetaData.Response response, HTTPOutputStream outputStream, HTTPConnection connection) { HttpURI uri = request.getURI(); System.out.println("server System.out.println("Server message complete: " + uri.getPath()); System.out.println(request.getFields()); switch (uri.getPath()) { case "/index": response.setStatus(HttpStatus.Code.OK.getCode()); response.setReason(HttpStatus.Code.OK.getMessage()); try (HTTPOutputStream output = outputStream) { output.writeWithContentLength(toBuffer("receive initial stream successful", StandardCharsets.UTF_8)); } catch (IOException e) { e.printStackTrace(); } break; case "/data": response.setStatus(HttpStatus.Code.OK.getCode()); response.setReason(HttpStatus.Code.OK.getMessage()); try (HTTPOutputStream output = outputStream) { output.writeWithContentLength(new ByteBuffer[]{ toBuffer("Receive data stream successful. ", StandardCharsets.UTF_8), toBuffer("Thank you!", StandardCharsets.UTF_8) }); } catch (IOException e) { e.printStackTrace(); } break; default: response.setStatus(HttpStatus.Code.NOT_FOUND.getCode()); response.setReason(HttpStatus.Code.NOT_FOUND.getMessage()); try (HTTPOutputStream output = outputStream) { output.writeWithContentLength(toBuffer(uri.getPath() + " not found", StandardCharsets.UTF_8)); } catch (IOException e) { e.printStackTrace(); } break; } System.out.println("server return true; } }); server.start(); return server; } }
package org.zkoss.ganttz.data; import static java.util.Arrays.asList; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import org.apache.commons.lang.Validate; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jgrapht.DirectedGraph; import org.jgrapht.graph.SimpleDirectedGraph; import org.zkoss.ganttz.data.DependencyType.Point; import org.zkoss.ganttz.data.ITaskFundamentalProperties.IModifications; import org.zkoss.ganttz.data.ITaskFundamentalProperties.IUpdatablePosition; import org.zkoss.ganttz.data.constraint.Constraint; import org.zkoss.ganttz.data.constraint.ConstraintOnComparableValues; import org.zkoss.ganttz.data.constraint.ConstraintOnComparableValues.ComparisonType; import org.zkoss.ganttz.data.criticalpath.ICriticalPathCalculable; import org.zkoss.ganttz.util.IAction; import org.zkoss.ganttz.util.PreAndPostNotReentrantActionsWrapper; import org.zkoss.ganttz.util.ReentranceGuard; import org.zkoss.ganttz.util.ReentranceGuard.IReentranceCases; public class GanttDiagramGraph<V, D extends IDependency<V>> implements ICriticalPathCalculable<V> { private static final Log LOG = LogFactory.getLog(GanttDiagramGraph.class); public static IDependenciesEnforcerHook doNothingHook() { return new IDependenciesEnforcerHook() { @Override public void setNewEnd(GanttDate previousEnd, GanttDate newEnd) { } @Override public void setStartDate(GanttDate previousStart, GanttDate previousEnd, GanttDate newStart) { } }; } private static final GanttZKAdapter GANTTZK_ADAPTER = new GanttZKAdapter(); public static IAdapter<Task, Dependency> taskAdapter() { return GANTTZK_ADAPTER; } public interface IAdapter<V, D extends IDependency<V>> { List<V> getChildren(V task); V getOwner(V task); boolean isContainer(V task); void registerDependenciesEnforcerHookOn(V task, IDependenciesEnforcerHookFactory<V> hookFactory); GanttDate getStartDate(V task); void setStartDateFor(V task, GanttDate newStart); GanttDate getEndDateFor(V task); void setEndDateFor(V task, GanttDate newEnd); public List<Constraint<GanttDate>> getConstraints( ConstraintCalculator<V> calculator, Set<D> withDependencies, Point point); List<Constraint<GanttDate>> getStartConstraintsFor(V task); List<Constraint<GanttDate>> getEndConstraintsFor(V task); V getSource(D dependency); V getDestination(D dependency); Class<D> getDependencyType(); D createInvisibleDependency(V origin, V destination, DependencyType type); DependencyType getType(D dependency); boolean isVisible(D dependency); boolean isFixed(V task); } public static class GanttZKAdapter implements IAdapter<Task, Dependency> { @Override public List<Task> getChildren(Task task) { return task.getTasks(); } @Override public Task getOwner(Task task) { if (task instanceof Milestone) { Milestone milestone = (Milestone) task; return milestone.getOwner(); } return null; } @Override public Task getDestination(Dependency dependency) { return dependency.getDestination(); } @Override public Task getSource(Dependency dependency) { return dependency.getSource(); } @Override public boolean isContainer(Task task) { return task.isContainer(); } @Override public void registerDependenciesEnforcerHookOn(Task task, IDependenciesEnforcerHookFactory<Task> hookFactory) { task.registerDependenciesEnforcerHook(hookFactory); } @Override public Dependency createInvisibleDependency(Task origin, Task destination, DependencyType type) { return new Dependency(origin, destination, type, false); } @Override public Class<Dependency> getDependencyType() { return Dependency.class; } @Override public DependencyType getType(Dependency dependency) { return dependency.getType(); } @Override public boolean isVisible(Dependency dependency) { return dependency.isVisible(); } @Override public GanttDate getEndDateFor(Task task) { return task.getEndDate(); } @Override public void setEndDateFor(Task task, final GanttDate newEnd) { task.doPositionModifications(new IModifications() { @Override public void doIt(IUpdatablePosition position) { position.setEndDate(newEnd); } }); } @Override public GanttDate getStartDate(Task task) { return task.getBeginDate(); } @Override public void setStartDateFor(Task task, final GanttDate newStart) { task.doPositionModifications(new IModifications() { @Override public void doIt(IUpdatablePosition position) { position.setBeginDate(newStart); } }); } @Override public List<Constraint<GanttDate>> getConstraints( ConstraintCalculator<Task> calculator, Set<Dependency> withDependencies, Point pointBeingModified) { return Dependency.getConstraintsFor(calculator, withDependencies, pointBeingModified); } @Override public List<Constraint<GanttDate>> getStartConstraintsFor(Task task) { return task.getStartConstraints(); } @Override public List<Constraint<GanttDate>> getEndConstraintsFor(Task task) { return task.getEndConstraints(); } @Override public boolean isFixed(Task task) { return task.isFixed(); } } public static class GanttZKDiagramGraph extends GanttDiagramGraph<Task, Dependency> { private GanttZKDiagramGraph(boolean scheduleBackwards, List<Constraint<GanttDate>> globalStartConstraints, List<Constraint<GanttDate>> globalEndConstraints, boolean dependenciesConstraintsHavePriority) { super(scheduleBackwards, GANTTZK_ADAPTER, globalStartConstraints, globalEndConstraints, dependenciesConstraintsHavePriority); } } public interface IGraphChangeListener { public void execute(); } public static GanttZKDiagramGraph create(boolean scheduleBackwards, List<Constraint<GanttDate>> globalStartConstraints, List<Constraint<GanttDate>> globalEndConstraints, boolean dependenciesConstraintsHavePriority) { return new GanttZKDiagramGraph(scheduleBackwards, globalStartConstraints, globalEndConstraints, dependenciesConstraintsHavePriority); } private final IAdapter<V, D> adapter; private final DirectedGraph<V, D> graph; private final TopologicalSorter topologicalSorter; private List<V> topLevelTasks = new ArrayList<V>(); private Map<V, V> fromChildToParent = new HashMap<V, V>(); private final List<Constraint<GanttDate>> globalStartConstraints; private final List<Constraint<GanttDate>> globalEndConstraints; private final boolean scheduleBackwards; private DependenciesEnforcer enforcer = new DependenciesEnforcer(); private final boolean dependenciesConstraintsHavePriority; private final ReentranceGuard positionsUpdatingGuard = new ReentranceGuard(); private final PreAndPostNotReentrantActionsWrapper preAndPostActions = new PreAndPostNotReentrantActionsWrapper() { @Override protected void postAction() { executeGraphChangeListeners(new ArrayList<IGraphChangeListener>( postGraphChangeListeners)); } @Override protected void preAction() { executeGraphChangeListeners(new ArrayList<IGraphChangeListener>( preGraphChangeListeners)); } private void executeGraphChangeListeners(List<IGraphChangeListener> graphChangeListeners) { for (IGraphChangeListener each : graphChangeListeners) { try { each.execute(); } catch (Exception e) { LOG.error("error executing execution listener", e); } } } }; private List<IGraphChangeListener> preGraphChangeListeners = new ArrayList<IGraphChangeListener>(); private List<IGraphChangeListener> postGraphChangeListeners = new ArrayList<IGraphChangeListener>(); public void addPreGraphChangeListener(IGraphChangeListener preGraphChangeListener) { preGraphChangeListeners.add(preGraphChangeListener); } public void removePreGraphChangeListener(IGraphChangeListener preGraphChangeListener) { preGraphChangeListeners.remove(preGraphChangeListener); } public void addPostGraphChangeListener(IGraphChangeListener postGraphChangeListener) { postGraphChangeListeners.add(postGraphChangeListener); } public void removePostGraphChangeListener(IGraphChangeListener postGraphChangeListener) { postGraphChangeListeners.remove(postGraphChangeListener); } public void addPreChangeListeners( Collection<? extends IGraphChangeListener> preChangeListeners) { for (IGraphChangeListener each : preChangeListeners) { addPreGraphChangeListener(each); } } public void addPostChangeListeners( Collection<? extends IGraphChangeListener> postChangeListeners) { for (IGraphChangeListener each : postChangeListeners) { addPostGraphChangeListener(each); } } public static <V, D extends IDependency<V>> GanttDiagramGraph<V, D> create( boolean scheduleBackwards, IAdapter<V, D> adapter, List<Constraint<GanttDate>> globalStartConstraints, List<Constraint<GanttDate>> globalEndConstraints, boolean dependenciesConstraintsHavePriority) { return new GanttDiagramGraph<V, D>(scheduleBackwards, adapter, globalStartConstraints, globalEndConstraints, dependenciesConstraintsHavePriority); } protected GanttDiagramGraph(boolean scheduleBackwards, IAdapter<V, D> adapter, List<Constraint<GanttDate>> globalStartConstraints, List<Constraint<GanttDate>> globalEndConstraints, boolean dependenciesConstraintsHavePriority) { this.scheduleBackwards = scheduleBackwards; this.adapter = adapter; this.globalStartConstraints = globalStartConstraints; this.globalEndConstraints = globalEndConstraints; this.dependenciesConstraintsHavePriority = dependenciesConstraintsHavePriority; this.graph = new SimpleDirectedGraph<V, D>(adapter.getDependencyType()); this.topologicalSorter = new TopologicalSorter(); } public void enforceAllRestrictions() { enforcer.enforceRestrictionsOn(withoutVisibleIncomingDependencies(getTopLevelTasks())); } private List<V> withoutVisibleIncomingDependencies( Collection<? extends V> tasks) { List<V> result = new ArrayList<V>(); for (V each : tasks) { if (noVisibleDependencies(isScheduleForward() ? graph .incomingEdgesOf(each) : graph.outgoingEdgesOf(each))) { result.add(each); } } return result; } private boolean noVisibleDependencies(Collection<? extends D> dependencies) { for (D each : dependencies) { if (adapter.isVisible(each)) { return false; } } return true; } public void addTopLevel(V task) { topLevelTasks.add(task); addTask(task); } public void addTopLevel(Collection<? extends V> tasks) { for (V task : tasks) { addTopLevel(task); } } public void addTasks(Collection<? extends V> tasks) { for (V t : tasks) { addTask(t); } } class TopologicalSorter { private Map<TaskPoint, Integer> taskPointsByDepthCached = null; private Map<TaskPoint, Integer> taskPointsByDepth() { if (taskPointsByDepthCached != null) { return taskPointsByDepthCached; } Map<TaskPoint, Integer> result = new HashMap<TaskPoint, Integer>(); Map<TaskPoint, Set<TaskPoint>> visitedBy = new HashMap<TaskPoint, Set<TaskPoint>>(); Queue<TaskPoint> withoutIncoming = getInitial(withoutVisibleIncomingDependencies(getTopLevelTasks())); for (TaskPoint each : withoutIncoming) { initializeIfNeededForKey(result, each, 0); } while (!withoutIncoming.isEmpty()) { TaskPoint current = withoutIncoming.poll(); for (TaskPoint each : current.getImmediateSuccessors()) { initializeIfNeededForKey(visitedBy, each, new HashSet<TaskPoint>()); Set<TaskPoint> visitors = visitedBy.get(each); visitors.add(current); Set<TaskPoint> predecessorsRequired = each .getImmediatePredecessors(); if (visitors.containsAll(predecessorsRequired)) { initializeIfNeededForKey(result, each, result.get(current) + 1); withoutIncoming.offer(each); } } } return taskPointsByDepthCached = Collections .unmodifiableMap(result); } private <K, T> void initializeIfNeededForKey(Map<K, T> map, K key, T initialValue) { if (!map.containsKey(key)) { map.put(key, initialValue); } } private LinkedList<TaskPoint> getInitial(List<V> initial) { LinkedList<TaskPoint> result = new LinkedList<TaskPoint>(); for (V each : initial) { result.add(allPointsPotentiallyModified(each)); } return result; } public void recalculationNeeded() { taskPointsByDepthCached = null; } public List<Recalculation> sort( Collection<? extends Recalculation> recalculationsToBeSorted) { List<Recalculation> result = new ArrayList<Recalculation>( recalculationsToBeSorted); final Map<TaskPoint, Integer> taskPointsByDepth = taskPointsByDepth(); Collections.sort(result, new Comparator<Recalculation>() { @Override public int compare(Recalculation o1, Recalculation o2) { int o1Depth = onNullDefault( taskPointsByDepth.get(o1.taskPoint), Integer.MAX_VALUE, "no depth value for " + o1.taskPoint); int o2Depth = onNullDefault( taskPointsByDepth.get(o2.taskPoint), Integer.MAX_VALUE, "no depth value for " + o2.taskPoint); int result = o1Depth - o2Depth; if (result == 0) { return asInt(o1.parentRecalculation) - asInt(o2.parentRecalculation); } return result; } private int asInt(boolean b) { return b ? 1 : 0; } }); return result; } } private static <T> T onNullDefault(T value, T defaultValue, String warnMessage) { if (value == null) { if (warnMessage != null) { LOG.warn(warnMessage); } return defaultValue; } return value; } public void addTask(V original) { List<V> stack = new LinkedList<V>(); stack.add(original); List<D> dependenciesToAdd = new ArrayList<D>(); while (!stack.isEmpty()){ V task = stack.remove(0); graph.addVertex(task); topologicalSorter.recalculationNeeded(); adapter.registerDependenciesEnforcerHookOn(task, enforcer); if (adapter.isContainer(task)) { for (V child : adapter.getChildren(task)) { fromChildToParent.put(child, task); stack.add(0, child); dependenciesToAdd.add(adapter.createInvisibleDependency( child, task, DependencyType.END_END)); dependenciesToAdd.add(adapter.createInvisibleDependency( task, child, DependencyType.START_START)); } } else { V owner = adapter.getOwner(task); if(owner != null) { dependenciesToAdd.add(adapter.createInvisibleDependency( task, owner, DependencyType.END_END)); dependenciesToAdd.add(adapter.createInvisibleDependency( owner, task, DependencyType.START_START)); } } } for (D each : dependenciesToAdd) { add(each, false); } } public interface IDependenciesEnforcerHook { public void setStartDate(GanttDate previousStart, GanttDate previousEnd, GanttDate newStart); public void setNewEnd(GanttDate previousEnd, GanttDate newEnd); } public interface IDependenciesEnforcerHookFactory<T> { public IDependenciesEnforcerHook create(T task, INotificationAfterDependenciesEnforcement notification); public IDependenciesEnforcerHook create(T task); } public interface INotificationAfterDependenciesEnforcement { public void onStartDateChange(GanttDate previousStart, GanttDate previousEnd, GanttDate newStart); public void onEndDateChange(GanttDate previousEnd, GanttDate newEnd); } private static final INotificationAfterDependenciesEnforcement EMPTY_NOTIFICATOR = new INotificationAfterDependenciesEnforcement() { @Override public void onStartDateChange(GanttDate previousStart, GanttDate previousEnd, GanttDate newStart) { } @Override public void onEndDateChange(GanttDate previousEnd, GanttDate newEnd) { } }; public class DeferedNotifier { private Map<V, NotificationPendingForTask> notificationsPending = new LinkedHashMap<V, NotificationPendingForTask>(); public void add(V task, StartDateNofitication notification) { retrieveOrCreateFor(task).setStartDateNofitication(notification); } private NotificationPendingForTask retrieveOrCreateFor(V task) { NotificationPendingForTask result = notificationsPending.get(task); if (result == null) { result = new NotificationPendingForTask(); notificationsPending.put(task, result); } return result; } void add(V task, LengthNotification notification) { retrieveOrCreateFor(task).setLengthNofitication(notification); } public void doNotifications() { for (NotificationPendingForTask each : notificationsPending .values()) { each.doNotification(); } notificationsPending.clear(); } } private class NotificationPendingForTask { private StartDateNofitication startDateNofitication; private LengthNotification lengthNofitication; void setStartDateNofitication( StartDateNofitication startDateNofitication) { this.startDateNofitication = this.startDateNofitication == null ? startDateNofitication : this.startDateNofitication .coalesce(startDateNofitication); } void setLengthNofitication(LengthNotification lengthNofitication) { this.lengthNofitication = this.lengthNofitication == null ? lengthNofitication : this.lengthNofitication.coalesce(lengthNofitication); } void doNotification() { if (startDateNofitication != null) { startDateNofitication.doNotification(); } if (lengthNofitication != null) { lengthNofitication.doNotification(); } } } private class StartDateNofitication { private final INotificationAfterDependenciesEnforcement notification; private final GanttDate previousStart; private final GanttDate previousEnd; private final GanttDate newStart; public StartDateNofitication( INotificationAfterDependenciesEnforcement notification, GanttDate previousStart, GanttDate previousEnd, GanttDate newStart) { this.notification = notification; this.previousStart = previousStart; this.previousEnd = previousEnd; this.newStart = newStart; } public StartDateNofitication coalesce( StartDateNofitication startDateNofitication) { return new StartDateNofitication(notification, previousStart, previousEnd, startDateNofitication.newStart); } void doNotification() { notification .onStartDateChange(previousStart, previousEnd, newStart); } } private class LengthNotification { private final INotificationAfterDependenciesEnforcement notification; private final GanttDate previousEnd; private final GanttDate newEnd; public LengthNotification( INotificationAfterDependenciesEnforcement notification, GanttDate previousEnd, GanttDate newEnd) { this.notification = notification; this.previousEnd = previousEnd; this.newEnd = newEnd; } public LengthNotification coalesce(LengthNotification lengthNofitication) { return new LengthNotification(notification, previousEnd, lengthNofitication.newEnd); } void doNotification() { notification.onEndDateChange(previousEnd, newEnd); } } private class DependenciesEnforcer implements IDependenciesEnforcerHookFactory<V> { private ThreadLocal<DeferedNotifier> deferedNotifier = new ThreadLocal<DeferedNotifier>(); @Override public IDependenciesEnforcerHook create(V task, INotificationAfterDependenciesEnforcement notificator) { return onlyEnforceDependenciesOnEntrance(onEntrance(task), onNotification(task, notificator)); } @Override public IDependenciesEnforcerHook create(V task) { return create(task, EMPTY_NOTIFICATOR); } private IDependenciesEnforcerHook onEntrance(final V task) { return new IDependenciesEnforcerHook() { public void setStartDate(GanttDate previousStart, GanttDate previousEnd, GanttDate newStart) { taskPositionModified(task); } @Override public void setNewEnd(GanttDate previousEnd, GanttDate newEnd) { taskPositionModified(task); } }; } private IDependenciesEnforcerHook onNotification(final V task, final INotificationAfterDependenciesEnforcement notification) { return new IDependenciesEnforcerHook() { @Override public void setStartDate(GanttDate previousStart, GanttDate previousEnd, GanttDate newStart) { StartDateNofitication startDateNotification = new StartDateNofitication( notification, previousStart, previousEnd, newStart); deferedNotifier.get().add(task, startDateNotification); } @Override public void setNewEnd(GanttDate previousEnd, GanttDate newEnd) { LengthNotification lengthNotification = new LengthNotification( notification, previousEnd, newEnd); deferedNotifier.get().add(task, lengthNotification); } }; } private IDependenciesEnforcerHook onlyEnforceDependenciesOnEntrance( final IDependenciesEnforcerHook onEntrance, final IDependenciesEnforcerHook notification) { return new IDependenciesEnforcerHook() { @Override public void setStartDate(final GanttDate previousStart, final GanttDate previousEnd, final GanttDate newStart) { positionsUpdatingGuard .entranceRequested(new IReentranceCases() { @Override public void ifNewEntrance() { onNewEntrance(new IAction() { @Override public void doAction() { notification.setStartDate( previousStart, previousEnd, newStart); onEntrance.setStartDate( previousStart, previousEnd, newStart); } }); } @Override public void ifAlreadyInside() { notification.setStartDate(previousStart, previousEnd, newStart); } }); } @Override public void setNewEnd(final GanttDate previousEnd, final GanttDate newEnd) { positionsUpdatingGuard .entranceRequested(new IReentranceCases() { @Override public void ifNewEntrance() { onNewEntrance(new IAction() { @Override public void doAction() { notification.setNewEnd(previousEnd, newEnd); onEntrance.setNewEnd(previousEnd, newEnd); } }); } @Override public void ifAlreadyInside() { notification.setNewEnd(previousEnd, newEnd); } }); } }; } void enforceRestrictionsOn(Collection<? extends V> tasks) { List<Recalculation> allRecalculations = new ArrayList<Recalculation>(); for (V each : tasks) { allRecalculations.addAll(getRecalculationsNeededFrom(each)); } enforceRestrictionsOn(allRecalculations, tasks); } void enforceRestrictionsOn(V task) { enforceRestrictionsOn(getRecalculationsNeededFrom(task), Collections.singleton(task)); } void enforceRestrictionsOn(final List<Recalculation> recalculations, final Collection<? extends V> initiallyModified) { executeWithPreAndPostActionsOnlyIfNewEntrance(new IAction() { @Override public void doAction() { doRecalculations(recalculations, initiallyModified); } }); } private void executeWithPreAndPostActionsOnlyIfNewEntrance( final IAction action) { positionsUpdatingGuard.entranceRequested(new IReentranceCases() { @Override public void ifAlreadyInside() { action.doAction(); } @Override public void ifNewEntrance() { onNewEntrance(action); } }); } private void onNewEntrance(final IAction action) { preAndPostActions.doAction(decorateWithNotifications(action)); } private IAction decorateWithNotifications(final IAction action) { return new IAction() { @Override public void doAction() { deferedNotifier.set(new DeferedNotifier()); try { action.doAction(); } finally { DeferedNotifier notifier = deferedNotifier.get(); notifier.doNotifications(); deferedNotifier.set(null); } } }; } DeferedNotifier manualNotification(final IAction action) { final DeferedNotifier result = new DeferedNotifier(); positionsUpdatingGuard.entranceRequested(new IReentranceCases() { @Override public void ifAlreadyInside() { throw new RuntimeException("it cannot do a manual notification if it's already inside"); } @Override public void ifNewEntrance() { preAndPostActions.doAction(new IAction() { @Override public void doAction() { deferedNotifier.set(result); try { action.doAction(); } finally { deferedNotifier.set(null); } } }); } }); return result; } private void taskPositionModified(final V task) { executeWithPreAndPostActionsOnlyIfNewEntrance(new IAction() { @Override public void doAction() { List<Recalculation> recalculationsNeededFrom = getRecalculationsNeededFrom(task); doRecalculations(recalculationsNeededFrom, Collections.singletonList(task)); } }); } private void doRecalculations(List<Recalculation> recalculationsNeeded, Collection<? extends V> initiallyModified) { Set<V> allModified = new HashSet<V>(); allModified.addAll(initiallyModified); for (Recalculation each : recalculationsNeeded) { boolean modified = each.doRecalculation(); if (modified) { allModified.add(each.taskPoint.task); } } List<V> shrunkContainers = shrunkContainersOfModified(allModified); for (V each : getTaskAffectedByShrinking(shrunkContainers)) { doRecalculations(getRecalculationsNeededFrom(each), Collections.singletonList(each)); } } private List<V> getTaskAffectedByShrinking(List<V> shrunkContainers) { List<V> tasksAffectedByShrinking = new ArrayList<V>(); for (V each : shrunkContainers) { for (D eachDependency : graph.outgoingEdgesOf(each)) { if (adapter.getType(eachDependency) == DependencyType.START_START && adapter.isVisible(eachDependency)) { tasksAffectedByShrinking.add(adapter .getDestination(eachDependency)); } } } return tasksAffectedByShrinking; } private List<V> shrunkContainersOfModified( Set<V> allModified) { Set<V> topmostToShrink = getTopMostThatCouldPotentiallyNeedShrinking(allModified); List<V> allToShrink = new ArrayList<V>(); for (V each : topmostToShrink) { allToShrink.addAll(getContainersBottomUp(each)); } List<V> result = new ArrayList<V>(); for (V each : allToShrink) { boolean modified = enforceParentShrinkage(each); if (modified) { result.add(each); } } return result; } private Set<V> getTopMostThatCouldPotentiallyNeedShrinking( Collection<V> modified) { Set<V> result = new HashSet<V>(); for (V each : modified) { V t = getTopmostFor(each); if (adapter.isContainer(t)) { result.add(t); } } return result; } private Collection<? extends V> getContainersBottomUp( V container) { List<V> result = new ArrayList<V>(); List<V> tasks = adapter.getChildren(container); for (V each : tasks) { if (adapter.isContainer(each)) { result.addAll(getContainersBottomUp(each)); result.add(each); } } result.add(container); return result; } boolean enforceParentShrinkage(V container) { GanttDate oldBeginDate = adapter.getStartDate(container); GanttDate firstStart = getSmallestBeginDateFromChildrenFor(container); GanttDate lastEnd = getBiggestEndDateFromChildrenFor(container); GanttDate previousEnd = adapter.getEndDateFor(container); if (firstStart.after(oldBeginDate) || previousEnd.after(lastEnd)) { adapter.setStartDateFor(container, GanttDate.max(firstStart, oldBeginDate)); adapter.setEndDateFor(container, GanttDate.min(lastEnd, previousEnd)); return true; } return false; } } private GanttDate getSmallestBeginDateFromChildrenFor(V container) { return Collections.min(getChildrenDates(container, Point.START)); } private GanttDate getBiggestEndDateFromChildrenFor(V container) { return Collections.max(getChildrenDates(container, Point.END)); } private List<GanttDate> getChildrenDates(V container, Point point) { List<V> children = adapter.getChildren(container); List<GanttDate> result = new ArrayList<GanttDate>(); if (children.isEmpty()) { result.add(getDateFor(container, point)); } for (V each : children) { result.add(getDateFor(each, point)); } return result; } GanttDate getDateFor(V task, Point point) { if (point.equals(Point.START)) { return adapter.getStartDate(task); } else { return adapter.getEndDateFor(task); } } List<Recalculation> getRecalculationsNeededFrom(V task) { List<Recalculation> result = new ArrayList<Recalculation>(); Set<Recalculation> parentRecalculationsAlreadyDone = new HashSet<Recalculation>(); Recalculation first = recalculationFor(allPointsPotentiallyModified(task)); first.couldHaveBeenModifiedBeforehand(); result.addAll(getParentsRecalculations(parentRecalculationsAlreadyDone, first.taskPoint)); result.add(first); Queue<Recalculation> pendingOfVisit = new LinkedList<Recalculation>(); pendingOfVisit.offer(first); Map<Recalculation, Recalculation> alreadyVisited = new HashMap<Recalculation, Recalculation>(); alreadyVisited.put(first, first); while (!pendingOfVisit.isEmpty()) { Recalculation current = pendingOfVisit.poll(); for (TaskPoint each : current.taskPoint.getImmediateSuccessors()) { if (each.isImmediatelyDerivedFrom(current.taskPoint)) { continue; } Recalculation recalculationToAdd = getRecalcualtionToAdd(each, alreadyVisited); recalculationToAdd.comesFromPredecessor(current); if (!alreadyVisited.containsKey(recalculationToAdd)) { result.addAll(getParentsRecalculations( parentRecalculationsAlreadyDone, each)); result.add(recalculationToAdd); pendingOfVisit.offer(recalculationToAdd); alreadyVisited.put(recalculationToAdd, recalculationToAdd); } } } return topologicalSorter.sort(result); } private Recalculation getRecalcualtionToAdd(TaskPoint taskPoint, Map<Recalculation, Recalculation> alreadyVisited) { Recalculation result = recalculationFor(taskPoint); if (alreadyVisited.containsKey(result)) { return alreadyVisited.get(result); } else { return result; } } private List<Recalculation> getParentsRecalculations( Set<Recalculation> parentRecalculationsAlreadyDone, TaskPoint taskPoint) { List<Recalculation> result = new ArrayList<Recalculation>(); for (TaskPoint eachParent : parentsRecalculationsNeededFor(taskPoint)) { Recalculation parentRecalculation = parentRecalculation(eachParent.task); if (!parentRecalculationsAlreadyDone .contains(parentRecalculation)) { parentRecalculationsAlreadyDone.add(parentRecalculation); result.add(parentRecalculation); } } return result; } private Set<TaskPoint> parentsRecalculationsNeededFor(TaskPoint current) { Set<TaskPoint> result = new LinkedHashSet<TaskPoint>(); if (current.areAllPointsPotentiallyModified()) { List<V> path = fromTaskToTop(current.task); if (path.size() > 1) { path = path.subList(1, path.size()); Collections.reverse(path); result.addAll(asBothPoints(path)); } } return result; } private Collection<? extends TaskPoint> asBothPoints(List<V> parents) { List<TaskPoint> result = new ArrayList<TaskPoint>(); for (V each : parents) { result.add(allPointsPotentiallyModified(each)); } return result; } private List<V> fromTaskToTop(V task) { List<V> result = new ArrayList<V>(); V current = task; while (current != null) { result.add(current); current = fromChildToParent.get(current); } return result; } private Recalculation parentRecalculation(V task) { return new Recalculation(allPointsPotentiallyModified(task), true); } private Recalculation recalculationFor(TaskPoint taskPoint) { return new Recalculation(taskPoint, false); } private class Recalculation { private final boolean parentRecalculation; private final TaskPoint taskPoint; private Set<Recalculation> recalculationsCouldAffectThis = new HashSet<Recalculation>(); private boolean recalculationCalled = false; private boolean dataPointModified = false; private boolean couldHaveBeenModifiedBeforehand = false; Recalculation(TaskPoint taskPoint, boolean isParentRecalculation) { Validate.notNull(taskPoint); this.taskPoint = taskPoint; this.parentRecalculation = isParentRecalculation; } public void couldHaveBeenModifiedBeforehand() { couldHaveBeenModifiedBeforehand = true; } public void comesFromPredecessor(Recalculation predecessor) { recalculationsCouldAffectThis.add(predecessor); } boolean doRecalculation() { recalculationCalled = true; dataPointModified = haveToDoCalculation() && taskChangesPosition(); return dataPointModified; } private boolean haveToDoCalculation() { return recalculationsCouldAffectThis.isEmpty() || predecessorsHaveBeenModified(); } private boolean predecessorsHaveBeenModified() { for (Recalculation each : recalculationsCouldAffectThis) { if (!each.recalculationCalled) { throw new RuntimeException( "the predecessor must be called first"); } if (each.dataPointModified || each.couldHaveBeenModifiedBeforehand) { return true; } } return false; } private boolean taskChangesPosition() { ChangeTracker tracker = trackTaskChanges(); Constraint.initialValue(noRestrictions()) .withConstraints(getConstraintsToApply()) .apply(); return tracker.taskHasChanged(); } @SuppressWarnings("unchecked") private List<Constraint<PositionRestrictions>> getConstraintsToApply() { Constraint<PositionRestrictions> weakForces = scheduleBackwards ? new WeakForwardForces() : new WeakBackwardsForces(); Constraint<PositionRestrictions> dominatingForces = scheduleBackwards ? new DominatingBackwardForces() : new DominatingForwardForces(); if (dependenciesConstraintsHavePriority) { return asList(weakForces, dominatingForces); } else { return asList(weakForces, dominatingForces, weakForces); } } abstract class PositionRestrictions { private final GanttDate start; private final GanttDate end; PositionRestrictions(GanttDate start, GanttDate end) { this.start = start; this.end = end; } GanttDate getStart() { return start; } GanttDate getEnd() { return end; } abstract List<Constraint<GanttDate>> getStartConstraints(); abstract List<Constraint<GanttDate>> getEndConstraints(); abstract boolean satisfies(PositionRestrictions other); } private final class NoRestrictions extends PositionRestrictions { public NoRestrictions(TaskPoint taskPoint) { super(adapter.getStartDate(taskPoint.task), adapter .getEndDateFor(taskPoint.task)); } @Override List<Constraint<GanttDate>> getStartConstraints() { return Collections.emptyList(); } @Override List<Constraint<GanttDate>> getEndConstraints() { return Collections.emptyList(); } @Override boolean satisfies(PositionRestrictions restrictions) { return true; } } PositionRestrictions noRestrictions() { return new NoRestrictions(taskPoint); } DatesBasedPositionRestrictions biggerThan(GanttDate start, GanttDate end) { ComparisonType type = isScheduleForward() ? ComparisonType.BIGGER_OR_EQUAL_THAN : ComparisonType.BIGGER_OR_EQUAL_THAN_LEFT_FLOATING; return new DatesBasedPositionRestrictions(type, start, end); } DatesBasedPositionRestrictions lessThan(GanttDate start, GanttDate end) { ComparisonType type = isScheduleForward() ? ComparisonType.LESS_OR_EQUAL_THAN_RIGHT_FLOATING : ComparisonType.LESS_OR_EQUAL_THAN; return new DatesBasedPositionRestrictions(type, start, end); } class DatesBasedPositionRestrictions extends PositionRestrictions { private Constraint<GanttDate> startConstraint; private Constraint<GanttDate> endConstraint; public DatesBasedPositionRestrictions( ComparisonType comparisonType, GanttDate start, GanttDate end) { super(start, end); this.startConstraint = ConstraintOnComparableValues .instantiate(comparisonType, start); this.endConstraint = ConstraintOnComparableValues.instantiate( comparisonType, end); } boolean satisfies(PositionRestrictions other) { if (DatesBasedPositionRestrictions.class.isInstance(other)) { return satisfies(DatesBasedPositionRestrictions.class .cast(other)); } return false; } private boolean satisfies(DatesBasedPositionRestrictions other) { return startConstraint.isSatisfiedBy(other.getStart()) && endConstraint.isSatisfiedBy(other.getEnd()); } @Override List<Constraint<GanttDate>> getStartConstraints() { return Collections.singletonList(startConstraint); } @Override List<Constraint<GanttDate>> getEndConstraints() { return Collections.singletonList(endConstraint); } } class ChangeTracker { private GanttDate start; private GanttDate end; private final V task; public ChangeTracker(V task) { this.task = task; this.start = adapter.getStartDate(task); this.end = adapter.getEndDateFor(task); } public boolean taskHasChanged() { return areNotEqual(adapter.getStartDate(task), this.start) || areNotEqual(adapter.getEndDateFor(task), this.end); } } boolean areNotEqual(GanttDate a, GanttDate b) { return a != b && a.compareTo(b) != 0; } protected ChangeTracker trackTaskChanges() { return new ChangeTracker(taskPoint.task); } abstract class Forces extends Constraint<PositionRestrictions> { protected final V task; public Forces() { this.task = taskPoint.task; } private PositionRestrictions resultingRestrictions = noRestrictions(); protected PositionRestrictions applyConstraintTo( PositionRestrictions restrictions) { if (adapter.isFixed(task)) { return restrictions; } resultingRestrictions = enforceUsingPreviousRestrictions(restrictions); return resultingRestrictions; } public boolean isSatisfiedBy(PositionRestrictions value) { return resultingRestrictions.satisfies(value); } public void checkSatisfiesResult(PositionRestrictions finalResult) { super.checkSatisfiesResult(finalResult); checkStartConstraints(finalResult.getStart()); checkEndConstraints(finalResult.getEnd()); } private void checkStartConstraints(GanttDate finalStart) { Constraint .checkSatisfyResult(getStartConstraints(), finalStart); } private void checkEndConstraints(GanttDate finalEnd) { Constraint.checkSatisfyResult(getEndConstraints(), finalEnd); } abstract List<Constraint<GanttDate>> getStartConstraints(); abstract List<Constraint<GanttDate>> getEndConstraints(); abstract PositionRestrictions enforceUsingPreviousRestrictions( PositionRestrictions restrictions); } abstract class Dominating extends Forces { private final Point primary; private final Point secondary; public Dominating(Point primary, Point secondary) { Validate.isTrue(isSupportedPoint(primary)); Validate.isTrue(isSupportedPoint(secondary)); Validate.isTrue(!primary.equals(secondary)); this.primary = primary; this.secondary = secondary; } private boolean isSupportedPoint(Point point) { EnumSet<Point> validPoints = EnumSet.of(Point.START, Point.END); return validPoints.contains(point); } private Point getPrimaryPoint() { return primary; } private Point getSecondaryPoint() { return secondary; } @Override PositionRestrictions enforceUsingPreviousRestrictions( PositionRestrictions restrictions) { if (parentRecalculation) { // avoid interference from task containers shrinking return enforcePrimaryPoint(restrictions); } else if (taskPoint.areAllPointsPotentiallyModified()) { return enforceBoth(restrictions); } else if (taskPoint.somePointPotentiallyModified()) { return enforceSecondaryPoint(restrictions); } return restrictions; } private PositionRestrictions enforceBoth( PositionRestrictions restrictions) { ChangeTracker changeTracker = trackTaskChanges(); PositionRestrictions currentRestrictions = enforcePrimaryPoint(restrictions); if (changeTracker.taskHasChanged() || parentRecalculation || couldHaveBeenModifiedBeforehand) { return enforceSecondaryPoint(currentRestrictions); } return currentRestrictions; } private PositionRestrictions enforcePrimaryPoint( PositionRestrictions originalRestrictions) { GanttDate newDominatingPointDate = calculatePrimaryPointDate(originalRestrictions); return enforceRestrictionsFor(primary, newDominatingPointDate); } /** * Calculates the new date for the primary point based on the * present constraints. If there are no constraints this method will * return the existent commanding point date * @param originalRestrictions */ private GanttDate calculatePrimaryPointDate( PositionRestrictions originalRestrictions) { GanttDate newDate = Constraint .<GanttDate> initialValue(null) .withConstraints( getConstraintsFrom(originalRestrictions, getPrimaryPoint())) .withConstraints(getConstraintsFor(getPrimaryPoint())) .applyWithoutFinalCheck(); if (newDate == null) { return getTaskDateFor(getPrimaryPoint()); } return newDate; } private List<Constraint<GanttDate>> getConstraintsFor(Point point) { Validate.isTrue(isSupportedPoint(point)); switch (point) { case START: return getStartConstraints(); case END: return getEndConstraints(); default: throw new RuntimeException("shouldn't happen"); } } private PositionRestrictions enforceSecondaryPoint( PositionRestrictions restrictions) { GanttDate newSecondaryPointDate = calculateSecondaryPointDate(restrictions); if (newSecondaryPointDate == null) { return restrictions; } restrictions = enforceRestrictionsFor(getSecondaryPoint(), newSecondaryPointDate); if (taskPoint.onlyModifies(getSecondaryPoint())) { // primary point constraints could be the ones "commanding" // now GanttDate potentialPrimaryDate = calculatePrimaryPointDate(restrictions); if (!doSatisfyOrderCondition(potentialPrimaryDate, getTaskDateFor(getPrimaryPoint()))) { return enforceRestrictionsFor(getPrimaryPoint(), potentialPrimaryDate); } } return restrictions; } private GanttDate calculateSecondaryPointDate( PositionRestrictions restrictions) { GanttDate newEnd = Constraint .<GanttDate> initialValue(null) .withConstraints( getConstraintsFrom(restrictions, getSecondaryPoint())) .withConstraints(getConstraintsFor(getSecondaryPoint())) .applyWithoutFinalCheck(); return newEnd; } protected abstract boolean doSatisfyOrderCondition( GanttDate supposedlyBefore, GanttDate supposedlyAfter); private PositionRestrictions enforceRestrictionsFor(Point point, GanttDate newDate) { GanttDate old = getTaskDateFor(point); if (areNotEqual(old, newDate)) { setTaskDateFor(point, newDate); } return createRestrictionsFor(getTaskDateFor(Point.START), getTaskDateFor(Point.END)); } GanttDate getTaskDateFor(Point point) { Validate.isTrue(isSupportedPoint(point)); return getDateFor(task, point); } protected abstract PositionRestrictions createRestrictionsFor( GanttDate start, GanttDate end); private void setTaskDateFor(Point point, GanttDate date) { Validate.isTrue(isSupportedPoint(point)); switch (point) { case START: adapter.setStartDateFor(task, date); break; case END: adapter.setEndDateFor(task, date); } } private List<Constraint<GanttDate>> getConstraintsFrom( PositionRestrictions restrictions, Point point) { Validate.isTrue(isSupportedPoint(point)); switch (point) { case START: return restrictions.getStartConstraints(); case END: return restrictions.getEndConstraints(); default: throw new RuntimeException("shouldn't happen"); } } protected List<Constraint<GanttDate>> getConstraintsForPrimaryPoint() { List<Constraint<GanttDate>> result = new ArrayList<Constraint<GanttDate>>(); if (dependenciesConstraintsHavePriority) { result.addAll(getTaskConstraints(getPrimaryPoint())); result.addAll(getDependenciesConstraintsFor(getPrimaryPoint())); } else { result.addAll(getDependenciesConstraintsFor(getPrimaryPoint())); result.addAll(getTaskConstraints(getPrimaryPoint())); } result.addAll(getGlobalConstraintsToApply(getPrimaryPoint())); return result; } private Collection<Constraint<GanttDate>> getGlobalConstraintsToApply( Point point) { Validate.isTrue(isSupportedPoint(point)); switch (point) { case START: return globalStartConstraints; case END: return globalEndConstraints; default: throw new RuntimeException("shouldn't happen"); } } protected List<Constraint<GanttDate>> getConstraintsForSecondaryPoint() { return getDependenciesConstraintsFor(getSecondaryPoint()); } private List<Constraint<GanttDate>> getDependenciesConstraintsFor( Point point) { final Set<D> withDependencies = getDependenciesAffectingThisTask(); return adapter.getConstraints(getCalculator(), withDependencies, point); } protected abstract Set<D> getDependenciesAffectingThisTask(); private List<Constraint<GanttDate>> getTaskConstraints(Point point) { Validate.isTrue(isSupportedPoint(point)); switch (point) { case START: return adapter.getStartConstraintsFor(task); case END: return adapter.getEndConstraintsFor(task); default: throw new RuntimeException("shouldn't happen"); } } protected abstract ConstraintCalculator<V> getCalculator(); protected ConstraintCalculator<V> createNormalCalculator() { return createCalculator(false); } protected ConstraintCalculator<V> createBackwardsCalculator() { return createCalculator(true); } private ConstraintCalculator<V> createCalculator(boolean inverse) { return new ConstraintCalculator<V>(inverse) { @Override protected GanttDate getStartDate(V vertex) { return adapter.getStartDate(vertex); } @Override protected GanttDate getEndDate(V vertex) { return adapter.getEndDateFor(vertex); } }; } } class DominatingForwardForces extends Dominating { public DominatingForwardForces() { super(Point.START, Point.END); } @Override List<Constraint<GanttDate>> getStartConstraints() { return getConstraintsForPrimaryPoint(); } @Override List<Constraint<GanttDate>> getEndConstraints() { return getConstraintsForSecondaryPoint(); } @Override protected Set<D> getDependenciesAffectingThisTask() { return graph.incomingEdgesOf(task); } @Override protected ConstraintCalculator<V> getCalculator() { return createNormalCalculator(); } @Override protected PositionRestrictions createRestrictionsFor( GanttDate start, GanttDate end) { return biggerThan(start, end); } @Override protected boolean doSatisfyOrderCondition( GanttDate supposedlyBefore, GanttDate supposedlyAfter) { return supposedlyBefore.compareTo(supposedlyAfter) <= 0; } } class DominatingBackwardForces extends Dominating { public DominatingBackwardForces() { super(Point.END, Point.START); } @Override List<Constraint<GanttDate>> getStartConstraints() { return getConstraintsForSecondaryPoint(); } @Override List<Constraint<GanttDate>> getEndConstraints() { return getConstraintsForPrimaryPoint(); } @Override protected Set<D> getDependenciesAffectingThisTask() { return graph.outgoingEdgesOf(task); } @Override protected ConstraintCalculator<V> getCalculator() { return createBackwardsCalculator(); } @Override protected PositionRestrictions createRestrictionsFor( GanttDate start, GanttDate end) { return lessThan(start, end); } @Override protected boolean doSatisfyOrderCondition( GanttDate supposedlyBefore, GanttDate supposedlyAfter) { return supposedlyBefore.compareTo(supposedlyAfter) >= 0; } } class WeakForwardForces extends Forces { @Override List<Constraint<GanttDate>> getStartConstraints() { return adapter.getStartConstraintsFor(task); } @Override List<Constraint<GanttDate>> getEndConstraints() { return Collections.emptyList(); } @Override PositionRestrictions enforceUsingPreviousRestrictions( PositionRestrictions restrictions) { GanttDate result = Constraint.<GanttDate> initialValue(null) .withConstraints(restrictions.getStartConstraints()) .withConstraints(getStartConstraints()) .applyWithoutFinalCheck(); if (result != null) { enforceRestrictions(result); return biggerThan(result, adapter.getEndDateFor(task)); } return restrictions; } private void enforceRestrictions(GanttDate result) { if (!result.equals(getStartDate(task))) { adapter.setStartDateFor(task, result); } } } class WeakBackwardsForces extends Forces { @Override PositionRestrictions enforceUsingPreviousRestrictions( PositionRestrictions restrictions) { GanttDate result = Constraint.<GanttDate> initialValue(null) .withConstraints(restrictions.getEndConstraints()) .withConstraints(getEndConstraints()) .applyWithoutFinalCheck(); if (result != null) { enforceRestrictions(result); return lessThan(adapter.getStartDate(task), result); } return restrictions; } @Override List<Constraint<GanttDate>> getStartConstraints() { return Collections.emptyList(); } @Override List<Constraint<GanttDate>> getEndConstraints() { return adapter.getEndConstraintsFor(task); } private void enforceRestrictions(GanttDate newEnd) { if (!newEnd.equals(getEndDateFor(task))) { adapter.setEndDateFor(task, newEnd); } } } @Override public int hashCode() { return new HashCodeBuilder() .append(parentRecalculation) .append(taskPoint) .toHashCode(); } @Override public String toString() { return String.format( "%s, parentRecalculation: %s, predecessors: %s", taskPoint, parentRecalculation, asSimpleString(recalculationsCouldAffectThis)); } private String asSimpleString( Collection<? extends Recalculation> recalculations) { StringBuilder result = new StringBuilder(); result.append("["); for (Recalculation each : recalculations) { result.append(each.taskPoint).append(", "); } result.append("]"); return result.toString(); } @Override public boolean equals(Object obj) { if (Recalculation.class.isInstance(obj)) { Recalculation other = Recalculation.class.cast(obj); return new EqualsBuilder().append(parentRecalculation, other.parentRecalculation) .append(taskPoint, other.taskPoint) .isEquals(); } return false; } } public void remove(final V task) { Set<V> needingEnforcing = getOutgoingTasksFor(task); graph.removeVertex(task); topLevelTasks.remove(task); fromChildToParent.remove(task); if (adapter.isContainer(task)) { for (V t : adapter.getChildren(task)) { remove(t); } } topologicalSorter.recalculationNeeded(); enforcer.enforceRestrictionsOn(needingEnforcing); } public void removeDependency(D dependency) { graph.removeEdge(dependency); topologicalSorter.recalculationNeeded(); V destination = adapter.getDestination(dependency); V source = adapter.getSource(dependency); enforcer.enforceRestrictionsOn(destination); enforcer.enforceRestrictionsOn(source); } public boolean canAddDependency(D dependency) { return !isForbidden(dependency) && doesNotProvokeLoop(dependency); } private boolean isForbidden(D dependency) { if (!adapter.isVisible(dependency)) { // the invisible dependencies, the ones used to implement container // behavior are not forbidden return false; } boolean endEndDependency = DependencyType.END_END == dependency .getType(); boolean startStartDependency = DependencyType.START_START == dependency .getType(); V source = adapter.getSource(dependency); V destination = adapter.getDestination(dependency); boolean destinationIsContainer = adapter.isContainer(destination); boolean sourceIsContainer = adapter.isContainer(source); return (destinationIsContainer && endEndDependency) || (sourceIsContainer && startStartDependency); } public void add(D dependency) { add(dependency, true); } public void addWithoutEnforcingConstraints(D dependency) { add(dependency, false); } private void add(D dependency, boolean enforceRestrictions) { if (isForbidden(dependency)) { return; } V source = adapter.getSource(dependency); V destination = adapter.getDestination(dependency); graph.addEdge(source, destination, dependency); topologicalSorter.recalculationNeeded(); if (enforceRestrictions) { enforceRestrictions(destination); } } public void enforceRestrictions(final V task) { enforcer.taskPositionModified(task); } public DeferedNotifier manualNotificationOn(IAction action) { return enforcer.manualNotification(action); } public boolean contains(D dependency) { return graph.containsEdge(dependency); } public List<V> getTasks() { return new ArrayList<V>(graph.vertexSet()); } public List<D> getVisibleDependencies() { ArrayList<D> result = new ArrayList<D>(); for (D dependency : graph.edgeSet()) { if (adapter.isVisible(dependency)) { result.add(dependency); } } return result; } public List<V> getTopLevelTasks() { return Collections.unmodifiableList(topLevelTasks); } public void childrenAddedTo(V task) { enforcer.enforceRestrictionsOn(task); } public List<V> getInitialTasks() { List<V> result = new ArrayList<V>(); for (V task : graph.vertexSet()) { int dependencies = graph.inDegreeOf(task); if ((dependencies == 0) || (dependencies == getNumberOfIncomingDependenciesByType( task, DependencyType.END_END))) { result.add(task); } } return result; } public IDependency<V> getDependencyFrom(V from, V to) { return graph.getEdge(from, to); } public Set<V> getOutgoingTasksFor(V task) { Set<V> result = new HashSet<V>(); for (D dependency : graph.outgoingEdgesOf(task)) { result.add(adapter.getDestination(dependency)); } return result; } public Set<V> getIncomingTasksFor(V task) { Set<V> result = new HashSet<V>(); for (D dependency : graph.incomingEdgesOf(task)) { result.add(adapter.getSource(dependency)); } return result; } public boolean hasVisibleIncomingDependencies(V task) { return isSomeVisibleAndNotEndEnd(graph.incomingEdgesOf(task)); } private boolean isSomeVisibleAndNotEndEnd(Set<D> dependencies) { for (D each : dependencies) { if (!each.getType().equals(DependencyType.END_END) && adapter.isVisible(each)) { return true; } } return false; } public boolean hasVisibleOutcomingDependencies(V task) { return isSomeVisibleAndNotStartStart(graph.outgoingEdgesOf(task)); } private boolean isSomeVisibleAndNotStartStart(Set<D> dependencies) { for (D each : dependencies) { if (!each.getType().equals(DependencyType.START_START) && adapter.isVisible(each)) { return true; } } return false; } public List<V> getLatestTasks() { List<V> tasks = new ArrayList<V>(); for (V task : graph.vertexSet()) { int dependencies = graph.outDegreeOf(task); if ((dependencies == 0) || (dependencies == getNumberOfOutgoingDependenciesByType( task, DependencyType.START_START))) { tasks.add(task); } } return tasks; } private int getNumberOfIncomingDependenciesByType(V task, DependencyType dependencyType) { int count = 0; for (D dependency : graph.incomingEdgesOf(task)) { if (adapter.getType(dependency).equals(dependencyType)) { count++; } } return count; } private int getNumberOfOutgoingDependenciesByType(V task, DependencyType dependencyType) { int count = 0; for (D dependency : graph.outgoingEdgesOf(task)) { if (adapter.getType(dependency).equals(dependencyType)) { count++; } } return count; } public boolean isContainer(V task) { if (task == null) { return false; } return adapter.isContainer(task); } public boolean contains(V container, V task) { if ((container == null) || (task == null)) { return false; } if (adapter.isContainer(container)) { return adapter.getChildren(container).contains(task); } return false; } public boolean doesNotProvokeLoop(D dependency) { Set<TaskPoint> reachableFromDestination = destinationPoint(dependency) .getReachable(); for (TaskPoint each : reachableFromDestination) { if (each.sendsModificationsThrough(dependency)) { return false; } } return true; } TaskPoint destinationPoint(D dependency) { V destination = getDependencyDestination(dependency); return new TaskPoint(destination, getDestinationPoint(dependency.getType())); } private Point getDestinationPoint(DependencyType type) { return type.getSourceAndDestination()[isScheduleForward() ? 1 : 0]; } TaskPoint sourcePoint(D dependency) { V source = getDependencySource(dependency); return new TaskPoint(source, getSourcePoint(dependency.getType())); } /** * The dominating point is the one that causes the other point to be * modified; e.g. when doing forward scheduling the dominating point is the * start. */ private boolean isDominatingPoint(Point point) { return point == getDominatingPoint(); } private Point getDominatingPoint() { return isScheduleForward() ? Point.START : Point.END; } private Point getSourcePoint(DependencyType type) { return type.getSourceAndDestination()[isScheduleForward() ? 0 : 1]; } private V getDependencySource(D dependency) { return isScheduleForward() ? adapter.getSource(dependency) : adapter .getDestination(dependency); } private V getDependencyDestination(D dependency) { return isScheduleForward() ? adapter.getDestination(dependency) : adapter.getSource(dependency); } TaskPoint allPointsPotentiallyModified(V task) { return new TaskPoint(task, getDominatingPoint()); } private class TaskPoint { private final V task; private final boolean isContainer; private final Set<Point> pointsModified; private final Point entryPoint; TaskPoint(V task, Point entryPoint) { Validate.notNull(task); Validate.notNull(entryPoint); this.task = task; this.entryPoint = entryPoint; this.pointsModified = isDominatingPoint(entryPoint) ? EnumSet.of( Point.START, Point.END) : EnumSet.of(entryPoint); this.isContainer = adapter.isContainer(task); } @Override public String toString() { return String.format("%s(%s)", task, pointsModified); } @Override public boolean equals(Object obj) { if (TaskPoint.class.isInstance(obj)) { TaskPoint other = TaskPoint.class.cast(obj); return new EqualsBuilder().append(task, other.task) .append(pointsModified, other.pointsModified) .isEquals(); } return false; } @Override public int hashCode() { return new HashCodeBuilder().append(task).append(pointsModified) .toHashCode(); } public boolean areAllPointsPotentiallyModified() { return pointsModified.size() > 1; } public boolean somePointPotentiallyModified() { return pointsModified.contains(Point.START) || pointsModified.contains(Point.END); } public boolean onlyModifies(Point point) { return pointsModified.size() == 1 && pointsModified.contains(point); } Set<TaskPoint> getReachable() { Set<TaskPoint> result = new HashSet<TaskPoint>(); Queue<TaskPoint> pending = new LinkedList<TaskPoint>(); result.add(this); pending.offer(this); while (!pending.isEmpty()) { TaskPoint current = pending.poll(); Set<TaskPoint> immendiate = current.getImmediateSuccessors(); for (TaskPoint each : immendiate) { if (!result.contains(each)) { result.add(each); pending.offer(each); } } } return result; } public boolean isImmediatelyDerivedFrom(TaskPoint other) { return this.task.equals(other.task) && other.pointsModified.containsAll(this.pointsModified); } private Set<TaskPoint> cachedInmmediateSuccesors = null; public Set<TaskPoint> getImmediateSuccessors() { if (cachedInmmediateSuccesors != null) { return cachedInmmediateSuccesors; } Set<TaskPoint> result = new HashSet<TaskPoint>(); result.addAll(getImmediatelyDerivedOnSameTask()); Set<D> candidates = immediateDependencies(); for (D each : candidates) { if (this.sendsModificationsThrough(each)) { result.add(destinationPoint(each)); } } return cachedInmmediateSuccesors = Collections .unmodifiableSet(result); } private Set<TaskPoint> cachedImmediatePredecessors = null; public Set<TaskPoint> getImmediatePredecessors() { if (cachedImmediatePredecessors != null) { return cachedImmediatePredecessors; } Set<TaskPoint> result = new HashSet<TaskPoint>(); if (!isDominatingPoint(entryPoint)) { TaskPoint dominating = allPointsPotentiallyModified(task); assert isDominatingPoint(dominating.entryPoint); assert this.isImmediatelyDerivedFrom(dominating); result.add(dominating); } for (D each : immediateIncomingDependencies()) { if (this.receivesModificationsThrough(each)) { TaskPoint sourcePoint = sourcePoint(each); result.add(sourcePoint); } } return cachedImmediatePredecessors = Collections .unmodifiableSet(result); } private Collection<TaskPoint> getImmediatelyDerivedOnSameTask() { for (Point each : pointsModified) { if (isDominatingPoint(each)) { return Collections.singletonList(new TaskPoint(task, each .getOther())); } } return Collections.emptyList(); } private Set<D> immediateDependencies() { return isScheduleForward() ? graph.outgoingEdgesOf(this.task) : graph.incomingEdgesOf(this.task); } private Set<D> immediateIncomingDependencies() { return isScheduleForward() ? graph.incomingEdgesOf(this.task) : graph.outgoingEdgesOf(this.task); } public boolean sendsModificationsThrough(D dependency) { V source = getDependencySource(dependency); Point dependencySourcePoint = getSourcePoint(adapter .getType(dependency)); return source.equals(task) && (!isContainer || pointsModified .contains(dependencySourcePoint)); } private Point getSourcePoint(DependencyType type) { Point[] sourceAndDestination = type.getSourceAndDestination(); return sourceAndDestination[isScheduleForward() ? 0 : 1]; } private boolean receivesModificationsThrough(D dependency) { V destination = getDependencyDestination(dependency); Point destinationPoint = getDestinationPoint(adapter .getType(dependency)); return destination.equals(task) && entryPoint == destinationPoint; } } private V getTopmostFor(V task) { V result = task; while (fromChildToParent.containsKey(result)) { result = fromChildToParent.get(result); } return result; } public boolean isScheduleForward() { return !isScheduleBackwards(); } public boolean isScheduleBackwards() { return scheduleBackwards; } @Override public GanttDate getEndDateFor(V task) { return adapter.getEndDateFor(task); } @Override public List<Constraint<GanttDate>> getStartConstraintsFor(V task) { return adapter.getStartConstraintsFor(task); } @Override public List<Constraint<GanttDate>> getEndConstraintsFor(V task) { return adapter.getEndConstraintsFor(task); } @Override public GanttDate getStartDate(V task) { return adapter.getStartDate(task); } @Override public List<V> getChildren(V task) { if (!isContainer(task)) { return Collections.emptyList(); } return adapter.getChildren(task); } }
package verification.timed_state_exploration.zoneProject; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Arrays; import java.util.HashSet; import java.util.List; import lpn.parser.ExprTree; import lpn.parser.LhpnFile; import lpn.parser.Transition; import lpn.parser.Variable; import verification.platu.lpn.DualHashMap; import verification.platu.lpn.LpnTranList; import verification.platu.stategraph.State; /** * This class is for storing and manipulating timing zones via difference bound matrices. * The underlying structure is backed by a two dimensional array. A difference bound * matrix has the form * t0 t1 t2 t3 * t0 m00 m01 m02 m03 * t1 m10 m11 m12 m13 * t2 m20 m21 m22 m23 * t3 m30 m31 m32 m33 * where tj - ti<= mij. In particular, m0k is an upper bound for tk and -mk is a lower * bound for tk. * * The timers are referred to by an index. * * This class also contains a public nested class DiagonalNonZeroException which extends * java.lang.RuntimeException. This exception may be thrown if the diagonal entries of a * zone become nonzero. * * @author Andrew N. Fisher * */ public class Zone{ // Abstraction Function : // The difference bound matrix is represented by int[][]. // In order to keep track of the upper and lower bounds of timers from when they are first // enabled, the matrix will be augmented by a row and a column. The first row will contain // the upper bounds and the first column will contain the negative of the lower bounds. // For one timer t1 that is between 2 and 3, we might have // lb t0 t1 // ub x 0 3 // t0 0 m m // t1 -2 m m // where x is not important (and will be given a zero value), 3 is the upper bound on t1 // and -2 is the negative of the lower bound. The m values represent the actual difference // bound matrix. Also note that the column heading are not part of the stored representation // lb stands for lower bound while ub stands for upper bound. // This upper and lower bound information is called the Delay for a Transition object. // Since a timer is tied directly to a Transition, the timers are index by the corresponding // Transition's index in a LPNTranslator. // The timers are named by an integer referred to as the index. The _indexToTimer array // connects the index in the DBM sub-matrix to the index of the timer. For example, // a the timer t1 // Representation invariant : // Zones are immutable. // Integer.MAX_VALUE is used to logically represent infinity. // The lb and ub values for a timer should be set when the timer is enabled. // A negative hash code indicates that the hash code has not been set. // The index of the timer in _indexToTimer is the index in the DBM and should contain // the zeroth timer. // The array _indexToTimerPair should always be sorted. // The index of the LPN should match where it is in the _lpnList, that is, if lpn is // and LhpnFile object in _lpnList, then _lpnList[getLpnIndex()] == lpn. /* * Resource List : * TODO : Create a list reference where the algorithms can be found that this class * depends on. */ public static final int INFINITY = Integer.MAX_VALUE; /* The lower and upper bounds of the times as well as the dbm. */ private int[][] _matrix; /* Maps the index to the timer. The index is row/column of the DBM sub-matrix. * Logically the zero timer is given index -1. * */ //private int[] _indexToTimer; private LPNTransitionPair[] _indexToTimerPair; /* The hash code. */ private int _hashCode; /* A lexicon between a transitions index and its name. */ //private static HashMap<Integer, Transition> _indexToTransition; /* Set if a failure in the testSplit method has fired already. */ //private static boolean _FAILURE = false; /* Hack to pass a parameter to the equals method though a variable */ //private boolean subsetting = false; /* Records the largest zone that occurs. */ public static int ZoneSize = 0; private void checkZoneMaxSize(){ if(dbmSize() > ZoneSize){ ZoneSize = dbmSize(); } } private LhpnFile[] _lpnList; /* * Turns on and off subsets for the zones. * True means subset will be considered. * False means subsets will not be considered. */ private static boolean _subsetFlag = true; /* * Turns on and off supersets for zones. * True means that supersets will be considered. * False means that supersets will not be considered. */ private static boolean _supersetFlag = true; /** * Gets the value of the subset flag. * @return * True if subsets are requested, false otherwise. */ public static boolean getSubsetFlag(){ return _subsetFlag; } /** * Sets the value of the subset flag. * @param useSubsets * The value for the subset flag. Set to true if * supersets are to be considered, false otherwise. */ public static void setSubsetFlag(boolean useSubsets){ _subsetFlag = useSubsets; } /** * Gets the value of the superset flag. * @return * True if supersets are to be considered, false otherwise. */ public static boolean getSupersetFlag(){ return _supersetFlag; } /** * Sets the superset flag. * @param useSupersets * The value of the superset flag. Set to true if * supersets are to be considered, false otherwise. */ public static void setSupersetFlag(boolean useSupersets){ _supersetFlag = useSupersets; } /** * Construct a zone that has the given timers. * @param timers * The ith index of the array is the index of the timer. For example, * if timers = [1, 3, 5], then the zeroth row/column of the DBM is the * timer of the transition with index 1, the first row/column of the * DBM is the timer of the transition with index 3, and the 2nd * row/column is the timer of the transition with index 5. Do not * include the zero timer. * @param matrix * The DBM augmented with the lower and upper bounds of the delays for the * transitions. For example, suppose a zone has timers [1, 3, 5] (as * described in the timers parameters). The delay for transition 1 is * [1, 3], the delay for transition 3 is [2,5], and the delay for * transition 5 is [4,6]. Also suppose the DBM is * t0 t1 t3 t5 * t0 | 0, 3, 3, 3 | * t1 | 0, 0, 0, 0 | * t3 | 0, 0, 0, 0 | * t5 | 0, 0, 0, 0 | * Then the matrix that should be passed is * lb t0 t1 t3 t5 * ub| 0, 0, 3, 5, 6| * t0| 0, 0, 3, 3, 3| * t1|-1, 0, 0, 0, 0| * t3|-2, 0, 0, 0, 0| * t5|-4, 0, 0, 0, 0| * The matrix should be non-null and the zero timer should always be the * first timer, even when there are no other timers. */ public Zone(int[] timers, int[][] matrix) { // A negative number indicates that the hash code has not been set. _hashCode = -1; // Make a copy to reorder the timers. // _indexToTimer = Arrays.copyOf(timers, timers.length); // Make a copy to reorder the timers. _indexToTimerPair = new LPNTransitionPair[timers.length]; for(int i=0; i<timers.length; i++){ _indexToTimerPair[i] = new LPNTransitionPair(LPNTransitionPair.SINGLE_LPN, timers[i], true); } // Sorting the array. // Arrays.sort(_indexToTimer); // Sorting the array. Arrays.sort(_indexToTimerPair); //if(_indexToTimer[0] != 0) // if(_indexToTimer[0] != -1) // // Add the zeroth timer. // int[] newIndexToTimer = new int[_indexToTimer.length+1]; // for(int i=0; i<_indexToTimer.length; i++) // newIndexToTimer[i+1] = _indexToTimer[i]; // _indexToTimer = newIndexToTimer; // _indexToTimer[0] = -1; if(_indexToTimerPair[0].get_transitionIndex() != -1){ // Add the zeroth timer. LPNTransitionPair[] newIndexToTimerPair = new LPNTransitionPair[_indexToTimerPair.length]; for(int i=0; i<_indexToTimerPair.length; i++){ newIndexToTimerPair[i+1] = _indexToTimerPair[i]; } _indexToTimerPair = newIndexToTimerPair; _indexToTimerPair[0] = new LPNTransitionPair(LPNTransitionPair.SINGLE_LPN, -1, true); } // if(_indexToTimer[0] < 0) // // Add a zero timer. // else if(_indexToTimer[0] > 0) // int[] newTimerIndex = new int[_indexToTimer.length+1]; // for(int i=0; i<_indexToTimer.length; i++) // newTimerIndex[i+1] = _indexToTimer[i]; // Map the old index of the timer to the new index of the timer. HashMap<Integer, Integer> newIndex = new HashMap<Integer, Integer>(); // For the old index, find the new index. for(int i=0; i<timers.length; i++) { // Since the zeroth timer is not included in the timers passed // to the index in the DBM is 1 more than the index of the timer // in the timers array. //newIndex.put(i+1, Arrays.binarySearch(_indexToTimer, timers[i])); LPNTransitionPair searchValue = new LPNTransitionPair(LPNTransitionPair.SINGLE_LPN, timers[i], true); newIndex.put(i+1, Arrays.binarySearch(_indexToTimerPair, searchValue)); } // Add the zero timer index. newIndex.put(0, 0); // Initialize the matrix. _matrix = new int[matrixSize()][matrixSize()]; // Copy the DBM for(int i=0; i<dbmSize(); i++) { for(int j=0; j<dbmSize(); j++) { // Copy the passed in matrix to _matrix. setDbmEntry(newIndex.get(i), newIndex.get(j), matrix[dbmIndexToMatrixIndex(i)][dbmIndexToMatrixIndex(j)]); // In the above, changed setDBMIndex to setdbm } } // Copy in the upper and lower bounds. The zero time does not have an upper or lower bound // so the index starts at i=1, the first non-zero timer. for(int i=1; i< dbmSize(); i++) { setUpperBoundbydbmIndex(newIndex.get(i), matrix[0][dbmIndexToMatrixIndex(i)]); // Note : The method setLowerBoundbydbmIndex, takes the value of the lower bound // and the matrix stores the negative of the lower bound. So the matrix value // must be multiplied by -1. setLowerBoundbydbmIndex(newIndex.get(i), -1*matrix[dbmIndexToMatrixIndex(i)][0]); } recononicalize(); } /** * Initializes a zone according to the markings of state. * @param currentState * The zone is initialized as if all enabled timers * have just been enabled. */ public Zone(State initialState) { // Extract the associated LPN. LhpnFile lpn = initialState.getLpn(); int LPNIndex = lpn.getLpnIndex(); if(_lpnList == null){ // If no LPN exists yet, create it and put lpn in it. _lpnList = new LhpnFile[LPNIndex+1]; _lpnList[LPNIndex] = lpn; } else if(_lpnList.length <= LPNIndex){ // The list does not contain the lpn. LhpnFile[] tmpList = _lpnList; _lpnList = new LhpnFile[LPNIndex+1]; _lpnList[LPNIndex] = lpn; // Copy any that exist already. for(int i=0; i<_lpnList.length; i++){ _lpnList[i] = tmpList[i]; } } else if(_lpnList[LPNIndex] != lpn){ // This checks that the appropriate lpn is in the right spot. // If not (which gets you in this block), then this fixes it. _lpnList[LPNIndex] = lpn; } // Default value for the hash code indicating that the hash code has not // been set yet. _hashCode = -1; // Get the list of currently enabled Transitions by their index. boolean[] enabledTran = initialState.getTranVector(); ArrayList<LPNTransitionPair> enabledTransitionsArrayList = new ArrayList<LPNTransitionPair>(); LPNTransitionPair zeroPair = new LPNTransitionPair(LPNTransitionPair.ZERO_TIMER, -1, true); // Add the zero timer first. enabledTransitionsArrayList.add(zeroPair); // The index of the boolean value corresponds to the index of the Transition. for(int i=0; i<enabledTran.length; i++){ if(enabledTran[i]){ enabledTransitionsArrayList.add(new LPNTransitionPair(LPNIndex, i, true)); } } _indexToTimerPair = enabledTransitionsArrayList.toArray(new LPNTransitionPair[0]); _matrix = new int[matrixSize()][matrixSize()]; for(int i=1; i<dbmSize(); i++) { // Get the name for the timer in the i-th column/row of DBM String tranName = lpn.getTransition(_indexToTimerPair[i].get_transitionIndex()).getName(); ExprTree delay = lpn.getDelayTree(tranName); // Get the values of the variables for evaluating the ExprTree. HashMap<String, String> varValues = lpn.getAllVarsWithValuesAsString(initialState.getVector()); // Set the upper and lower bound. int upper, lower; if(delay.getOp().equals("uniform")) { ExprTree lowerDelay = delay.getLeftChild(); ExprTree upperDelay = delay.getRightChild(); lower = (int) lowerDelay.evaluateExpr(varValues); upper = (int) upperDelay.evaluateExpr(varValues); } else { lower = (int) delay.evaluateExpr(varValues); upper = lower; } setLowerBoundbydbmIndex(i, lower); setUpperBoundbydbmIndex(i, upper); } // Advance the time and tighten the bounds. advance(); recononicalize(); checkZoneMaxSize(); } /** * Creates a Zone based on the local states. * @param localStates * The current state (or initial) of the LPNs. */ public Zone(State[] localStates){ // Extract the local states. //State[] localStates = tps.toStateArray(); // Initialize hash code to -1 (indicating nothing cached). _hashCode = -1; // Initialize the LPN list. initialize_lpnList(localStates); // Get the enabled transitions. This initializes the _indexTotimerPair // which stores the relevant information. initialize_indexToTimerPair(localStates); // Initialize the matrix. _matrix = new int[matrixSize()][matrixSize()]; // Set the lower bound/ upper bounds. initializeLowerUpperBounds(getAllNames(), localStates); // Advance Time advance(); // Re-canonicalize recononicalize(); // Check the size of the DBM. checkZoneMaxSize(); } /** * Gives the names of all the transitions and continuous variables that * are represented by the zone. * @return * The names of the transitions and continuous variables that are * represented by the zone. */ public String[] getAllNames(){ // String[] transitionNames = new String[_indexToTimerPair.length]; // transitionNames[0] = "The zero timer."; // for(int i=1; i<transitionNames.length; i++){ // LPNTransitionPair ltPair = _indexToTimerPair[i]; // transitionNames[i] = _lpnList[ltPair.get_lpnIndex()] // .getTransition(ltPair.get_transitionIndex()).getName(); // return transitionNames; // Get the continuous variable names. String[] contVar = getContVarNames(); // Get the transition names. String[] trans = getTranNames(); // Create an array large enough for all the names. String[] names = new String[contVar.length + trans.length + 1]; // Add the zero timer. names[0] = "The zero timer."; // Add the continuous variables. for(int i=0; i<contVar.length; i++){ names[i+1] = contVar[i]; } // Add the timers. for(int i=0; i<trans.length; i++){ // Already the zero timer has been added and the elements of contVar. // That's a total of 'contVar.length + 1' elements. The last index was // thus 'contVar.length' So the first index to add to is // 'contVar.length +1'. names[1+contVar.length + i] = trans[i]; } return names; } /** * Get the names of the continuous variables that this zone uses. * @return * The names of the continuous variables that are part of this zone. */ public String[] getContVarNames(){ // List for accumulating the names. ArrayList<String> contNames = new ArrayList<String>(); // Find the pairs that represent the continuous variables. Loop starts at // i=1 since the i=0 is the zero timer. for(int i=1; i<_indexToTimerPair.length; i++){ LPNTransitionPair ltPair = _indexToTimerPair[i]; // If the isTimer value is false, then this pair represents a continuous // variable. if(!ltPair.get_isTimer()){ // Get the LPN that this pairing references and find the name of // the continuous variable whose index is given by this pairing. contNames.add(_lpnList[ltPair.get_lpnIndex()] .getVariable(ltPair.get_transitionIndex()).getName()); } } return contNames.toArray(new String[0]); } /** * Gets the names of the transitions that are associated with the timers in the * zone. Does not return the zero timer. * @return * The names of the transitions whose timers are in the zone except the zero * timer. */ public String[] getTranNames(){ // List for accumulating the names. ArrayList<String> transitionNames = new ArrayList<String>(); // Find the pairs that represent the transition timers. for(int i=1; i<_indexToTimerPair.length; i++){ LPNTransitionPair ltPair = _indexToTimerPair[i]; // If the isTimer value is true, then this pair represents a timer. if(ltPair.get_isTimer()){ // Get the LPN that this pairing references and find the name of the // transition whose index is given by this pairing. transitionNames.add(_lpnList[ltPair.get_lpnIndex()] .getTransition(ltPair.get_transitionIndex()).getName()); } } return transitionNames.toArray(new String[0]); } /** * Initializes the _lpnList using information from the local states. * @param localStates * The local states. * @return * The enabled transitions. */ private void initialize_lpnList(State[] localStates){ // Create the LPN list. _lpnList = new LhpnFile[localStates.length]; // Get the LPNs. for(int i=0; i<localStates.length; i++){ _lpnList[i] = localStates[i].getLpn(); } } /** * Initializes the _indexToTimerPair from the local states. * @param localStates * The local states. * @return * The names of the transitions stored in the _indexToTimerPair (in the same order). */ private void initialize_indexToTimerPair(State[] localStates){ /* * The populating of the _indexToTimerPair is done in three stages. * The first is to add the zero timer which is at the beginning of the zone. * The second is to add the continuous variables. And the third is to add * the other timers. Since the continuous variables are added before the * timers and the variables and timers are added in the order of the LPNs, * the elements in an accumulating list (enabledTransitionsArrayList) are * already in order up to the elements added for a particular LPN. Thus the * only sorting that needs to take place is the sorting for a particular LPN. * Correspondingly, elements are first found for an LPN and sort, then added * to the main list. */ // This list accumulates the transition pairs (ie timers) and the continuous // variables. ArrayList<LPNTransitionPair> enabledTransitionsArrayList = new ArrayList<LPNTransitionPair>(); // Put in the zero timer. enabledTransitionsArrayList .add(new LPNTransitionPair(LPNTransitionPair.ZERO_TIMER, -1, true)); // Get the continuous variables. for(int i=0; i<localStates.length; i++){ // Accumulates the changing continuous variables for a single LPN. ArrayList<LPNTransitionPair> singleLPN = new ArrayList<LPNTransitionPair>(); // Get the associated LPN. LhpnFile lpn = localStates[i].getLpn(); // Get the continuous variables for this LPN. String[] continuousVariables = lpn.getContVars(); // Get the variable, index map. DualHashMap<String, Integer> variableIndex = lpn.getVarIndexMap(); // Find which have a nonzero rate. for(int j=0; j<continuousVariables.length; j++){ // Get the Variables with this name. Variable contVar = lpn.getVariable(continuousVariables[j]); // Get the rate. int rate = (int) Double.parseDouble(contVar.getInitRate()); // If the rate is non-zero, then the variables needs to be tracked // by the zone. if(rate !=0){ // Temporary exception guaranteeing only unit rates. if(rate != -1 && rate != 1){ throw new IllegalArgumentException("Current development " + "only supports unit rates. The variable " + contVar + " has a rate of " + rate); } // Get the LPN index for the variable int lpnIndex = lpn.getLpnIndex(); // Get the index as a variable for the LPN. This index matches // the index in the vector stored by platu.State. int contVariableIndex = variableIndex.get(continuousVariables[j]); // The continuous variable reference. singleLPN.add( new LPNTransitionPair(lpnIndex, contVariableIndex, false)); } } // Sort the list. Collections.sort(singleLPN); // Add the list to the total accumulating list. for(int j=0; j<singleLPN.size(); j++){ enabledTransitionsArrayList.add(singleLPN.get(j)); } } // Get the transitions. for(int i=0; i<localStates.length; i++){ // Extract the enabled transition vector. boolean[] enabledTran = localStates[i].getTranVector(); // Accumulates the transition pairs for one LPN. ArrayList<LPNTransitionPair> singleLPN = new ArrayList<LPNTransitionPair>(); // The index of the boolean value corresponds to the index of the Transition. for(int j=0; j<enabledTran.length; j++){ if(enabledTran[j]){ // Add the transition pair. singleLPN.add(new LPNTransitionPair(i, j, true)); } } // Sort the transitions for the current LPN. Collections.sort(singleLPN); // Add the collection to the enabledTransitionsArrayList for(int j=0; j<singleLPN.size(); j++){ enabledTransitionsArrayList.add(singleLPN.get(j)); } } // Extract out the array portion of the enabledTransitionsArrayList. _indexToTimerPair = enabledTransitionsArrayList.toArray(new LPNTransitionPair[0]); } /** * Sets the lower and upper bounds for the transitions and continuous variables. * @param varNames * The names of the transitions in _indexToTimerPair. */ private void initializeLowerUpperBounds(String[] varNames, State[] localStates){ // Traverse the entire length of the DBM sub-matrix except the zero row/column. // This is the same length as the _indexToTimerPair.length-1. The DBM is used to // match the idea of setting the value for each row. for(int i=1; i<dbmSize(); i++){ // Get the current LPN and transition pairing. LPNTransitionPair ltPair = _indexToTimerPair[i]; int upper, lower; if(!ltPair.get_isTimer()){ // If the pairing represents a continuous variable, then the // upper and lower bound are the initial value or infinity depending // on whether the initial rate is positive or negative. // If the value is a constant, then assign the upper and lower bounds // to be constant. If the value is a range then assign the upper and // lower bounds to be a range. Variable v = _lpnList[ltPair.get_lpnIndex()] .getVariable(ltPair.get_transitionIndex()); // TODO : For now, I'm assuming that the initial rate is constant. This // will need to change later. int initialRate = (int) Double.parseDouble(v.getInitRate()); upper = initialRate; lower = initialRate; } else{ // Get the expression tree. ExprTree delay = _lpnList[ltPair.get_lpnIndex()].getDelayTree(varNames[i]); // Get the values of the variables for evaluating the ExprTree. HashMap<String, String> varValues = _lpnList[ltPair.get_lpnIndex()] .getAllVarsWithValuesAsString(localStates[ltPair.get_lpnIndex()].getVector()); // Set the upper and lower bound. // int upper, lower; if(delay.getOp().equals("uniform")) { ExprTree lowerDelay = delay.getLeftChild(); ExprTree upperDelay = delay.getRightChild(); lower = (int) lowerDelay.evaluateExpr(varValues); upper = (int) upperDelay.evaluateExpr(varValues); } else { lower = (int) delay.evaluateExpr(varValues); upper = lower; } } setLowerBoundbydbmIndex(i, lower); setUpperBoundbydbmIndex(i, upper); } } /** * Zero argument constructor for use in methods that create Zones where the members * variables will be set by the method. */ private Zone() { _matrix = new int[0][0]; _indexToTimerPair = new LPNTransitionPair[0]; _hashCode = -1; _lpnList = new LhpnFile[0]; } /** * Gets the upper bound of a Transition from the zone. * @param t * The transition whose upper bound is wanted. * @return * The upper bound of Transition t. */ public int getUpperBoundbyTransition(Transition t) { LhpnFile lpn = t.getLpn(); int lpnIndex = lpn.getLpnIndex(); int transitionIndex = t.getIndex(); LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex, true); return getUpperBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair)); } /** * Get the value of the upper bound for the delay. * @param index * The timer's row/column of the DBM matrix. * @return * The upper bound on the transitions delay. */ public int getUpperBoundbydbmIndex(int index) { return _matrix[0][dbmIndexToMatrixIndex(index)]; } /** * Set the value of the upper bound for the delay. * @param t * The transition whose upper bound is being set. * @param value * The value of the upper bound. */ public void setUpperBoundbyTransition(Transition t, int value) { LhpnFile lpn = t.getLpn(); int lpnIndex = lpn.getLpnIndex(); int transitionIndex = t.getIndex(); LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex, true); setUpperBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair), value); } /** * Set the value of the upper bound for the delay. * @param index * The timer's row/column of the DBM matrix. * @param value * The value of the upper bound. */ public void setUpperBoundbydbmIndex(int index, int value) { _matrix[0][dbmIndexToMatrixIndex(index)] = value; } /** * Sets the upper bound for a transition described by an LPNTransitionPair. * @param ltPair * The index of the transition and the index of the associated LPN for * the timer to set the upper bound. * @param value * The value for setting the upper bound. */ private void setUpperBoundByLPNTransitionPair(LPNTransitionPair ltPair, int value){ setUpperBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair), value); } /** * Gets the lower bound of a Transition from the zone. * @param t * The transition whose upper bound is wanted. * @return * The lower bound of Transition t. */ public int getLowerBoundbyTransition(Transition t) { LhpnFile lpn = t.getLpn(); int lpnIndex = lpn.getLpnIndex(); int transitionIndex = t.getIndex(); LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex, true); return -1*getLowerBoundbydbmIndex( Arrays.binarySearch(_indexToTimerPair, ltPair)); } /** * Get the value of the lower bound for the delay. * @param index * The timer's row/column of the DBM matrix. * @return * The value of the lower bound. */ public int getLowerBoundbydbmIndex(int index) { return _matrix[dbmIndexToMatrixIndex(index)][0]; } /** * Set the value of the lower bound for the delay. * @param t * The transition whose lower bound is being set. * @param value * The value of the lower bound. */ public void setLowerBoundbyTransition(Transition t, int value) { LhpnFile lpn = t.getLpn(); int lpnIndex = lpn.getLpnIndex(); int transitionIndex = t.getIndex(); LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex, true); setLowerBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair,ltPair), value); } /** * Set the value of the upper bound for the delay. * @param t * The transition whose upper bound is being set. * @param value * The value of the upper bound. */ private void setLowerBoundByLPNTransitionPair(LPNTransitionPair ltPair, int value){ setLowerBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair,ltPair), value); } /** * Set the value of the lower bound for the delay. * @param index * The timer's row/column of the DBM matrix. * @param value * The value of the lower bound. */ public void setLowerBoundbydbmIndex(int index, int value) { _matrix[dbmIndexToMatrixIndex(index)][0] = -1*value; } /** * Converts the index of the DBM to the index of _matrix. * @param i * The row/column index of the DBM. * @return * The row/column index of _matrix. */ private int dbmIndexToMatrixIndex(int i) { return i+1; } /** * Retrieves an entry of the DBM using the DBM's addressing. * @param i * The row of the DBM. * @param j * The column of the DBM. * @return * The value of the (i, j) element of the DBM. */ public int getDbmEntry(int i, int j) { return _matrix[dbmIndexToMatrixIndex(i)][dbmIndexToMatrixIndex(j)]; } /** * Sets an entry of the DBM using the DBM's addressing. * @param i * The row of the DBM. * @param j * The column of the DBM. * @param value * The new value for the entry. */ private void setDbmEntry(int i, int j, int value) { _matrix[dbmIndexToMatrixIndex(i)][dbmIndexToMatrixIndex(j)] = value; } /** * Returns the index of the the transition in the DBM given a LPNTransitionPair pairing * the transition index and associated LPN index. * @param ltPair * The pairing comprising the index of the transition and the index of the associated * LPN. * @return * The row/column of the DBM associated with the ltPair. */ private int timerIndexToDBMIndex(LPNTransitionPair ltPair) { return Arrays.binarySearch(_indexToTimerPair, ltPair); } /** * The matrix labeled with 'ti' where i is the transition index associated with the timer. */ public String toString() { String result = "Timer and delay.\n"; int count = 0; // Print the timers. for(int i=1; i<_indexToTimerPair.length; i++, count++) { if(_lpnList.length == 0) { // If no LPN's are associated with this Zone, use the index of the timer. result += " t" + _indexToTimerPair[i].get_transitionIndex() + " : "; } else { String name; // If the current LPNTransitionPair is a timer, get the name // from the transitions. if(_indexToTimerPair[i].get_isTimer()){ // Get the name of the transition. Transition tran = _lpnList[_indexToTimerPair[i].get_lpnIndex()]. getTransition(_indexToTimerPair[i].get_transitionIndex()); name = tran.getName(); } else{ // If the current LPNTransitionPair is not a timer, get the // name as a continuous variable. Variable var = _lpnList[_indexToTimerPair[i].get_lpnIndex()] .getVariable(_indexToTimerPair[i].get_transitionIndex()); name = var.getName(); } // result += " " + tran.getName() + ":"; result += " " + name + ":"; } result += "[ " + -1*getLowerBoundbydbmIndex(i) + ", " + getUpperBoundbydbmIndex(i) + " ]"; if(count > 9) { result += "\n"; count = 0; } } result += "\nDBM\n"; // Print the DBM. for(int i=0; i<_indexToTimerPair.length; i++) { result += "| " + getDbmEntry(i, 0); for(int j=1; j<_indexToTimerPair.length; j++) { result += ", " + getDbmEntry(i, j); } result += " |\n"; } return result; } /** * Tests for equality. Overrides inherited equals method. * @return True if o is equal to this object, false otherwise. */ public boolean equals(Object o) { // Check if the reference is null. if(o == null) { return false; } // Check that the type is correct. if(!(o instanceof Zone)) { return false; } // Check for equality using the Zone equality. return equals((Zone) o); } /** * Tests for equality. * @param * The Zone to compare. * @return * True if the zones are non-null and equal, false otherwise. */ public boolean equals(Zone otherZone) { // Check if the reference is null first. if(otherZone == null) { return false; } // Check for reference equality. if(this == otherZone) { return true; } // If the hash codes are different, then the objects are not equal. if(this.hashCode() != otherZone.hashCode()) { return false; } // Check if the they have the same number of timers. if(this._indexToTimerPair.length != otherZone._indexToTimerPair.length){ return false; } // Check if the timers are the same. for(int i=0; i<this._indexToTimerPair.length; i++){ if(!(this._indexToTimerPair[i].equals(otherZone._indexToTimerPair[i]))){ return false; } } // Check if the matrix is the same for(int i=0; i<_matrix.length; i++) { for(int j=0; j<_matrix[0].length; j++) { if(!(this._matrix[i][j] == otherZone._matrix[i][j])) { return false; } } } return true; } /** * Determines if this zone is a subset of Zone otherZone. * @param otherZone * The zone to compare against. * @return * True if this is a subset of other; false otherwise. */ public boolean subset(Zone otherZone){ // Check if the reference is null first. if(otherZone == null) { return false; } // Check for reference equality. if(this == otherZone) { return true; } // Check if the the same number of timers are present. if(this._indexToTimerPair.length != otherZone._indexToTimerPair.length){ return false; } // Check if the transitions are the same. for(int i=0; i<this._indexToTimerPair.length; i++){ if(!(this._indexToTimerPair[i].equals(otherZone._indexToTimerPair[i]))){ return false; } } // Check if the entries of this Zone are less than or equal to the entries // of the other Zone. for(int i=0; i<_matrix.length; i++) { for(int j=0; j<_matrix[0].length; j++) { if(!(this._matrix[i][j] <= otherZone._matrix[i][j])){ return false; } } } return true; } /** * Determines if this zone is a superset of Zone otherZone. * @param otherZone * The zone to compare against. * @return * True if this is a subset of other; false otherwise. More specifically it * gives the result of otherZone.subset(this). Thus it agrees with the subset method. */ public boolean superset(Zone otherZone){ return otherZone.subset(this); } /** * Overrides the hashCode. */ public int hashCode() { // Check if the hash code has been set. if(_hashCode <0) { _hashCode = createHashCode(); } return _hashCode; } /** * Creates a hash code for a Zone object. * @return * The hash code. */ private int createHashCode() { int newHashCode = Arrays.hashCode(_indexToTimerPair); for(int i=0; i<_matrix.length; i++) { newHashCode ^= Arrays.hashCode(_matrix[i]); } return Math.abs(newHashCode); } /** * The size of the DBM sub matrix. This is calculated using the size of _indexToTimer. * @return * The size of the DBM. */ private int dbmSize() { return _indexToTimerPair.length; } /** * The size of the matrix. * @return * The size of the matrix. This is calculated using the size of _indexToTimer. */ private int matrixSize() { return _indexToTimerPair.length + 1; } /** * Performs the Floyd's least pairs algorithm to reduce the DBM. */ private void recononicalize() { for(int k=0; k<dbmSize(); k++) { for (int i=0; i<dbmSize(); i++) { for(int j=0; j<dbmSize(); j++) { if(getDbmEntry(i, k) != INFINITY && getDbmEntry(k, j) != INFINITY && getDbmEntry(i, j) > getDbmEntry(i, k) + getDbmEntry(k, j)) { setDbmEntry(i, j, getDbmEntry(i, k) + getDbmEntry(k, j)); } if( (i==j) && getDbmEntry(i, j) != 0) { throw new DiagonalNonZeroException("Entry (" + i + ", " + j + ")" + " became " + getDbmEntry(i, j) + "."); } } } } } /** * Determines if a timer associated with a given transitions has reached its lower bound. * @param t * The transition to consider. * @return * True if the timer has reached its lower bound, false otherwise. */ public boolean exceedsLowerBoundbyTransitionIndex(Transition t) { LhpnFile lpn = t.getLpn(); int lpnIndex = lpn.getLpnIndex(); int transitionIndex = t.getIndex(); LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex, true); return exceedsLowerBoundbydbmIndex(Arrays.binarySearch(_indexToTimerPair, ltPair)); } /** * Determines if a timer has reached its lower bound. * @param timer * The timer's index. * @return * True if the timer has reached its lower bound, false otherwise. */ public boolean exceedsLowerBoundbydbmIndex(int index) { // Note : Make sure that the lower bound is stored as a negative number // and that the inequality is correct. return _matrix[0][dbmIndexToMatrixIndex(index)] <= _matrix[1][dbmIndexToMatrixIndex(index)]; } /* (non-Javadoc) * @see verification.timed_state_exploration.zone.Zone#fireTransitionbyTransitionIndex(int, int[], verification.platu.stategraph.State) */ // public Zone fireTransitionbyTransitionIndex(int timer, int[] enabledTimers, // State state) // // TODO: Check if finish. // int index = Arrays.binarySearch(_indexToTimer, timer); // //return fireTransitionbydbmIndex(Arrays.binarySearch(_indexToTimer, timer), // //enabledTimers, state); // // Check if the value is in this zone to fire. // if(index < 0){ // return this; // return fireTransitionbydbmIndex(index, enabledTimers, state); /** * Gives the Zone obtained by firing a given Transitions. * @param t * The transitions being fired. * @param enabledTran * The list of currently enabled Transitions. * @param localStates * The current local states. * @return * The Zone obtained by firing Transition t with enabled Transitions enabled * enabledTran when the current state is localStates. */ public Zone fire(Transition t, LpnTranList enabledTran, State[] localStates){ // Create the LPNTransitionPair to check if the Transitions is in the zone and to // find the index. LhpnFile lpn = t.getLpn(); int lpnIndex = lpn.getLpnIndex(); int transitionIndex = t.getIndex(); LPNTransitionPair ltPair = new LPNTransitionPair(lpnIndex, transitionIndex, true); int dbmIndex = Arrays.binarySearch(_indexToTimerPair, ltPair); if(dbmIndex <= 0){ return this; } return fireTransitionbydbmIndex(dbmIndex, enabledTran, localStates); } /** * Updates the Zone according to the transition firing. * @param index * The index of the timer. * @return * The updated Zone. */ public Zone fireTransitionbydbmIndex(int index, LpnTranList enabledTimers, State[] localStates) { Zone newZone = new Zone(); // Copy the LPNs over. newZone._lpnList = new LhpnFile[this._lpnList.length]; for(int i=0; i<this._lpnList.length; i++){ newZone._lpnList[i] = this._lpnList[i]; } // Extract the pairing information for the enabled timers. // Using the enabledTimersList should be faster than calling the get method // several times. newZone._indexToTimerPair = new LPNTransitionPair[enabledTimers.size() + 1]; int count = 0; newZone._indexToTimerPair[count++] = new LPNTransitionPair(LPNTransitionPair.ZERO_TIMER, -1, true); for(Transition t : enabledTimers){ newZone._indexToTimerPair[count++] = new LPNTransitionPair(t.getLpn().getLpnIndex(), t.getIndex(), true); } Arrays.sort(newZone._indexToTimerPair); HashSet<LPNTransitionPair> newTimers = new HashSet<LPNTransitionPair>(); HashSet<LPNTransitionPair> oldTimers = new HashSet<LPNTransitionPair>(); for(int i=0; i<newZone._indexToTimerPair.length; i++) { // Determine if each value is a new timer or old. if(Arrays.binarySearch(this._indexToTimerPair, newZone._indexToTimerPair[i]) >= 0 ) { // The timer was already present in the zone. oldTimers.add(newZone._indexToTimerPair[i]); } else { // The timer is a new timer. newTimers.add(newZone._indexToTimerPair[i]); } } // Create the new matrix. newZone._matrix = new int[newZone.matrixSize()][newZone.matrixSize()]; // TODO: For simplicity, make a copy of the current zone and perform the // restriction and re-canonicalization. Later add a copy re-canonicalization // that does the steps together. Zone tempZone = this.clone(); tempZone.restrict(index); tempZone.recononicalize(); // Copy the tempZone to the new zone. for(int i=0; i<tempZone.dbmSize(); i++) { if(!oldTimers.contains(tempZone._indexToTimerPair[i])) { continue; } // Get the new index of for the timer. int newIndexi = i==0 ? 0 : Arrays.binarySearch(newZone._indexToTimerPair, tempZone._indexToTimerPair[i]); for(int j=0; j<tempZone.dbmSize(); j++) { if(!oldTimers.contains(tempZone._indexToTimerPair[j])) { continue; } int newIndexj = j==0 ? 0 : Arrays.binarySearch(newZone._indexToTimerPair, tempZone._indexToTimerPair[j]); newZone._matrix[newZone.dbmIndexToMatrixIndex(newIndexi)] [newZone.dbmIndexToMatrixIndex(newIndexj)] = tempZone.getDbmEntry(i, j); } } // Copy the upper and lower bounds. for(int i=1; i<tempZone.dbmSize(); i++) { if(!oldTimers.contains(tempZone._indexToTimerPair[i])) { continue; } newZone.setLowerBoundByLPNTransitionPair(tempZone._indexToTimerPair[i], -1*tempZone.getLowerBoundbydbmIndex(i)); // The minus sign is because _matrix stores the negative of the lower bound. newZone.setUpperBoundByLPNTransitionPair(tempZone._indexToTimerPair[i], tempZone.getUpperBoundbydbmIndex(i)); } // Copy in the new relations for the new timers. for(LPNTransitionPair timerNew : newTimers) { for(LPNTransitionPair timerOld : oldTimers) { newZone.setDbmEntry(newZone.timerIndexToDBMIndex(timerNew), newZone.timerIndexToDBMIndex(timerOld), tempZone.getDbmEntry(0, tempZone.timerIndexToDBMIndex(timerOld))); // int newTimeIndex = newZone.timerIndexToDBMIndex(timerNew); // int oldTimeIndex = newZone.timerIndexToDBMIndex(timerOld); // int value = tempZone.getDbmEntry(0, oldTimeIndex); newZone.setDbmEntry(newZone.timerIndexToDBMIndex(timerOld), newZone.timerIndexToDBMIndex(timerNew), tempZone.getDbmEntry(tempZone.timerIndexToDBMIndex(timerOld), 0)); } } // Set the upper and lower bounds for the new timers. for(LPNTransitionPair pair : newTimers){ // Get all the upper and lower bounds for the new timers. // Get the name for the timer in the i-th column/row of DBM //String tranName = indexToTran.get(i).getName(); String tranName = _lpnList[pair.get_lpnIndex()] .getTransition(pair.get_transitionIndex()).getName(); ExprTree delay = _lpnList[pair.get_lpnIndex()].getDelayTree(tranName); // Get the values of the variables for evaluating the ExprTree. HashMap<String, String> varValues = _lpnList[pair.get_lpnIndex()] .getAllVarsWithValuesAsString(localStates[pair.get_lpnIndex()].getVector()); // Set the upper and lower bound. int upper, lower; if(delay.getOp().equals("uniform")) { ExprTree lowerDelay = delay.getLeftChild(); ExprTree upperDelay = delay.getRightChild(); lower = (int) lowerDelay.evaluateExpr(varValues); upper = (int) upperDelay.evaluateExpr(varValues); } else { lower = (int) delay.evaluateExpr(varValues); upper = lower; } newZone.setLowerBoundByLPNTransitionPair(pair, lower); newZone.setUpperBoundByLPNTransitionPair(pair, upper); } newZone.advance(); newZone.recononicalize(); newZone.checkZoneMaxSize(); return newZone; } /** * Advances time. */ private void advance() { for(int i=0; i<dbmSize(); i++) { _matrix[dbmIndexToMatrixIndex(0)][dbmIndexToMatrixIndex(i)] = getUpperBoundbydbmIndex(i); } } /* (non-Javadoc) * @see java.lang.Object#clone() */ public Zone clone() { // TODO: Check if finished. Zone clonedZone = new Zone(); clonedZone._matrix = new int[this.matrixSize()][this.matrixSize()]; for(int i=0; i<this.matrixSize(); i++) { for(int j=0; j<this.matrixSize(); j++) { clonedZone._matrix[i][j] = this._matrix[i][j]; } } clonedZone._indexToTimerPair = Arrays.copyOf(_indexToTimerPair, _indexToTimerPair.length); clonedZone._hashCode = this._hashCode; clonedZone._lpnList = Arrays.copyOf(this._lpnList, this._lpnList.length); return clonedZone; } /** * Restricts the lower bound of a timer. * * @param timer * The timer to tighten the lower bound. */ private void restrict(int timer) { //int dbmIndex = Arrays.binarySearch(_indexToTimer, timer); _matrix[dbmIndexToMatrixIndex(timer)][dbmIndexToMatrixIndex(0)] = getLowerBoundbydbmIndex(timer); } /** * The list of enabled timers. * @return * The list of all timers that have reached their lower bounds. */ public List<Transition> getEnabledTransitions() { ArrayList<Transition> enabledTransitions = new ArrayList<Transition>(); // Check if the timer exceeds its lower bound staring with the first nonzero // timer. for(int i=1; i<_indexToTimerPair.length; i++) { if(getDbmEntry(0, i) >= -1 * getLowerBoundbydbmIndex(i)) { enabledTransitions.add(_lpnList[_indexToTimerPair[i].get_lpnIndex()] .getTransition(_indexToTimerPair[i].get_transitionIndex())); } } return enabledTransitions; } /** * Gives the list of enabled transitions associated with a particular LPN. * @param LpnIndex * The Index of the LPN the Transitions are a part of. * @return * A List of the Transitions that are enabled in the LPN given by the index. */ public List<Transition> getEnabledTransitions(int LpnIndex){ ArrayList<Transition> enabledTransitions = new ArrayList<Transition>(); // Check if the timer exceeds its lower bound staring with the first nonzero // timer. for(int i=1; i<_indexToTimerPair.length; i++) { if(getDbmEntry(0, i) >= -1 * getLowerBoundbydbmIndex(i)) { LPNTransitionPair ltPair = _indexToTimerPair[i]; if( ltPair.get_lpnIndex() == LpnIndex){ enabledTransitions.add(_lpnList[ltPair.get_lpnIndex()] .getTransition(ltPair.get_transitionIndex())); } } } return enabledTransitions; } /* (non-Javadoc) * @see verification.timed_state_exploration.zone.Zone#getLexicon() */ // public HashMap<Integer, Transition> getLexicon(){ // if(_indexToTransition == null){ // return null; // return new HashMap<Integer, Transition>(_indexToTransition); // public void setLexicon(HashMap<Integer, Transition> lexicon){ // _indexToTransition = lexicon; /** * Gives an array that maps the index of a timer in the DBM to the timer's index. * @return * The array that maps the index of a timer in the DBM to the timer's index. */ // public int[] getIndexToTimer(){ // return Arrays.copyOf(_indexToTimerPair, _indexToTimerPair.length); /** * Calculates a warping value needed to warp a Zone. When a zone is being warped the form * r1*z2 - r1*z1 + r2*z1 becomes important in finding the new values of the zone. For example, * * @param z1 * Upper bound or negative lower bound. * @param z2 * Relative value. * @param r1 * First ratio. * @param r2 * Second ratio. * @return * r1*z2 - r1*z1 + r2*z1 */ public int warp(int z1, int z2, int r1, int r2){ /* * See "Verification of Analog/Mixed-Signal Circuits Using Labeled Hybrid Petri Nets" * by S. Little, D. Walter, C. Myers, R. Thacker, S. Batchu, and T. Yoneda * Section III.C for details on how this function is used and where it comes * from. */ return r1*z2 - r1*z1 + r2*z1; } /** * Warps a Zone. * @return * The warped Zone. */ public Zone dmbWarp(){ /* * See "Verification of Analog/Mixed-Signal Circuits Using Labeled Hybrid Petri Nets" * by S. Little, D. Walter, C. Myers, R. Thacker, S. Batchu, and T. Yoneda * Section III.C for details on how this function is used and where it comes * from. */ return null; } /** * The DiagonalNonZeroException extends the java.lang.RuntimerExpcetion. * The intention is for this exception to be thrown is a Zone has a non zero * entry appear on the diagonal. * * @author Andrew N. Fisher * */ public class DiagonalNonZeroException extends java.lang.RuntimeException { /** * Generated serialVersionUID. */ private static final long serialVersionUID = -3857736741611605411L; /** * Creates a DiagonalNonZeroException. * @param Message * The message to be displayed when the exception is thrown. */ public DiagonalNonZeroException(String Message) { super(Message); } } /** * This exception is thrown when trying to merge two zones whose corresponding timers * do not agree. * @author Andrew N. Fisher * */ // public class IncompatibleZoneException extends java.lang.RuntimeException // // TODO : Check if this class can be removed. // /** // * Generated serialVersionUID // */ // private static final long serialVersionUID = -2453680267411313227L; // public IncompatibleZoneException(String Message) // super(Message); /** * Clears out the lexicon. */ // public static void clearLexicon(){ // _indexToTransition = null; }
package ilg.gnuarmeclipse.core; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; /** * A collection of utilities used for string processing. */ public class StringUtils { /** * Join an array of string. * * @param strArray * array of strings. * @param joiner * a string inserted between elements. * @return a string. */ public static String join(String[] strArray, String joiner) { assert strArray != null; StringBuffer sb = new StringBuffer(); int i = 0; for (String item : strArray) { if (i > 0) { sb.append(joiner); } sb.append(item.trim()); ++i; } return sb.toString(); } /** * Convert hex to long. Considers +/-, ignores 0x and 0X. * * @param hex * a string. * @return a long. */ public static long convertHexLong(String hex) { boolean isNegative = false; if (hex.startsWith("+")) { hex = hex.substring(1); } else if (hex.startsWith("-")) { hex = hex.substring(1); isNegative = true; } if (hex.startsWith("0x") || hex.startsWith("0X")) { hex = hex.substring(2); } long value = Long.valueOf("0" + hex, 16); if (isNegative) value = -value; return value; } /** * Capitalise first letter of a string. * * @param str * a string. * @return a string. */ public static String capitalizeFirst(String str) { if (str.isEmpty()) { return str; } return str.substring(0, 1).toUpperCase() + str.substring(1); } /** * Cosmetise the URL tail to always have a slash, to simplify appending more * path elements. * * @param url * a string. * @return a string. */ public static String cosmetiseUrl(String url) { if (url.endsWith("/")) { return url; } else { return url + "/"; } } /** * Convert an integer to B/kB/MB. * * @param size * an integer size. * @return a string. */ public static String convertSizeToString(int size) { String sizeString; if (size < 1024) { sizeString = String.valueOf(size) + "B"; } else if (size < 1024 * 1024) { sizeString = String.valueOf((size + (1024 / 2)) / 1024) + "kB"; } else { sizeString = String.valueOf((size + ((1024 * 1024) / 2)) / (1024 * 1024)) + "MB"; } return sizeString; } /** * Duplicate single backslashes, i.e. not part of a double backslash group. * * @param str * a string. * @return a string. */ public static String duplicateBackslashes(String str) { if (str.indexOf('\\') < 0) { return str; } String sa[] = str.split("\\\\\\\\"); for (int i = 0; i < sa.length; ++i) { // System.out.println(sa[i]); sa[i] = sa[i].replaceAll("\\\\", "\\\\\\\\"); // System.out.println(sa[i]); } str = StringUtils.join(sa, "\\\\"); // System.out.println(str); return str; } /** * Split the path into segments and return the name. * * @param str * a string with the full path. * @return a string with the name, or the full path if error. */ public static String extractNameFromPath(String str) { if (str == null) { return null; } IPath path = new Path(str); String ret = path.lastSegment(); if (ret != null) { return ret; } return str; } private static enum SplitState { None, InOption, InString }; /** * Split a string containing command line option separated by white spaces * into substrings. Content of quoted options is not parsed, but preserved * as a single substring. Quotes are removed. * * @param str * a command line string, possibly with single/double quotes. * @return array of strings. */ public static List<String> splitCommandLineOptions(String str) { List<String> lst = new ArrayList<String>(); SplitState state = SplitState.None; char quote = 0; StringBuffer sb = new StringBuffer(); for (int i = 0; i < str.length(); ++i) { char ch = str.charAt(i); // a small state machine to split a string in substrings, // preserving quoted parts switch (state) { case None: if (ch == '"' || ch == '\'') { quote = ch; sb.setLength(0); state = SplitState.InString; } else if (ch != ' ' && ch != '\n' && ch != '\r') { sb.setLength(0); sb.append(ch); state = SplitState.InOption; } break; case InOption: if (ch != ' ' && ch != '\n' && ch != '\r') { sb.append(ch); } else { lst.add(sb.toString()); state = SplitState.None; } break; case InString: if (ch != quote) { sb.append(ch); } else { lst.add(sb.toString()); state = SplitState.None; quote = 0; } break; } } if (state == SplitState.InOption || state == SplitState.InString) { lst.add(sb.toString()); } return lst; } /** * Compare two strings that represent numeric versions. * Version numbers are expected to be in the format x.y.z... * * Return * - -1 if v1 is older than v2 * - 0 if they are the same * - +1 if v1 is newer than v2 */ public static int compareNumericVersions(String v1, String v2) { String[] v1digits = v1.split("\\."); String[] v2digits = v2.split("\\."); for (int i = 0; i < v1digits.length && i < v2digits.length; i++) { int d1 = Integer.parseInt(v1digits[i]); int d2 = Integer.parseInt(v2digits[i]); if (d1 < d2) return -1; if (d1 > d2) return 1; } // At this point all digits have the same value. // The version with the longer string wins if (v1digits.length < v2digits.length) return -1; // x.y < x.y.z if (v1digits.length > v2digits.length) return 1; // x.y.z > x.y // If digits are the same and the length are // the same, then versions are identical. return 0; } public String capitalizeFirstLetter(String original) { if (original == null || original.length() == 0) { return original; } return original.substring(0, 1).toUpperCase() + original.substring(1); } }
package info.limpet.ui.editors; import info.limpet.ICommand; import info.limpet.IDocument; import info.limpet.IStoreGroup; import info.limpet.IStoreItem; import info.limpet.impl.DoubleListDocument; import info.limpet.impl.LocationDocument; import info.limpet.impl.NumberDocument; import info.limpet.impl.StringDocument; import info.limpet.ui.Activator; import info.limpet.ui.data_provider.data.DataModel; import info.limpet.ui.data_provider.data.LimpetWrapper; import info.limpet.ui.data_provider.data.NamedList; import javax.measure.quantity.Angle; import javax.measure.quantity.Dimensionless; import javax.measure.unit.Dimension; import javax.measure.unit.NonSI; import javax.measure.unit.SI; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.swt.graphics.Image; public class LimpetLabelProvider extends LabelProvider { public ImageDescriptor getImageDescriptor(Object obj2) { ImageDescriptor res = null; IStoreItem item = null; if (obj2 instanceof LimpetWrapper) { LimpetWrapper wrapper = (LimpetWrapper) obj2; Object obj = wrapper.getSubject(); if (obj instanceof IStoreItem) { item = (IStoreItem) obj; } else if (obj instanceof NamedList) { // is it just one, or multiple? res = Activator.getImageDescriptor("icons/folder.png"); } } else if (obj2 instanceof IStoreItem) { item = (IStoreItem) obj2; } if (item != null) { if (item instanceof IStoreGroup) { // is it just one, or multiple? res = Activator.getImageDescriptor("icons/folder.png"); } if (item instanceof IDocument) { // is it just one, or multiple? IDocument<?> coll = (IDocument<?>) item; if (coll.isQuantity()) { NumberDocument q = (NumberDocument) coll; Dimension dim = q.getUnits().getDimension(); if (dim.equals(Dimension.LENGTH)) { res = Activator.getImageDescriptor("icons/measure.png"); } else if (dim.equals(Angle.UNIT.getDimension())) { res = Activator.getImageDescriptor("icons/angle.png"); } else if (dim.equals(Dimension.MASS)) { res = Activator.getImageDescriptor("icons/weight.png"); } else if (dim.equals(NonSI.DECIBEL)) { res = Activator.getImageDescriptor("icons/volume.png"); } else if (dim.equals(Dimension.LENGTH.times(Dimension.LENGTH).times( Dimension.LENGTH).divide(Dimension.MASS))) { res = Activator.getImageDescriptor("icons/density.png"); } else if (dim.equals(Dimension.TIME)) { res = Activator.getImageDescriptor("icons/time.png"); } else if (dim.equals(Dimensionless.UNIT.getDimension())) { res = Activator.getImageDescriptor("icons/numbers.png"); } else if (dim.equals(SI.HERTZ.getDimension())) { res = Activator.getImageDescriptor("icons/frequency.png"); } else if (dim.equals(Dimension.LENGTH.divide(Dimension.TIME))) { res = Activator.getImageDescriptor("icons/speed.png"); } else { // default image type res = Activator.getImageDescriptor("icons/frequency.png"); } } else if (coll instanceof LocationDocument) { res = Activator.getImageDescriptor("icons/location.png"); } else if (coll instanceof StringDocument) { res = Activator.getImageDescriptor("icons/string.png"); } else if (coll instanceof DoubleListDocument) { res = Activator.getImageDescriptor("icons/string.png"); } } else if (item instanceof ICommand) { res = Activator.getImageDescriptor("icons/interpolate.png"); } else if (obj2 instanceof NamedList) { NamedList nl = (NamedList) obj2; String name = nl.toString(); if (name.equals(DataModel.PRECEDENTS)) { res = Activator.getImageDescriptor("icons/l_arrow.png"); } else if (name.equals(DataModel.DEPENDENTS)) { res = Activator.getImageDescriptor("icons/r_arrow.png"); } } if (res == null) { System.err.println("no icon for:" + item); } } return res; } @Override public Image getImage(Object obj) { Image res = null; ImageDescriptor desc = getImageDescriptor(obj); if (desc != null) { res = Activator.getImageFromRegistry(desc); } return res; } }
package uk.ac.ebi.biosamples; import java.net.URI; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.context.annotation.Profile; import org.springframework.core.ParameterizedTypeReference; import org.springframework.hateoas.Link; import org.springframework.hateoas.MediaTypes; import org.springframework.hateoas.PagedResources; import org.springframework.hateoas.Resource; import org.springframework.hateoas.ResourceSupport; import org.springframework.hateoas.hal.Jackson2HalModule; import org.springframework.hateoas.mvc.TypeConstrainedMappingJackson2HttpMessageConverter; import org.springframework.http.RequestEntity; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.stereotype.Component; import org.springframework.web.client.RestOperations; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponents; import org.springframework.web.util.UriComponentsBuilder; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Lists; import uk.ac.ebi.biosamples.client.BioSamplesClient; import uk.ac.ebi.biosamples.model.Attribute; import uk.ac.ebi.biosamples.model.Relationship; import uk.ac.ebi.biosamples.model.Sample; @Component @Profile({"big"}) public class BigIntegration extends AbstractIntegration { private Logger log = LoggerFactory.getLogger(this.getClass()); private final RestOperations restOperations; private final BioSamplesProperties bioSamplesProperties; //must be over 1000 private final int noSamples = 5000; public BigIntegration(BioSamplesClient client, RestTemplateBuilder restTemplateBuilder, BioSamplesProperties bioSamplesProperties) { super(client); RestTemplate restTemplate = restTemplateBuilder.build(); //make sure there is a application/hal+json converter //traverson will make its own but not if we want to customize the resttemplate in any way (e.g. caching) List<HttpMessageConverter<?>> converters = restTemplate.getMessageConverters(); ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new Jackson2HalModule()); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); MappingJackson2HttpMessageConverter halConverter = new TypeConstrainedMappingJackson2HttpMessageConverter(ResourceSupport.class); halConverter.setObjectMapper(mapper); halConverter.setSupportedMediaTypes(Arrays.asList(MediaTypes.HAL_JSON)); //make sure this is inserted first converters.add(0, halConverter); restTemplate.setMessageConverters(converters); this.restOperations = restTemplate; this.bioSamplesProperties = bioSamplesProperties; } @Override protected void phaseOne() { List<Sample> samples = new ArrayList<>(); //generate a root sample Sample root = generateSample(0, Collections.emptyList(), null); samples.add(root); //generate a large number of samples for (int i = 1; i < noSamples; i++) { Sample sample = generateSample(i, Collections.emptyList(), root); samples.add(sample); } //generate one sample to rule them all samples.add(generateSample(noSamples, samples, null)); //time how long it takes to submit them long startTime = System.nanoTime(); client.persistSamples(samples); long endTime = System.nanoTime(); double elapsedMs = (int) ((endTime-startTime)/1000000l); double msPerSample = elapsedMs/noSamples; log.info("Submitted "+noSamples+" samples in "+elapsedMs+"ms ("+msPerSample+"ms each)"); if (msPerSample > 100) { throw new RuntimeException("Took more than 100ms per sample to submit ("+msPerSample+"ms each)"); } } @Override protected void phaseTwo() { long startTime; long endTime; double elapsedMs; // time how long it takes to get the highly connected sample startTime = System.nanoTime(); client.fetchSample("SAMbig"+noSamples); endTime = System.nanoTime(); elapsedMs = (int) ((endTime-startTime)/1000000l); if (elapsedMs > 5000) { throw new RuntimeException("Took more than 5000ms to fetch highly-connected sample ("+elapsedMs+"ms)"); } startTime = System.nanoTime(); client.fetchSample("SAMbig"+0); endTime = System.nanoTime(); elapsedMs = (int) ((endTime-startTime)/1000000l); if (elapsedMs > 5000) { throw new RuntimeException("Took more than 5000ms to fetch highly-connected sample ("+elapsedMs+"ms)"); } //time how long it takes to loop over all of them startTime = System.nanoTime(); for (Resource<Sample> sample : client.fetchSampleResourceAll()) { //do nothing } endTime = System.nanoTime(); elapsedMs = (int) ((endTime-startTime)/1000000l); if (elapsedMs > 5000) { throw new RuntimeException("Took more than 5000ms to fetch all samples ("+elapsedMs+"ms)"); } //TODO check HAL links for search term and facets are persistent over paging etc URI uri = UriComponentsBuilder .fromUri(bioSamplesProperties.getBiosamplesClientUri()) .pathSegment("samples") .queryParam("text", "Sample") .queryParam("filter", "attr:organism:Homo sapiens") .build().encode().toUri(); log.info("checking HAL links on "+uri); ResponseEntity<PagedResources<Resource<Sample>>> responseEntity = restOperations.exchange( RequestEntity.get(uri).accept(MediaTypes.HAL_JSON).build(), new ParameterizedTypeReference<PagedResources<Resource<Sample>>>(){}); PagedResources<Resource<Sample>> page = responseEntity.getBody(); log.info("looking for links in "+page); for (Link link : page.getLinks()) { log.info("Found link "+link); } Link firstLink = page.getLink(Link.REL_FIRST); UriComponents firstLinkUriComponents = UriComponentsBuilder.fromUriString(firstLink.getHref()) .build(); String firstFilter = firstLinkUriComponents.getQueryParams().get("filter").get(0); if (!"attr:organism:Homo%20sapiens".equals(firstFilter)) { throw new RuntimeException("Expected first relationship URL to include parameter filter with value 'attr:organism:Homo sapiens' but got '" +firstFilter+"'"); } String firstText = firstLinkUriComponents.getQueryParams().get("text").get(0); if (!"Sample".equals(firstText)) { throw new RuntimeException("Expected first relationship URL to include parameter text with value 'Sample' but got '" +firstText+"'"); } } @Override protected void phaseThree() { // TODO Auto-generated method stub } @Override protected void phaseFour() { // TODO Auto-generated method stub } @Override protected void phaseFive() { // TODO Auto-generated method stub } public Sample generateSample(int i, List<Sample> samples, Sample root) { Instant update = Instant.parse("2016-05-05T11:36:57.00Z"); Instant release = Instant.parse("2016-04-01T11:36:57.00Z"); String domain = "self.BiosampleIntegrationTest"; SortedSet<Attribute> attributes = new TreeSet<>(); attributes.add( Attribute.build("organism", "Homo sapiens", Lists.newArrayList("http://purl.obolibrary.org/obo/NCBITaxon_9606"), null)); SortedSet<Relationship> relationships = new TreeSet<>(); for (Sample other : samples) { relationships.add(Relationship.build("SAMbig"+i, "derived from", other.getAccession())); } if (root != null) { relationships.add(Relationship.build("SAMbig"+i, "derived from", root.getAccession())); } Sample sample = Sample.build("big sample "+i, "SAMbig"+i, domain, release, update, attributes, relationships, null, null, null, null); log.trace("built "+sample.getAccession()); return sample; } }
package org.intermine.dataloader; import java.io.File; import java.io.FileInputStream; import org.apache.tools.ant.Task; import org.apache.tools.ant.BuildException; /** * Uses an IntegrationWriter to load data from XML format * * @author Richard Smith * @author Andrew Varley * @author Matthew Wakeling */ public class XmlDataLoaderTask extends Task { protected String integrationWriter; protected File xmlFile; protected String sourceName; /** * Set the IntegrationWriter. * * @param integrationWriter the name of the IntegrationWriter */ public void setIntegrationWriter(String integrationWriter) { this.integrationWriter = integrationWriter; } /** * Set the XML file to load data from. * * @param xmlFile the XML file */ public void setXmlFile(File xmlFile) { this.xmlFile = xmlFile; } /** * Set the source name, as used by primary key priority config. * * @param sourceName the name of the data source */ public void setSourceName(String sourceName) { this.sourceName = sourceName; } /** * @see Task#execute * @throws BuildException */ public void execute() throws BuildException { if (integrationWriter == null) { throw new BuildException("integrationWriter attribute is not set"); } if (xmlFile == null) { throw new BuildException("xmlFile attribute is not set"); } if (sourceName == null) { throw new BuildException("sourceName attribute is not set"); } try { IntegrationWriter iw = IntegrationWriterFactory.getIntegrationWriter(integrationWriter); new XmlDataLoader(iw).processXml(new FileInputStream(xmlFile), iw.getMainSource(sourceName), iw.getSkeletonSource(sourceName)); } catch (Exception e) { throw new BuildException("Exception while reading from: " + xmlFile + " with source " + sourceName, e); } } }
package org.intermine.web; import java.util.Iterator; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.intermine.cache.InterMineCache; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.ObjectStoreException; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; /** * Action to create a new TemplateQuery from current query. * * @author Thomas Riley */ public class CreateTemplateAction extends InterMineAction { protected static final Logger LOG = Logger.getLogger(CreateTemplateAction.class); /** * Take the current query and TemplateBuildState from the session and create a * TemplateQuery. Put the query in the user's profile. * * @param mapping The ActionMapping used to select this instance * @param form The optional ActionForm bean for this request (if any) * @param request The HTTP request we are processing * @param response The HTTP response we are creating * @return an ActionForward object defining where control goes next * * @exception Exception if the application business logic throws * an exception */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); ServletContext servletContext = session.getServletContext(); Profile profile = (Profile) session.getAttribute(Constants.PROFILE); ObjectStore os = (ObjectStore) servletContext.getAttribute(Constants.OBJECTSTORE); PathQuery query = (PathQuery) session.getAttribute(Constants.QUERY); TemplateBuildState tbs = (TemplateBuildState) session.getAttribute(Constants.TEMPLATE_BUILD_STATE); boolean seenProblem = false; // Check whether query has at least one constraint and at least one output if (query.getView().size() == 0) { recordError(new ActionMessage("errors.createtemplate.nooutputs"), request); seenProblem = true; } Iterator iter = query.getNodes().values().iterator(); boolean foundEditableConstraint = false; while (iter.hasNext()) { PathNode node = (PathNode) iter.next(); if (node.isAttribute()) { Iterator citer = node.getConstraints().iterator(); while (citer.hasNext()) { Constraint c = (Constraint) citer.next(); if (c.isEditable()) { foundEditableConstraint = true; break; } } } } if (!foundEditableConstraint) { recordError(new ActionMessage("errors.createtemplate.noconstraints"), request); seenProblem = true; } // Check whether there is a template name clash if (profile.getSavedTemplates().containsKey(tbs.getName()) && (tbs.getUpdatingTemplate() == null || !tbs.getUpdatingTemplate().getName().equals(tbs.getName()))) { recordError(new ActionMessage("errors.createtemplate.existing", tbs.getName()), request); seenProblem = true; } if (StringUtils.isEmpty(tbs.getName())) { recordError(new ActionMessage("errors.required", "Template name"), request); seenProblem = true; } if (StringUtils.isEmpty(tbs.getDescription())) { recordError(new ActionMessage("errors.required", "Template description", tbs.getName()), request); seenProblem = true; } // Ensure that we can actually execute the query if (!seenProblem) { try { if (query.getInfo() == null) { query.setInfo(os.estimate(MainHelper.makeQuery(query, profile.getSavedBags()))); } } catch (ObjectStoreException e) { recordError(new ActionMessage("errors.query.objectstoreerror"), request, e, LOG); seenProblem = true; } } if (seenProblem) { return mapping.findForward("query"); } TemplateQuery template = TemplateHelper.buildTemplateQuery(tbs, query); TemplateQuery editing = tbs.getUpdatingTemplate(); String key = (editing == null) ? "templateBuilder.templateCreated" : "templateBuilder.templateUpdated"; recordMessage(new ActionMessage(key, template.getName()), request); // Replace template if needed if (editing != null) { profile.deleteTemplate(editing.getName()); } profile.saveTemplate(template.getName(), template); // If superuser then rebuild shared templates if (profile.getUsername() != null && profile.getUsername().equals (servletContext.getAttribute(Constants.SUPERUSER_ACCOUNT))) { TemplateRepository tr = TemplateRepository.getTemplateRepository(servletContext); if (editing != null) { tr.globalTemplateUpdated(template); } else { tr.globalTemplateAdded(template); } } session.removeAttribute(Constants.TEMPLATE_BUILD_STATE); cleanCache(servletContext, template); return mapping.findForward("history"); } /** * Remove all entries from the cache that mention the given template. */ private void cleanCache(ServletContext servletContext, TemplateQuery template) { InterMineCache cache = ServletMethods.getGlobalCache(servletContext); cache.flushByKey(TemplateHelper.TEMPLATE_TABLE_CACHE_TAG, new Object[] {template.getName(), null, null}); } }
package org.intermine.web.struts; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.intermine.api.InterMineAPI; import org.intermine.api.profile.InterMineBag; import org.intermine.api.profile.Profile; import org.intermine.objectstore.ObjectStoreException; import org.intermine.web.logic.results.PagedTable; import org.intermine.web.logic.session.SessionMethods; /** * Saves selected items in a new bag or combines with existing bag. * * @author Andrew Varley * @author Thomas Riley * @author Kim Rutherford */ public class SaveBagAction extends InterMineAction { protected static final Logger LOG = Logger.getLogger(SaveBagAction.class); /** * @param mapping The ActionMapping used to select this instance * @param form The optional ActionForm bean for this request (if any) * @param request The HTTP request we are processing * @param response The HTTP response we are creating * @return an ActionForward object defining where control goes next * @exception Exception if the application business logic throws * an exception */ @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { return saveBag(mapping, form, request, response); } /** * The batch size to use when we need to iterate through the whole result set. */ public static final int BIG_BATCH_SIZE = 10000; /** * Save the selected objects to a bag on the session * @param mapping The ActionMapping used to select this instance * @param form The optional ActionForm bean for this request (if any) * @param request The HTTP request we are processing * @param response The HTTP response we are creating * @return an ActionForward object defining where control goes next */ public ActionForward saveBag(ActionMapping mapping, ActionForm form, HttpServletRequest request, @SuppressWarnings("unused") HttpServletResponse response) { HttpSession session = request.getSession(); Profile profile = SessionMethods.getProfile(session); PagedTable pt = SessionMethods.getResultsTable(session, request.getParameter("table")); SaveBagForm sbf = (SaveBagForm) form; String bagName = null; String operation = ""; if (request.getParameter("saveNewBag") != null || (sbf.getOperationButton() != null && "saveNewBag".equals(sbf.getOperationButton()))) { bagName = sbf.getNewBagName(); operation = "saveNewBag"; } else { bagName = sbf.getExistingBagName(); operation = "addToBag"; } if (bagName == null) { return null; } if (pt.isEmptySelection()) { ActionMessage actionMessage = new ActionMessage("errors.bag.empty"); recordError(actionMessage, request); return mapping.findForward("results"); } InterMineBag bag = profile.getSavedBags().get(bagName); if ((bag != null) && (!bag.getType().equals(pt.getSelectedClass()))) { ActionMessage actionMessage = new ActionMessage("bag.moreThanOneType"); recordError(actionMessage, request); return mapping.findForward("results"); } try { if (bag == null) { InterMineAPI im = SessionMethods.getInterMineAPI(session); bag = profile.createBag(bagName, pt.getSelectedClass(), "", im.getClassKeys()); } pt.addSelectedToBag(bag); recordMessage(new ActionMessage("bag.saved", bagName), request); SessionMethods.invalidateBagTable(session, bagName); } catch (ObjectStoreException e) { LOG.error("Failed to save bag", e); recordError(new ActionMessage("An error occured while saving the bag"), request); return mapping.findForward("results"); } if ("saveNewBag".equals(operation)) { return new ForwardParameters(mapping.findForward("bag")).addParameter("bagName", bag.getName()).forward(); } return mapping.findForward("results"); } }
package org.javarosa.j2me.file; import java.util.Enumeration; import java.util.Vector; import javax.microedition.io.file.FileSystemRegistry; import org.javarosa.core.reference.ReferenceManager; import org.javarosa.core.services.Logger; import org.javarosa.core.services.PropertyManager; import org.javarosa.core.services.properties.IPropertyRules; /** * The J2meFileSystemProperties class provides a clean and quick * interface for configuring the parameters associated with the * local file system. Registering the class provides the settings * interface with a way to determine and configure a local * RootFactory (operating with the ReferenceManager in the * local runtime environment), and it provides a helper method * to initialize the most like-useful file root on startup, thus * making jr://file/ references work reliably without manual * configuration or intervention. * * @author ctsims * */ public class J2meFileSystemProperties implements IPropertyRules { public static final String FILE_SYSTEM_ROOT = "j2me-fileroot"; Vector<String> fileroots; J2meFileRoot currentRoot; public J2meFileSystemProperties() { } private Vector<String> roots() { if(fileroots == null) { fileroots = new Vector<String>(); try { for(Enumeration en = FileSystemRegistry.listRoots(); en.hasMoreElements() ; ) { String root = (String)en.nextElement(); if(root.endsWith("/")) { //cut off any trailing /'s root = root.substring(0, root.length() -1); fileroots.addElement(root); } } } catch(SecurityException e) { this.securityException(e); if(fileroots.size() > 0 ) { //got something.... return fileroots; } else { //something happened, probably the user denying access to list the roots. //return an empty vector, but set fileroots to null so that it'll try again later fileroots = null; return new Vector<String>(); } } catch(NullPointerException npe) { //This exists simply to catch an error in some (MicroEmu's) implementations of listroots return new Vector<String>(); } } return fileroots; } /** * @return A root in the local environment which is deemed * to be likely to be the most useful with which to store * and retrieve data, if one exists. Null if no file roots * are available in the current environment. */ public String getPreferredDefaultRoot() { Vector<String> preferredRoots = getCardRoots(); Vector<String> roots = roots(); for(String root : roots) { if(preferredRoots.contains(root.toLowerCase())) { return root; } } //no memory card roots found, just go with the first one if(roots.size() > 0) { return roots().elementAt(0); } return null; } /** * Makes available a file reference in the current environment which is set * to either be the current property value for a file system root, or is * set to the preferred default root inferred by the getPreferredDefaultRoot() * method. */ public void initializeFileReference() { String root = PropertyManager._().getSingularProperty(FILE_SYSTEM_ROOT); if(root == null) { root = getPreferredDefaultRoot(); if(root != null) { PropertyManager._().setProperty(FILE_SYSTEM_ROOT, root); } } if(root != null) { registerReferenceFactory(root); } } /** * @return The common roots for memory cards */ private Vector<String> getCardRoots() { Vector<String> cardRoots = new Vector<String>(); //For Nokia Phones cardRoots.addElement("e:"); //For BlackBerry's cardRoots.addElement("sdcard"); //For (sony?) cardRoots.addElement("memorystick"); return cardRoots; } /** * @return The common roots for phone memory */ private Vector<String> getPhoneMemoryRoots() { Vector<String> phoneRoots = new Vector<String>(); //For Nokia Phones phoneRoots.addElement("c:"); //For BlackBerry's phoneRoots.addElement(""); //For (sony?) phoneRoots.addElement("memorystick"); //For Emulators phoneRoots.addElement("root1"); return phoneRoots; } /* (non-Javadoc) * @see org.javarosa.core.services.properties.IPropertyRules#allowableProperties() */ public Vector allowableProperties() { Vector properties = new Vector(); properties.addElement(FILE_SYSTEM_ROOT); return properties; } /* (non-Javadoc) * @see org.javarosa.core.services.properties.IPropertyRules#allowableValues(java.lang.String) */ public Vector allowableValues(String propertyName) { if(propertyName.equals(FILE_SYSTEM_ROOT)) { return roots(); } return null; } /* (non-Javadoc) * @see org.javarosa.core.services.properties.IPropertyRules#checkPropertyAllowed(java.lang.String) */ public boolean checkPropertyAllowed(String propertyName) { if(propertyName.equals(FILE_SYSTEM_ROOT)) { return true; } return false; } /* (non-Javadoc) * @see org.javarosa.core.services.properties.IPropertyRules#checkPropertyUserReadOnly(java.lang.String) */ public boolean checkPropertyUserReadOnly(String propertyName) { if(propertyName.equals(FILE_SYSTEM_ROOT)) { return false; } return false; } /* (non-Javadoc) * @see org.javarosa.core.services.properties.IPropertyRules#checkValueAllowed(java.lang.String, java.lang.String) */ public boolean checkValueAllowed(String propertyName, String potentialValue) { if(propertyName.equals(FILE_SYSTEM_ROOT) && roots().contains(potentialValue)) { return true; } return false; } /* (non-Javadoc) * @see org.javarosa.core.services.properties.IPropertyRules#getHumanReadableDescription(java.lang.String) */ public String getHumanReadableDescription(String propertyName) { if(propertyName.equals(FILE_SYSTEM_ROOT)) { return "File System Root"; } return null; } /* (non-Javadoc) * @see org.javarosa.core.services.properties.IPropertyRules#getHumanReadableValue(java.lang.String, java.lang.String) */ public String getHumanReadableValue(String propertyName, String value) { if(propertyName.equals(FILE_SYSTEM_ROOT)) { if(getCardRoots().contains(value.toLowerCase())) { return "Memory Card (" + value + ")"; } else if(getPhoneMemoryRoots().contains(value.toLowerCase())) { return "File System (" + value + ")"; } else { return "Other (" + value + ")"; } } return null; } /* (non-Javadoc) * @see org.javarosa.core.services.properties.IPropertyRules#handlePropertyChanges(java.lang.String) */ public void handlePropertyChanges(String propertyName) { if(propertyName.equals(FILE_SYSTEM_ROOT)) { registerReferenceFactory(PropertyManager._().getSingularProperty(FILE_SYSTEM_ROOT)); } } private void registerReferenceFactory(String newRoot) { if(currentRoot != null) { ReferenceManager._().removeReferenceFactory(currentRoot); } if(newRoot != null) { currentRoot = root(newRoot); ReferenceManager._().addReferenceFactory(currentRoot); } } protected J2meFileRoot root(String root) { return new J2meFileRoot(root); } protected void securityException(SecurityException e) { Logger.log("security_file", e.getMessage()); } }
package com.intellij.ide.actions; import com.intellij.codeInsight.daemon.JavaErrorBundle; import com.intellij.codeInsight.daemon.impl.analysis.HighlightClassUtil; import com.intellij.codeInsight.daemon.impl.analysis.HighlightingFeature; import com.intellij.core.JavaPsiBundle; import com.intellij.ide.fileTemplates.*; import com.intellij.ide.highlighter.JavaFileType; import com.intellij.java.JavaBundle; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.InputValidatorEx; import com.intellij.openapi.util.text.StringUtil; import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.*; import com.intellij.psi.util.PsiUtil; import com.intellij.util.IncorrectOperationException; import com.intellij.util.PlatformIcons; import org.jetbrains.annotations.NotNull; /** * The standard "New Class" action. */ public class CreateClassAction extends JavaCreateTemplateInPackageAction<PsiClass> implements DumbAware { public CreateClassAction() { super("", JavaBundle.message("action.create.new.class.description"), PlatformIcons.CLASS_ICON, true); } @Override protected void buildDialog(final Project project, PsiDirectory directory, CreateFileFromTemplateDialog.Builder builder) { builder .setTitle(JavaBundle.message("action.create.new.class")) .addKind(JavaPsiBundle.message("node.class.tooltip"), PlatformIcons.CLASS_ICON, JavaTemplateUtil.INTERNAL_CLASS_TEMPLATE_NAME) .addKind(JavaPsiBundle.message("node.interface.tooltip"), PlatformIcons.INTERFACE_ICON, JavaTemplateUtil.INTERNAL_INTERFACE_TEMPLATE_NAME); if (HighlightingFeature.RECORDS.isAvailable(directory)) { builder.addKind(JavaPsiBundle.message("node.record.tooltip"), PlatformIcons.RECORD_ICON, JavaTemplateUtil.INTERNAL_RECORD_TEMPLATE_NAME); } LanguageLevel level = PsiUtil.getLanguageLevel(directory); if (level.isAtLeast(LanguageLevel.JDK_1_5)) { builder.addKind(JavaPsiBundle.message("node.enum.tooltip"), PlatformIcons.ENUM_ICON, JavaTemplateUtil.INTERNAL_ENUM_TEMPLATE_NAME); builder.addKind(JavaPsiBundle.message("node.annotation.tooltip"), PlatformIcons.ANNOTATION_TYPE_ICON, JavaTemplateUtil.INTERNAL_ANNOTATION_TYPE_TEMPLATE_NAME); } PsiDirectory[] dirs = {directory}; for (FileTemplate template : FileTemplateManager.getInstance(project).getAllTemplates()) { final @NotNull CreateFromTemplateHandler handler = FileTemplateUtil.findHandler(template); if (handler instanceof JavaCreateFromTemplateHandler && handler.handlesTemplate(template) && handler.canCreate(dirs)) { builder.addKind(template.getName(), JavaFileType.INSTANCE.getIcon(), template.getName()); } } builder.setValidator(new InputValidatorEx() { @Override public String getErrorText(String inputString) { if (inputString.length() > 0 && !PsiNameHelper.getInstance(project).isQualifiedName(inputString)) { return "This is not a valid Java qualified name"; } String shortName = StringUtil.getShortName(inputString); if (HighlightClassUtil.isRestrictedIdentifier(shortName, level)) { return JavaErrorBundle.message("restricted.identifier", shortName); } return null; } @Override public boolean checkInput(String inputString) { return true; } @Override public boolean canClose(String inputString) { return !StringUtil.isEmptyOrSpaces(inputString) && getErrorText(inputString) == null; } }); } @Override protected String removeExtension(String templateName, String className) { return StringUtil.trimEnd(className, ".java"); } @NotNull @Override protected String getErrorTitle() { return JavaBundle.message("title.cannot.create.class"); } @Override protected String getActionName(PsiDirectory directory, @NotNull String newName, String templateName) { return JavaBundle.message("progress.creating.class", StringUtil.getQualifiedName(JavaDirectoryService.getInstance().getPackage(directory).getQualifiedName(), newName)); } @Override public boolean startInWriteAction() { return false; } @Override protected final PsiClass doCreate(PsiDirectory dir, String className, String templateName) throws IncorrectOperationException { return JavaDirectoryService.getInstance().createClass(dir, className, templateName, true); } @Override protected PsiElement getNavigationElement(@NotNull PsiClass createdElement) { return createdElement.getLBrace(); } }
package org.jbehave.core.embedder; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Properties; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadPoolExecutor; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import org.jbehave.core.ConfigurableEmbedder; import org.jbehave.core.Embeddable; import org.jbehave.core.configuration.Configuration; import org.jbehave.core.configuration.MostUsefulConfiguration; import org.jbehave.core.embedder.StoryManager.ThrowableStory; import org.jbehave.core.embedder.StoryRunner.State; import org.jbehave.core.failures.BatchFailures; import org.jbehave.core.failures.FailingUponPendingStep; import org.jbehave.core.junit.AnnotatedEmbedderRunner; import org.jbehave.core.junit.AnnotatedEmbedderUtils; import org.jbehave.core.model.Story; import org.jbehave.core.model.StoryMaps; import org.jbehave.core.reporters.ReportsCount; import org.jbehave.core.reporters.StepdocReporter; import org.jbehave.core.reporters.StoryReporterBuilder; import org.jbehave.core.reporters.ViewGenerator; import org.jbehave.core.steps.CandidateSteps; import org.jbehave.core.steps.InjectableStepsFactory; import org.jbehave.core.steps.ProvidedStepsFactory; import org.jbehave.core.steps.StepCollector.Stage; import org.jbehave.core.steps.StepFinder; import org.jbehave.core.steps.Stepdoc; /** * The Embedder is a facade allowing all functionality to be embedded into other * run contexts, such as IDEs (e.g. via JUnit support) or CLIs (via Ant or * Maven). */ public class Embedder { private StoryMapper storyMapper; private StoryRunner storyRunner; private EmbedderMonitor embedderMonitor; private EmbedderClassLoader classLoader = new EmbedderClassLoader(this.getClass().getClassLoader()); private EmbedderControls embedderControls = new EmbedderControls(); private EmbedderFailureStrategy embedderFailureStrategy = new ThrowingRunningStoriesFailed(); private Configuration configuration = new MostUsefulConfiguration(); private List<CandidateSteps> candidateSteps = new ArrayList<CandidateSteps>(); private InjectableStepsFactory stepsFactory; private List<String> metaFilters = Arrays.asList(); private Properties systemProperties = new Properties(); private ExecutorService executorService; private boolean executorServiceCreated; public Embedder() { this(new StoryMapper(), new StoryRunner(), new PrintStreamEmbedderMonitor()); } public Embedder(StoryMapper storyMapper, StoryRunner storyRunner, EmbedderMonitor embedderMonitor) { this.storyMapper = storyMapper; this.storyRunner = storyRunner; this.embedderMonitor = embedderMonitor; } public void mapStoriesAsPaths(List<String> storyPaths) { EmbedderControls embedderControls = embedderControls(); embedderMonitor.usingControls(embedderControls); if (embedderControls.skip()) { embedderMonitor.storiesSkipped(storyPaths); return; } processSystemProperties(); for (String storyPath : storyPaths) { Story story = storyRunner.storyOfPath(configuration, storyPath); embedderMonitor.mappingStory(storyPath, metaFilters); storyMapper.map(story, new MetaFilter("")); for (String filter : metaFilters) { storyMapper.map(story, new MetaFilter(filter)); } } generateMapsView(storyMapper.getStoryMaps()); } private void generateMapsView(StoryMaps storyMaps) { Configuration configuration = configuration(); StoryReporterBuilder builder = configuration.storyReporterBuilder(); File outputDirectory = builder.outputDirectory(); Properties viewResources = builder.viewResources(); ViewGenerator viewGenerator = configuration.viewGenerator(); try { embedderMonitor.generatingMapsView(outputDirectory, storyMaps, viewResources); viewGenerator.generateMapsView(outputDirectory, storyMaps, viewResources); } catch (RuntimeException e) { embedderMonitor.mapsViewGenerationFailed(outputDirectory, storyMaps, viewResources, e); throw new ViewGenerationFailed(outputDirectory, storyMaps, viewResources, e); } } public void runAsEmbeddables(List<String> classNames) { EmbedderControls embedderControls = embedderControls(); embedderMonitor.usingControls(embedderControls); if (embedderControls.skip()) { embedderMonitor.embeddablesSkipped(classNames); return; } BatchFailures failures = new BatchFailures(embedderControls.verboseFailures()); for (Embeddable embeddable : embeddables(classNames, classLoader())) { String name = embeddable.getClass().getName(); try { embedderMonitor.runningEmbeddable(name); embeddable.useEmbedder(this); embeddable.run(); } catch (Throwable e) { if (embedderControls.batch()) { // collect and postpone decision to throw exception failures.put(name, e); } else { if (ignoreFailure(embedderControls)) { embedderMonitor.embeddableFailed(name, e); } else { throw new RunningEmbeddablesFailed(name, e); } } } } if (embedderControls.batch() && failures.size() > 0) { if (ignoreFailure(embedderControls)) { embedderMonitor.batchFailed(failures); } else { throw new RunningEmbeddablesFailed(failures); } } } private boolean ignoreFailure(EmbedderControls embedderControls) { boolean ignore = embedderControls.ignoreFailureInStories(); if (embedderControls.generateViewAfterStories()) { ignore = ignore && embedderControls.ignoreFailureInView(); } return ignore; } private List<Embeddable> embeddables(List<String> classNames, EmbedderClassLoader classLoader) { List<Embeddable> embeddables = new ArrayList<Embeddable>(); for (String className : classNames) { if (!classLoader.isAbstract(className)) { embeddables.add(classLoader.newInstance(Embeddable.class, className)); } } return embeddables; } public void runStoriesWithAnnotatedEmbedderRunner(List<String> classNames) { EmbedderClassLoader classLoader = classLoader(); for (String className : classNames) { embedderMonitor.runningWithAnnotatedEmbedderRunner(className); AnnotatedEmbedderRunner runner = AnnotatedEmbedderUtils.annotatedEmbedderRunner(className, classLoader); try { Object annotatedInstance = runner.createTest(); if (annotatedInstance instanceof Embeddable) { ((Embeddable) annotatedInstance).run(); } else { embedderMonitor.annotatedInstanceNotOfType(annotatedInstance, Embeddable.class); } } catch (Throwable e) { throw new AnnotatedEmbedderRunFailed(runner, e); } } } public void runStoriesAsPaths(List<String> storyPaths) { processSystemProperties(); EmbedderMonitor embedderMonitor = embedderMonitor(); EmbedderControls embedderControls = embedderControls(); embedderMonitor.usingControls(embedderControls); if (embedderControls.skip()) { embedderMonitor.storiesSkipped(storyPaths); return; } try { // set up run context Configuration configuration = configuration(); configureThreads(configuration, embedderControls.threads()); InjectableStepsFactory stepsFactory = stepsFactory(); StoryRunner storyRunner = storyRunner(); StoryManager storyManager = new StoryManager(configuration, embedderControls, embedderMonitor, executorService(), stepsFactory, storyRunner); MetaFilter filter = metaFilter(); BatchFailures failures = new BatchFailures(embedderControls.verboseFailures()); // run before stories List<CandidateSteps> candidateSteps = stepsFactory.createCandidateSteps(); State beforeStories = storyRunner.runBeforeOrAfterStories(configuration, candidateSteps, Stage.BEFORE); if (storyRunner.failed(beforeStories)) { failures.put(beforeStories.toString(), storyRunner.failure(beforeStories)); } // run stories storyManager.runningStories(storyPaths, filter, failures, beforeStories); storyManager.waitUntilAllDoneOrFailed(failures); List<Story> notAllowed = storyManager.notAllowedBy(filter); if (!notAllowed.isEmpty()) { embedderMonitor.storiesNotAllowed(notAllowed, filter); } // run after stories State afterStories = storyRunner.runBeforeOrAfterStories(configuration, candidateSteps, Stage.AFTER); if (storyRunner.failed(afterStories)) { failures.put(afterStories.toString(), storyRunner.failure(afterStories)); } // check for failures handleFailures(embedderMonitor, embedderControls, failures); } finally { // generate reports view regardless of failures in running stories // (if configured to do so) if (embedderControls.generateViewAfterStories()) { generateReportsView(); } shutdownExecutorService(); } } private void handleFailures(EmbedderMonitor embedderMonitor, EmbedderControls embedderControls, BatchFailures failures) { if (failures.size() > 0) { if (embedderControls.ignoreFailureInStories()) { embedderMonitor.batchFailed(failures); } else { embedderFailureStrategy.handleFailures(failures); } } } /** * @deprecated From 3.6 use {@link enqueueStoryAsText(String, String) */ public Future<ThrowableStory> enqueueStory(BatchFailures batchFailures, MetaFilter filter, List<Future<ThrowableStory>> futures, String storyPath, Story story) { StoryManager storyManager = storyManager(); return storyManager.runningStory(storyPath, story, filter, batchFailures, null).getFuture(); } public Future<ThrowableStory> enqueueStoryAsText(String storyAsText, String storyId) { StoryManager storyManager = storyManager(); Story story = storyManager.storyOfText(storyAsText, storyId); MetaFilter filter = metaFilter(); return storyManager.runningStory(storyId, story, filter, new BatchFailures(), null).getFuture(); } private StoryManager storyManager() { return new StoryManager(configuration(), embedderControls(), embedderMonitor(), executorService(), stepsFactory(), storyRunner()); } private void configureThreads(Configuration configuration, int threads) { StoryReporterBuilder reporterBuilder = configuration.storyReporterBuilder(); reporterBuilder.withMultiThreading(threads > 1); configuration.useStoryReporterBuilder(reporterBuilder); } public void generateReportsView() { StoryReporterBuilder builder = configuration().storyReporterBuilder(); File outputDirectory = builder.outputDirectory(); List<String> formatNames = builder.formatNames(true); generateReportsView(outputDirectory, formatNames, builder.viewResources()); } public void generateReportsView(File outputDirectory, List<String> formats, Properties viewResources) { EmbedderControls embedderControls = embedderControls(); EmbedderMonitor embedderMonitor = embedderMonitor(); if (embedderControls.skip()) { embedderMonitor.reportsViewNotGenerated(); return; } ViewGenerator viewGenerator = configuration().viewGenerator(); try { embedderMonitor.generatingReportsView(outputDirectory, formats, viewResources); viewGenerator.generateReportsView(outputDirectory, formats, viewResources); } catch (RuntimeException e) { embedderMonitor.reportsViewGenerationFailed(outputDirectory, formats, viewResources, e); throw new ViewGenerationFailed(outputDirectory, formats, viewResources, e); } ReportsCount count = viewGenerator.getReportsCount(); embedderMonitor.reportsViewGenerated(count); handleFailures(embedderMonitor, embedderControls, count); } private void handleFailures(EmbedderMonitor embedderMonitor, EmbedderControls embedderControls, ReportsCount count) { boolean failed = count.failed(); if (configuration().pendingStepStrategy() instanceof FailingUponPendingStep) { failed = failed || count.pending(); } if (failed) { if (embedderControls.ignoreFailureInView()) { embedderMonitor.reportsViewFailures(count); } else { embedderFailureStrategy.handleFailures(count); } } } public void generateCrossReference() { StoryReporterBuilder builder = configuration().storyReporterBuilder(); if (builder.hasCrossReference()) { builder.crossReference().outputToFiles(builder); } } public void reportStepdocs() { reportStepdocs(configuration(), candidateSteps()); } public void reportStepdocsAsEmbeddables(List<String> classNames) { EmbedderControls embedderControls = embedderControls(); if (embedderControls.skip()) { embedderMonitor.embeddablesSkipped(classNames); return; } for (Embeddable embeddable : embeddables(classNames, classLoader())) { if (embeddable instanceof ConfigurableEmbedder) { ConfigurableEmbedder configurableEmbedder = (ConfigurableEmbedder) embeddable; List<CandidateSteps> steps = configurableEmbedder.candidateSteps(); if (steps.isEmpty()) { steps = configurableEmbedder.stepsFactory().createCandidateSteps(); } reportStepdocs(configurableEmbedder.configuration(), steps); } else { embedderMonitor.embeddableNotConfigurable(embeddable.getClass().getName()); } } } public void reportStepdocs(Configuration configuration, List<CandidateSteps> candidateSteps) { StepFinder finder = configuration.stepFinder(); StepdocReporter reporter = configuration.stepdocReporter(); List<Object> stepsInstances = finder.stepsInstances(candidateSteps); reporter.stepdocs(finder.stepdocs(candidateSteps), stepsInstances); } public void reportMatchingStepdocs(String stepAsString) { Configuration configuration = configuration(); List<CandidateSteps> candidateSteps = candidateSteps(); StepFinder finder = configuration.stepFinder(); StepdocReporter reporter = configuration.stepdocReporter(); List<Stepdoc> matching = finder.findMatching(stepAsString, candidateSteps); List<Object> stepsInstances = finder.stepsInstances(candidateSteps); reporter.stepdocsMatching(stepAsString, matching, stepsInstances); } public void processSystemProperties() { Properties properties = systemProperties(); embedderMonitor.processingSystemProperties(properties); if (!properties.isEmpty()) { for (Object key : properties.keySet()) { String name = (String) key; String value = properties.getProperty(name); System.setProperty(name, value); embedderMonitor.systemPropertySet(name, value); } } } public EmbedderClassLoader classLoader() { return classLoader; } public Configuration configuration() { return configuration; } public List<CandidateSteps> candidateSteps() { return candidateSteps; } public InjectableStepsFactory stepsFactory() { if (stepsFactory == null) { stepsFactory = new ProvidedStepsFactory(candidateSteps); } return stepsFactory; } public EmbedderControls embedderControls() { return embedderControls; } public EmbedderMonitor embedderMonitor() { return embedderMonitor; } public EmbedderFailureStrategy embedderFailureStrategy() { return embedderFailureStrategy; } public boolean hasExecutorService() { return executorService != null; } public ExecutorService executorService() { if (executorService == null) { executorService = createExecutorService(); executorServiceCreated = true; } return executorService; } /** * Creates a {@link ThreadPoolExecutor} using the number of threads defined * in the {@link EmbedderControls#threads()} * * @return An ExecutorService */ private ExecutorService createExecutorService() { int threads = embedderControls.threads(); embedderMonitor.usingThreads(threads); return createNewFixedThreadPool(threads); } protected void shutdownExecutorService() { if (executorServiceCreated) { executorService.shutdownNow(); executorService = null; executorServiceCreated = false; } } /** * Create default threadpool. Visible for testing * * @param threads num threads * @return the threadpool */ protected ExecutorService createNewFixedThreadPool(int threads) { return Executors.newFixedThreadPool(threads); } public List<String> metaFilters() { return metaFilters; } public MetaFilter metaFilter() { return new MetaFilter(StringUtils.join(metaFilters, " "), embedderMonitor); } public StoryRunner storyRunner() { return storyRunner; } public Properties systemProperties() { return systemProperties; } public void useClassLoader(EmbedderClassLoader classLoader) { this.classLoader = classLoader; } public void useConfiguration(Configuration configuration) { this.configuration = configuration; } public void useCandidateSteps(List<CandidateSteps> candidateSteps) { this.candidateSteps = candidateSteps; } public void useStepsFactory(InjectableStepsFactory stepsFactory) { this.stepsFactory = stepsFactory; } public void useEmbedderControls(EmbedderControls embedderControls) { this.embedderControls = embedderControls; } public void useEmbedderFailureStrategy(EmbedderFailureStrategy failureStategy) { this.embedderFailureStrategy = failureStategy; } public void useEmbedderMonitor(EmbedderMonitor embedderMonitor) { this.embedderMonitor = embedderMonitor; } public void useExecutorService(ExecutorService executorService) { this.executorService = executorService; embedderMonitor.usingExecutorService(executorService); } public void useMetaFilters(List<String> metaFilters) { this.metaFilters = metaFilters; } public void useStoryRunner(StoryRunner storyRunner) { this.storyRunner = storyRunner; } public void useSystemProperties(Properties systemProperties) { this.systemProperties = systemProperties; } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); } public static interface EmbedderFailureStrategy { void handleFailures(BatchFailures failures); void handleFailures(ReportsCount count); } public static class ThrowingRunningStoriesFailed implements EmbedderFailureStrategy { public void handleFailures(BatchFailures failures) { throw new RunningStoriesFailed(failures); } public void handleFailures(ReportsCount count) { throw new RunningStoriesFailed(count); } } @SuppressWarnings("serial") public static class AnnotatedEmbedderRunFailed extends RuntimeException { public AnnotatedEmbedderRunFailed(AnnotatedEmbedderRunner runner, Throwable cause) { super("Annotated embedder run failed with runner " + runner.toString(), cause); } } @SuppressWarnings("serial") public static class RunningEmbeddablesFailed extends RuntimeException { public RunningEmbeddablesFailed(String name, Throwable failure) { super("Failure in running embeddable: " + name, failure); } public RunningEmbeddablesFailed(BatchFailures failures) { super("Failures in running embeddables: " + failures); } } @SuppressWarnings("serial") public static class RunningStoriesFailed extends RuntimeException { public RunningStoriesFailed(ReportsCount reportsCount) { super("Failures in running stories: " + reportsCount); } public RunningStoriesFailed(BatchFailures failures) { super("Failures in running stories: " + failures); } } @SuppressWarnings("serial") public static class ViewGenerationFailed extends RuntimeException { public ViewGenerationFailed(File outputDirectory, List<String> formats, Properties viewResources, RuntimeException cause) { super("View generation failed to " + outputDirectory + " for formats " + formats + " and resources " + viewResources, cause); } public ViewGenerationFailed(File outputDirectory, StoryMaps storyMaps, Properties viewResources, RuntimeException cause) { super("View generation failed to " + outputDirectory + " for story maps " + storyMaps + " for resources " + viewResources, cause); } } }
package org.lionsoul.jcseg.util; import org.lionsoul.jcseg.tokenizer.core.ADictionary; import org.lionsoul.jcseg.tokenizer.core.ILexicon; /** * Entity format manager class * * @author chenxin<chenxin619315@gmail.com> */ public class EntityFormat { /** * check if the specified string is an email address or not * * @param str * @return boolean */ public final static boolean isMailAddress(String str) { int atIndex = str.indexOf('@'); if ( atIndex == -1 ) { return false; } if ( ! StringUtil.isLetterOrNumeric(str, 0, atIndex) ) { return false; } int ptIndex, ptStart = atIndex + 1; while ( (ptIndex = str.indexOf('.', ptStart)) > 0 ) { if ( ptIndex == ptStart ) { return false; } if ( ! StringUtil.isLetterOrNumeric(str, ptStart, ptIndex) ) { return false; } ptStart = ptIndex + 1; } if ( ptStart < str.length() && ! StringUtil.isLetterOrNumeric(str, ptStart, str.length()) ) { return false; } return true; } /** * check if the specified string is an URL address or not * * @param str * @param dic optional dictionary object * @return boolean */ public final static boolean isUrlAddress(String str, ADictionary dic) { int prIndex = str.indexOf(": if ( prIndex > -1 && ! StringUtil.isLatin(str, 0, prIndex) ) { return false; } int sIdx = prIndex > -1 ? prIndex + 3 : 0; int slIndex = str.indexOf('/', sIdx), sgIndex = str.indexOf('?', sIdx); int eIdx = slIndex > -1 ? slIndex : (sgIndex > -1 ? sgIndex : str.length()); int lpIndex = -1; for ( int i = sIdx; i < eIdx; i++ ) { char chr = str.charAt(i); if ( chr == '.' ) { if ( lpIndex == -1 ) { lpIndex = i; continue; } if ( (i - lpIndex) == 1 || i == (eIdx - 1)) { return false; } lpIndex = i; } else if ( ! StringUtil.isEnLetter(chr) && ! StringUtil.isEnNumeric(chr) ) { return false; } } if ( dic != null && ! dic.match(ILexicon.DOMAIN_SUFFIX, str.substring(lpIndex+1, eIdx)) ) { return false; } //check the path part if ( slIndex > -1 ) { sIdx = slIndex; eIdx = sgIndex > -1 ? sgIndex : str.length(); lpIndex = -1; for ( int i = sIdx; i < eIdx; i++ ) { char chr = str.charAt(i); if ( "./-_".indexOf(chr) > -1 ) { if ( lpIndex == -1 ) { lpIndex = i; continue; } if ( i - lpIndex == 1 || (chr == '.' && i == (eIdx - 1)) ) { return false; } lpIndex = i; } else if ( ! StringUtil.isEnLetter(chr) && ! StringUtil.isEnNumeric(chr) ) { return false; } } } return true; } /** * check if the specified string is a mobile number * * @param str * @return boolean */ public static final boolean isMobileNumber(String str) { if ( str.length() != 11 ) { return false; } if ( str.charAt(0) != '1' ) { return false; } if ( "34578".indexOf(str.charAt(1)) == -1 ) { return false; } return StringUtil.isNumeric(str, 2, str.length()); } /** * check if the specified string is a IPv4/v6 address * v6 is not supported for now * * @param str * @return boolean */ private static final boolean ipPartCheck( String str, int sIdx, int eIdx) { int len = eIdx - sIdx; if ( len < 1 ) { return false; } switch ( len ) { case 1: case 2: if ( ! StringUtil.isNumeric(str, sIdx, eIdx) ) return false; break; case 3: char chr1 = str.charAt(sIdx); if ( chr1 == '1' ) { if ( ! StringUtil.isNumeric(str, sIdx+1, eIdx) ) return false; } else if ( chr1 == '2' ) { char chr2 = str.charAt(sIdx+1); if ( chr2 < '0' || chr2 > '5' ) return false; char chr3 = str.charAt(sIdx+2); //the third numeric if ( chr2 == '5' ) { if ( chr3 < '0' || chr3 > '5' ) return false; } else { if ( chr3 < '0' || chr3 > '9' ) return false; } } break; default: return false; } return true; } public static final boolean isIpAddress(String str) { if ( str.length() < 7 && str.length() > 15 ) { return false; } int sIdx = 0, eIdx, pcount = 0; while ( (eIdx = str.indexOf('.', sIdx)) > -1 ) { pcount++; if ( ! ipPartCheck(str, sIdx, eIdx) ) { return false; } sIdx = eIdx + 1; } /* * bug fixed at 2017/02/12 * for the last part of the ip address not checked */ if ( sIdx < str.length() ) { if ( ! ipPartCheck(str, sIdx, str.length()) ) { return false; } } return pcount == 3; } /** * check if the specified string is an valid Latin Date string * like "2017/02/22", "2017-02-22" or "2017.02.22" * * @param str * @return boolean */ public static final String isDate(String str, char delimiter) { int length = str.length(); if ( length > 10 ) { return null; } int sIdx = 0, eIdx = 0, idx = 0; String[] parts = new String[]{null,null,null}; while ( (eIdx = str.indexOf(delimiter, sIdx)) > -1 ) { parts[idx++] = str.substring(sIdx, eIdx); sIdx = eIdx + 1; if ( idx > 2 ) { return null; } } if ( sIdx < length ) { parts[idx++] = str.substring(sIdx); } if ( idx < 2 || idx > 3 ) { return null; } String y, m, d = null; if ( idx == 2 ) { y = parts[0]; m = parts[1]; } else { y = parts[0]; m = parts[1]; d = parts[2]; } //System.out.println(y+","+m+","+d); //year format check if ( y.length() != 4 || ! StringUtil.isDigit(y) || y.charAt(0) == '0' ) { return null; } //month format check int len = m.length(); if ( len < 1 || len > 2 ) { return null; } if ( len == 1 ) { char chr = m.charAt(0); if ( chr < '1' || chr > '9' ) { return null; } } else if ( len == 2 ) { char chr1 = m.charAt(0); char chr2 = m.charAt(1); if ( ! (chr1 == '0' || chr1 == '1') ) { return null; } if ( chr1 == '0' ) { if ( chr2 < '1' || chr2 > '9' ) { return null; } } else if ( chr2 < '0' || chr2 > '2' ) { return null; } } //day format check if ( idx == 3 ) { len = d.length(); if ( len < 1 || len > 2 ) { return null; } if ( len == 1 ) { char chr = d.charAt(0); if ( chr < '1' || chr > '9' ) { return null; } } else if ( len == 2 ) { char chr1 = d.charAt(0); char chr2 = d.charAt(1); if ( "0123".indexOf(chr1) == -1 ) { return null; } if ( chr1 < '3' ) { if ( chr2 < '1' && chr2 > '9' ) { return null; } } else if ( chr2 < '0' || chr2 > '1' ) { return null; } } } if ( delimiter == '.' ) { return idx == 2 ? (y+"-"+m) : (y+"-"+m+"-"+d); } return str; } /** * check if the specified string is a valid time string * like '12:45', '12:45:12' * * @param str * @return boolean */ public static final boolean isTime(String str) { int length = str.length(); if ( length > 8 ) { return false; } int sIdx = 0, eIdx = 0, idx = 0; String[] parts = new String[]{null,null,null}; while ( (eIdx = str.indexOf(':', sIdx)) > -1 ) { parts[idx++] = str.substring(sIdx, eIdx); sIdx = eIdx + 1; if ( idx > 2 ) { return false; } } if ( sIdx < length ) { parts[idx++] = str.substring(sIdx); } if ( idx < 2 || idx > 3 ) { return false; } String h,i,s = null; if ( idx == 2 ) { h = parts[0]; i = parts[1]; } else { h = parts[0]; i = parts[1]; s = parts[2]; } //hour format check int len = h.length(); if ( len < 1 || len > 2 ) { return false; } if ( len == 1 ) { char chr = h.charAt(0); if ( chr < '0' || chr > '9' ) { return false; } } else if ( len == 2 ) { char chr1 = h.charAt(0); char chr2 = h.charAt(1); if ( chr1 == '0' || chr1 == '1' ) { if ( chr2 < '0' || chr2 > '9' ) { return false; } } else if ( chr1 == '2' ) { if ( chr2 < '0' || chr2 > '4' ) { return false; } } else { return false; } } //minute format check len = i.length(); if ( len < 1 || len > 2 ) { return false; } if ( len == 1 ) { char chr = i.charAt(0); if ( chr < '0' || chr > '9' ) { return false; } } else if ( len == 2 ) { char chr1 = i.charAt(0); char chr2 = i.charAt(1); if ( chr1 >= '0' && chr1 <= '5' ) { if ( chr2 < '0' || chr2 > '9' ) { return false; } } else { return false; } } //second format check if ( idx == 3 ) { len = s.length(); if ( len < 1 || len > 2 ) { return false; } if ( len == 1 ) { char chr = s.charAt(0); if ( chr < '0' || chr > '9' ) { return false; } } else if ( len == 2 ) { char chr1 = s.charAt(0); char chr2 = s.charAt(1); if ( chr1 >= '0' && chr1 <= '5' ) { if ( chr2 < '0' || chr2 > '9' ) { return false; } } else { return false; } } } return true; } public static void main(String[] args) { for ( int i = 32; i < 120; i++ ) { System.out.println(i + ": " + ((char)i)); } } }
package com.jme3.shader.plugins; import com.jme3.asset.*; import com.jme3.asset.cache.AssetCache; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.util.*; /** * GLSL File parser that supports #import pre-processor statement */ public class GLSLLoader implements AssetLoader { private AssetManager assetManager; private Map<String, ShaderDependencyNode> dependCache = new HashMap<>(); /** * Used to load {@link ShaderDependencyNode}s. * Asset caching is disabled. */ private class ShaderDependencyKey extends AssetKey<Reader> { public ShaderDependencyKey(String name) { super(name); } @Override public Class<? extends AssetCache> getCacheType() { // Disallow caching here return null; } } /** * Creates a {@link ShaderDependencyNode} from a stream representing shader code. * * @param reader the reader with shader code * @param nodeName the node name. * @return the shader dependency node * @throws AssetLoadException if we failed to load the shader code. */ private ShaderDependencyNode loadNode(Reader reader, String nodeName) { ShaderDependencyNode node = new ShaderDependencyNode(nodeName); StringBuilder sb = new StringBuilder(); StringBuilder sbExt = new StringBuilder(); try (final BufferedReader bufferedReader = new BufferedReader(reader)) { String ln; if (!nodeName.equals("[main]")) { sb.append("// -- begin import ").append(nodeName).append(" --\n"); } while ((ln = bufferedReader.readLine()) != null) { if (ln.trim().startsWith("#import ")) { ln = ln.trim().substring(8).trim(); if (ln.startsWith("\"") && ln.endsWith("\"") && ln.length() > 3) { // import user code // remove quotes to get filename ln = ln.substring(1, ln.length() - 1); if (ln.equals(nodeName)) { throw new IOException("Node depends on itself."); } // check cache first ShaderDependencyNode dependNode = dependCache.get(ln); if (dependNode == null) { Reader dependNodeReader = assetManager.loadAsset(new ShaderDependencyKey(ln)); dependNode = loadNode(dependNodeReader, ln); } node.addDependency(sb.length(), dependNode); } } else if (ln.trim().startsWith("#extension ")) { sbExt.append(ln).append('\n'); } else { sb.append(ln).append('\n'); } } if (!nodeName.equals("[main]")) { sb.append("// -- end import ").append(nodeName).append(" --\n"); } } catch (final IOException ex) { throw new AssetLoadException("Failed to load shader node: " + nodeName, ex); } node.setSource(sb.toString()); node.setExtensions(sbExt.toString()); dependCache.put(nodeName, node); return node; } private ShaderDependencyNode nextIndependentNode() throws IOException { Collection<ShaderDependencyNode> allNodes = dependCache.values(); if (allNodes.isEmpty()) { return null; } for (ShaderDependencyNode node : allNodes) { if (node.getDependOnMe().isEmpty()) { return node; } } // Circular dependency found.. for (ShaderDependencyNode node : allNodes){ System.out.println(node.getName()); } throw new IOException("Circular dependency."); } private String resolveDependencies(ShaderDependencyNode node, Set<ShaderDependencyNode> alreadyInjectedSet, StringBuilder extensions) { if (alreadyInjectedSet.contains(node)) { return "// " + node.getName() + " was already injected at the top.\n"; } else { alreadyInjectedSet.add(node); } if (!node.getExtensions().isEmpty()) { extensions.append(node.getExtensions()); } if (node.getDependencies().isEmpty()) { return node.getSource(); } else { StringBuilder sb = new StringBuilder(node.getSource()); List<String> resolvedShaderNodes = new ArrayList<>(); for (ShaderDependencyNode dependencyNode : node.getDependencies()) { resolvedShaderNodes.add(resolveDependencies(dependencyNode, alreadyInjectedSet, extensions)); } List<Integer> injectIndices = node.getDependencyInjectIndices(); for (int i = resolvedShaderNodes.size() - 1; i >= 0; i // Must insert them backwards .. sb.insert(injectIndices.get(i), resolvedShaderNodes.get(i)); } return sb.toString(); } } @Override public Object load(AssetInfo info) throws IOException { // The input stream provided is for the vertex shader, // to retrieve the fragment shader, use the content manager this.assetManager = info.getManager(); Reader reader = new InputStreamReader(info.openStream()); if (info.getKey().getExtension().equals("glsllib")) { // NOTE: Loopback, GLSLLIB is loaded by this loader // and needs data as InputStream return reader; } else { ShaderDependencyNode rootNode = loadNode(reader, "[main]"); StringBuilder extensions = new StringBuilder(); String code = resolveDependencies(rootNode, new HashSet<ShaderDependencyNode>(), extensions); extensions.append(code); dependCache.clear(); return extensions.toString(); } } }
package jsettlers.graphics.map.draw; import go.graphics.GLDrawContext; import go.graphics.GLDrawContext.GLBuffer; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.BitSet; import jsettlers.common.CommonConstants; import jsettlers.common.landscape.ELandscapeType; import jsettlers.common.map.IGraphicsBackgroundListener; import jsettlers.common.map.shapes.MapRectangle; import jsettlers.common.position.FloatRectangle; import jsettlers.graphics.map.MapDrawContext; import jsettlers.graphics.reader.AdvancedDatFileReader; import jsettlers.graphics.reader.DatBitmapReader; import jsettlers.graphics.reader.ImageArrayProvider; import jsettlers.graphics.reader.ImageMetadata; /** * The map background * * @author michael */ public class Background implements IGraphicsBackgroundListener { private static final int LAND_FILE = 0; /** * The base texture size. */ private static final int TEXTURE_SIZE = 1024; /** * Our base texture is divided into multiple squares that all hold a single texture. Continuous textures occupy 5*5 squares */ private static final int TEXTURE_GRID = 32; private static final int[][] TEXTURE_POSITIONS = { /* 0: big */{ 0, 0, 5 }, /* 1: big */{ 5, 0, 5 }, /* 2: big */{ 10, 0, 5 }, /* 3: big */{ 15, 0, 5 }, /* 4: big */{ 20, 0, 5 }, /* 5: small */{ 30, 0, 1 }, /* 6: small */{ 31, 0, 1 }, /* 7: big */{ 25, 0, 5 }, /* 8: small */{ 30, 1, 1 }, /* 9: small */{ 31, 1, 1 }, /* 10: big */{ 0, 5, 5 }, /* 11: small, continuous */{ 0, 20, 2 }, /* 12: small, continuous */{ 2, 20, 2 }, /* 13: small, continuous */{ 4, 20, 2 }, /* 14: small, continuous */{ 6, 20, 2 }, /* 15: small, continuous */{ 8, 20, 2 }, /* 16: small, continuous */{ 10, 20, 2 }, /* 17: small, continuous */{ 12, 20, 2 }, /* 18: big */{ 5, 5, 5 }, /* 19: small */{ 31, 5, 1 }, /* 20: small */{ 30, 6, 1 }, /* 21: big */{ 10, 5, 5 }, /* 22: small */{ 31, 6, 1 }, /* 23: small */{ 30, 7, 1 }, /* 24: big */{ 15, 5, 5 }, /* 25: small */{ 31, 7, 1 }, /* 26: small */{ 30, 8, 1 }, /* 27: small */{ 31, 8, 1 }, /* 28: small */{ 30, 9, 1 }, /* 29: small */{ 31, 9, 1 }, /* 30: small */{ 30, 10, 1 }, /* 31: big */{ 20, 5, 5 }, /* 32: small */{ 31, 10, 1 }, /* 33: small */{ 30, 11, 1 }, /* 34: small */{ 31, 11, 1 }, /* 35: big */{ 25, 5, 5 }, /* 36: big */{ 0, 10, 5 }, /* 37: small */{ 30, 13, 1 }, /* 38: small */{ 31, 13, 1 }, /* 39: small */{ 30, 14, 1 }, /* 40: small */{ 31, 14, 1 }, /* 41: small */{ 0, 15, 1 }, /* 42: small */{ 1, 15, 1 }, /* 43: small */{ 2, 15, 1 }, /* 44: small */{ 3, 15, 1 }, /* 45: small */{ 4, 15, 1 }, /* 46: small */{ 5, 15, 1 }, /* 47: small */{ 6, 15, 1 }, /* 48: small */{ 7, 15, 1 }, /* 49: small */{ 8, 15, 1 }, /* 50: small */{ 9, 15, 1 }, /* 51: small */{ 10, 15, 1 }, /* 52: small */{ 11, 15, 1 }, /* 53: small */{ 12, 15, 1 }, /* 54: small */{ 13, 15, 1 }, /* 55: small */{ 14, 15, 1 }, /* 56: small */{ 15, 15, 1 }, /* 57: small */{ 16, 15, 1 }, /* 58: small */{ 17, 15, 1 }, /* 59: small */{ 18, 15, 1 }, /* 60: small */{ 19, 15, 1 }, /* 61: small */{ 20, 15, 1 }, /* 62: small */{ 21, 15, 1 }, /* 63: small */{ 22, 15, 1 }, /* 64: small */{ 23, 15, 1 }, /* 65: small */{ 24, 15, 1 }, /* 66: small */{ 25, 15, 1 }, /* 67: small */{ 26, 15, 1 }, /* 68: small */{ 27, 15, 1 }, /* 69: small */{ 28, 15, 1 }, /* 70: small */{ 29, 15, 1 }, /* 71: small */{ 30, 15, 1 }, /* 72: small */{ 31, 15, 1 }, /* 73: small */{ 0, 16, 1 }, /* 74: small */{ 1, 16, 1 }, /* 75: small */{ 2, 16, 1 }, /* 76: small */{ 3, 16, 1 }, /* 77: small */{ 4, 16, 1 }, /* 78: small */{ 5, 16, 1 }, /* 79: small */{ 6, 16, 1 }, /* 80: small */{ 7, 16, 1 }, /* 81: small */{ 8, 16, 1 }, /* 82: small */{ 9, 16, 1 }, /* 83: small */{ 10, 16, 1 }, /* 84: small */{ 11, 16, 1 }, /* 85: small */{ 12, 16, 1 }, /* 86: small */{ 13, 16, 1 }, /* 87: small */{ 14, 16, 1 }, /* 88: small */{ 15, 16, 1 }, /* 89: small */{ 16, 16, 1 }, /* 90: small */{ 17, 16, 1 }, /* 91: small */{ 18, 16, 1 }, /* 92: small */{ 19, 16, 1 }, /* 93: small */{ 20, 16, 1 }, /* 94: small */{ 21, 16, 1 }, /* 95: small */{ 22, 16, 1 }, /* 96: small */{ 23, 16, 1 }, /* 97: small */{ 24, 16, 1 }, /* 98: small */{ 30, 16, 1 }, /* 99: small */{ 31, 12, 1 }, /* 100: small */{ 25, 12, 1 }, /* 101: small */{ 26, 16, 1 }, /* 102: small */{ 27, 16, 1 }, /* 103: small */{ 28, 16, 1 }, /* 104: small */{ 29, 16, 1 }, /* 105: small */{ 30, 16, 1 }, /* 106: small */{ 31, 16, 1 }, /* 107: small */{ 0, 17, 1 }, /* 108: small */{ 1, 17, 1 }, /* 109: small */{ 2, 17, 1 }, /* 110: small */{ 3, 17, 1 }, /* 111: small */{ 4, 17, 1 }, /* 112: small */{ 5, 17, 1 }, /* 113: small */{ 6, 17, 1 }, /* 114: small */{ 7, 17, 1 }, /* 115: small */{ 8, 17, 1 }, /* 116: small */{ 9, 17, 1 }, /* 117: small */{ 10, 17, 1 }, /* 118: small */{ 11, 17, 1 }, /* 119: small */{ 12, 17, 1 }, /* 120: small */{ 13, 17, 1 }, /* 121: small */{ 14, 17, 1 }, /* 122: small */{ 15, 17, 1 }, /* 123: small */{ 16, 17, 1 }, /* 124: small */{ 17, 17, 1 }, /* 125: small */{ 18, 17, 1 }, /* 126: small */{ 19, 17, 1 }, /* 127: small */{ 20, 17, 1 }, /* 128: small */{ 21, 17, 1 }, /* 129: small */{ 22, 17, 1 }, /* 130: small */{ 23, 17, 1 }, /* 131: small */{ 24, 17, 1 }, /* 132: small */{ 25, 17, 1 }, /* 133: small */{ 26, 17, 1 }, /* 134: small */{ 27, 17, 1 }, /* 135: small */{ 28, 17, 1 }, /* 136: small */{ 29, 17, 1 }, /* 137: small */{ 30, 17, 1 }, /* 138: small */{ 31, 17, 1 }, /* 139: small */{ 0, 18, 1 }, /* 140: small */{ 1, 18, 1 }, /* 141: small */{ 2, 18, 1 }, /* 142: small */{ 3, 18, 1 }, /* 143: small */{ 4, 18, 1 }, /* 144: small */{ 5, 18, 1 }, /* 145: small */{ 6, 18, 1 }, /* 146: small */{ 7, 18, 1 }, /* 147: small */{ 8, 18, 1 }, /* 148: small */{ 9, 18, 1 }, /* 149: small */{ 10, 18, 1 }, /* 150: small */{ 11, 18, 1 }, /* 151: small */{ 12, 18, 1 }, /* 152: small */{ 13, 18, 1 }, /* 153: small */{ 14, 18, 1 }, /* 154: small */{ 15, 18, 1 }, /* 155: small */{ 16, 18, 1 }, /* 156: small */{ 17, 18, 1 }, /* 157: small */{ 18, 18, 1 }, /* 158: small */{ 19, 18, 1 }, /* 159: small */{ 20, 18, 1 }, /* 160: small */{ 21, 18, 1 }, /* 161: small */{ 22, 18, 1 }, /* 162: small */{ 23, 18, 1 }, /* 163: small */{ 24, 18, 1 }, /* 164: small */{ 25, 18, 1 }, /* 165: small */{ 26, 18, 1 }, /* 166: small */{ 27, 18, 1 }, /* 167: small */{ 28, 18, 1 }, /* 168: small */{ 29, 18, 1 }, /* 169: small */{ 30, 18, 1 }, /* 170: small */{ 31, 18, 1 }, /* 171: small */{ 0, 19, 1 }, /* 172: small */{ 1, 19, 1 }, /* 173: small */{ 2, 19, 1 }, /* 174: small */{ 3, 19, 1 }, /* 175: small */{ 4, 19, 1 }, /* 176: big (odd shape?) */{ 5, 10, 5 }, /* 177: small */{ 6, 19, 1 }, /* 178: small */{ 7, 19, 1 }, /* 179: small */{ 8, 19, 1 }, /* 180: small */{ 9, 19, 1 }, /* 181: small */{ 10, 19, 1 }, /* 182: small */{ 11, 19, 1 }, /* 183: small */{ 12, 19, 1 }, /* 184: small */{ 13, 19, 1 }, /* 185: small */{ 14, 19, 1 }, /* 186: small */{ 15, 19, 1 }, /* 187: small */{ 16, 19, 1 }, /* 188: small */{ 17, 19, 1 }, /* 189: small */{ 18, 19, 1 }, /* 190: small */{ 19, 19, 1 }, /* 191: small */{ 20, 19, 1 }, /* 192: small */{ 21, 19, 1 }, /* 193: small */{ 22, 19, 1 }, /* 194: small */{ 23, 19, 1 }, /* 195: small */{ 24, 19, 1 }, /* 196: small */{ 25, 19, 1 }, /* 197: small */{ 26, 19, 1 }, /* 198: small */{ 27, 19, 1 }, /* 199: small */{ 28, 19, 1 }, /* 200: small */{ 29, 19, 1 }, /* 201: small */{ 30, 19, 1 }, /* 202: small */{ 31, 19, 1 }, /* 203: small */{ 0, 22, 1 }, /* 204: small */{ 1, 22, 1 }, /* 205: small */{ 2, 22, 1 }, /* 206: small */{ 3, 22, 1 }, /* 207: small */{ 4, 22, 1 }, /* 208: small */{ 5, 22, 1 }, /* 209: small */{ 6, 22, 1 }, /* 210: small */{ 7, 22, 1 }, /* 211: small */{ 8, 22, 1 }, /* 212: small */{ 9, 22, 1 }, /* 213: small */{ 10, 22, 1 }, /* 214: small */{ 11, 22, 1 }, /* 215: small */{ 12, 22, 1 }, /* 216: small */{ 13, 22, 1 }, /* 217: big */{ 14, 20, 5 }, /* 218: small */{ 1, 23, 1 }, /* 219: small */{ 2, 23, 1 }, /* 220: small */{ 3, 23, 1 }, /* 221: small */{ 4, 23, 1 }, /* 222: small */{ 5, 23, 1 }, /* 223: small */{ 6, 23, 1 }, /* 224: small */{ 7, 23, 1 }, /* 225: small */{ 8, 23, 1 }, /* 226: small */{ 9, 23, 1 }, /* 227: small */{ 10, 23, 1 }, /* 228: small */{ 11, 23, 1 }, /* 229: small */{ 12, 23, 1 }, /* 230: big */{ 19, 20, 5 }, /* 231: small */{ 13, 23, 1 }, /* 232: small */{ 0, 24, 1 }, /* 233: small */{ 1, 24, 1 }, /* 234: small */{ 2, 24, 1 }, }; private static final short FLOAT_SIZE = 4; /** * How many bytes are needed per vertex */ private static final short VERTEX_SIZE = 6 * FLOAT_SIZE; private static final byte DIM_MAX = 20; private static final byte[] BLACK = new byte[] { 0, 0, 0, (byte) 255 }; /** * Offset of color definition in bytes, relative to vertex start */ // private static final int COLOR_OFFSET = 5 * FLOAT_SIZE; private byte[] fogOfWarStatus = new byte[1]; private MapRectangle oldBufferPosition = new MapRectangle(0, 0, 0, 0); private int bufferwidth = 1;; // in map points. private int bufferheight = 1; // in map points. private static int texture = -1; private int geometryindex = -1; private int geometrytirs; private BitSet geometryInvalid = new BitSet(); private static Object preloadMutex = new Object(); private static short[] preloadedTexture = null; private static short[] getTexture() { short[] data = new short[TEXTURE_SIZE * TEXTURE_SIZE]; try { addTextures(data); } catch (IOException e) { e.printStackTrace(); } return data; } public static void preloadTexture() { synchronized (preloadMutex) { if (preloadedTexture == null) { preloadedTexture = getTexture(); ImageProvider.getInstance().addPreloadTask(new GLPreloadTask() { @Override public void run(GLDrawContext context) { getTexture(context); } }); } } } private static int getTexture(GLDrawContext context) { if (texture < 0) { long starttime = System.currentTimeMillis(); short[] data; synchronized (preloadMutex) { if (preloadedTexture != null) { data = preloadedTexture; // free the array preloadedTexture = null; } else { data = getTexture(); } } ByteBuffer buffer = ByteBuffer.allocateDirect(data.length * 2).order( ByteOrder.nativeOrder()); buffer.asShortBuffer().put(data); texture = context.generateTexture(TEXTURE_SIZE, TEXTURE_SIZE, buffer.asShortBuffer()); System.out.println("Background texture generated in " + (System.currentTimeMillis() - starttime) + "ms"); } return texture; } private static class ImageWriter implements ImageArrayProvider { int arrayoffset; int cellsize; int maxoffset; short[] data; // nothing to do. We assume images are a rectangle and have the right // size. @Override public void startImage(int width, int height) throws IOException { } @Override public void writeLine(short[] data, int length) throws IOException { if (arrayoffset < maxoffset) { for (int i = 0; i < cellsize; i++) { this.data[arrayoffset + i] = data[i % length]; } arrayoffset += TEXTURE_SIZE; } } } /** * Generates the texture data. * * @param data * The texture data buffer. * @throws IOException */ private static void addTextures(short[] data) throws IOException { AdvancedDatFileReader reader = ImageProvider.getInstance().getFileReader(LAND_FILE); if (reader == null) { throw new IOException("Could not get a file reader for the file."); } ImageWriter imageWriter = new ImageWriter(); imageWriter.data = data; ImageMetadata meta = new ImageMetadata(); for (int index = 0; index < TEXTURE_POSITIONS.length; index++) { int[] position = TEXTURE_POSITIONS[index]; int x = position[0] * TEXTURE_GRID; int y = position[1] * TEXTURE_GRID; int start = y * TEXTURE_SIZE + x; int cellsize = position[2] * TEXTURE_GRID; int end = (y + cellsize) * TEXTURE_SIZE + x; imageWriter.arrayoffset = start; imageWriter.cellsize = cellsize; imageWriter.maxoffset = end; DatBitmapReader.uncompressImage( reader.getReaderForLandscape(index), AdvancedDatFileReader.LANDSCAPE_TRANSLATOR, meta, imageWriter); // freaky stuff int arrayoffset = imageWriter.arrayoffset; int l = arrayoffset - start; while (arrayoffset < end) { for (int i = 0; i < cellsize; i++) { data[arrayoffset + i] = data[arrayoffset - l + i]; } arrayoffset += TEXTURE_SIZE; } } } /** * Copys a image to the texture position. * * @param data * The data to copy to * @param image * The image to copy * @param texturepos * The texture position */ // private static void copyImageAt(short[] data, SingleImage image, // int[] texturepos) { // int startx = texturepos[0] * TEXTURE_GRID; // int starty = texturepos[1] * TEXTURE_GRID; // int maxx = startx + texturepos[2] * TEXTURE_GRID; // int maxy = starty + texturepos[2] * TEXTURE_GRID; // for (int x = startx; x < maxx; x += image.getWidth()) { // for (int y = starty; y < maxy; y += image.getHeight()) { // int width = Math.min(image.getWidth(), maxx - x); // int height = Math.min(image.getHeight(), maxy - y); // copyImage(data, image, x, y, width, height); /** * Copys the left top image corner to the buffer at (x, y), assuming the buffer is a TEXTURE_SIZE wide image. * * @param data * The data to copy to * @param image * The image to copy from * @param x * The x coordinate in the destination buffer * @param y * The y coordinate in the destination buffer * @param width * The width of the area to copy * @param height * The height of the area to copy */ // private static void copyImage(short[] data, SingleImage image, int x, // int y, int width, int height) { // short[] sourceData = image.getData().array(); // for (int dy = 0; dy < height && dy < image.getHeight(); dy++) { // System.arraycopy(sourceData, image.getWidth() * dy, data, // TEXTURE_SIZE * (y + dy) + x, width); /** * Gets the image number of the border * * @param outer * The outer landscape (that has two triangle edges). * @param inner * The inner landscape. * @param useSecond * If it is true, the secondary texture is used. * @return The texture. */ private static int getBorder(ELandscapeType outer, ELandscapeType inner, boolean useSecond) { int index; // water <=> water if (outer == ELandscapeType.WATER1 && inner == ELandscapeType.WATER2) { index = 84; } else if (outer == ELandscapeType.WATER2 && inner == ELandscapeType.WATER1) { index = 86; } else if (outer == ELandscapeType.WATER2 && inner == ELandscapeType.WATER3) { index = 88; } else if (outer == ELandscapeType.WATER3 && inner == ELandscapeType.WATER2) { index = 90; } else if (outer == ELandscapeType.WATER3 && inner == ELandscapeType.WATER4) { index = 92; } else if (outer == ELandscapeType.WATER4 && inner == ELandscapeType.WATER3) { index = 94; } else if (outer == ELandscapeType.WATER4 && inner == ELandscapeType.WATER5) { index = 96; } else if (outer == ELandscapeType.WATER5 && inner == ELandscapeType.WATER4) { index = 98; } else if (outer == ELandscapeType.WATER5 && inner == ELandscapeType.WATER6) { index = 100; } else if (outer == ELandscapeType.WATER6 && inner == ELandscapeType.WATER5) { index = 102; } else if (outer == ELandscapeType.WATER6 && inner == ELandscapeType.WATER7) { index = 104; } else if (outer == ELandscapeType.WATER7 && inner == ELandscapeType.WATER6) { index = 106; } else if (outer == ELandscapeType.WATER7 && inner == ELandscapeType.WATER8) { index = 108; } else if (outer == ELandscapeType.WATER8 && inner == ELandscapeType.WATER7) { index = 110; // grass <=> dessert } else if (outer == ELandscapeType.GRASS && inner == ELandscapeType.DESERT) { index = 181; } else if (outer == ELandscapeType.DESERT && inner == ELandscapeType.GRASS) { index = 183; // water <=> sand } else if (outer == ELandscapeType.WATER1 && inner == ELandscapeType.SAND) { index = 39; } else if (outer == ELandscapeType.SAND && inner == ELandscapeType.WATER1) { index = 37; // grass <=> mountain } else if (outer == ELandscapeType.GRASS && inner == ELandscapeType.MOUNTAINBORDEROUTER) { index = 116; } else if (outer == ELandscapeType.MOUNTAINBORDEROUTER && inner == ELandscapeType.GRASS) { index = 118; } else if (outer == ELandscapeType.MOUNTAINBORDEROUTER && inner == ELandscapeType.MOUNTAINBORDER) { index = 120; } else if (outer == ELandscapeType.MOUNTAINBORDER && inner == ELandscapeType.MOUNTAINBORDEROUTER) { index = 122; } else if (outer == ELandscapeType.MOUNTAINBORDER && inner == ELandscapeType.MOUNTAIN) { index = 124; } else if (outer == ELandscapeType.MOUNTAIN && inner == ELandscapeType.MOUNTAINBORDER) { index = 126; // mountain <=> snow } else if (outer == ELandscapeType.MOUNTAIN && inner == ELandscapeType.SNOW) { index = 156; } else if (outer == ELandscapeType.SNOW && inner == ELandscapeType.MOUNTAIN) { index = 158; // earth <=> grass } else if (outer == ELandscapeType.EARTH && inner == ELandscapeType.GRASS) { index = 170; } else if (outer == ELandscapeType.GRASS && inner == ELandscapeType.EARTH) { index = 168; // grass <=> dry grass } else if (outer == ELandscapeType.GRASS && inner == ELandscapeType.DRY_GRASS) { index = 116; } else if (outer == ELandscapeType.DRY_GRASS && inner == ELandscapeType.GRASS) { index = 118; // dry grass <=> desert } else if (outer == ELandscapeType.DRY_GRASS && inner == ELandscapeType.DESERT) { index = 136; } else if (outer == ELandscapeType.DESERT && inner == ELandscapeType.DRY_GRASS) { index = 138; // river <=> grass } else if (outer == ELandscapeType.GRASS && inner == ELandscapeType.RIVER1) { index = 52; } else if (outer == ELandscapeType.RIVER1 && inner == ELandscapeType.GRASS) { index = 54; } else if (outer == ELandscapeType.GRASS && inner == ELandscapeType.RIVER1) { index = 56; } else if (outer == ELandscapeType.RIVER2 && inner == ELandscapeType.GRASS) { index = 58; } else if (outer == ELandscapeType.GRASS && inner == ELandscapeType.RIVER3) { index = 60; } else if (outer == ELandscapeType.RIVER3 && inner == ELandscapeType.GRASS) { index = 62; } else if (outer == ELandscapeType.GRASS && inner == ELandscapeType.RIVER4) { index = 64; } else if (outer == ELandscapeType.RIVER4 && inner == ELandscapeType.GRASS) { index = 66; // sand <=> river } else if (outer == ELandscapeType.SAND && inner == ELandscapeType.RIVER1) { index = 68; } else if (outer == ELandscapeType.RIVER1 && inner == ELandscapeType.SAND) { index = 70; } else if (outer == ELandscapeType.SAND && inner == ELandscapeType.RIVER1) { index = 72; } else if (outer == ELandscapeType.RIVER2 && inner == ELandscapeType.SAND) { index = 74; } else if (outer == ELandscapeType.SAND && inner == ELandscapeType.RIVER3) { index = 76; } else if (outer == ELandscapeType.RIVER3 && inner == ELandscapeType.SAND) { index = 78; } else if (outer == ELandscapeType.SAND && inner == ELandscapeType.RIVER4) { index = 80; } else if (outer == ELandscapeType.RIVER4 && inner == ELandscapeType.SAND) { index = 82; // grass <=> sand } else if (outer == ELandscapeType.GRASS && inner == ELandscapeType.SAND) { index = 114; } else if (outer == ELandscapeType.SAND && inner == ELandscapeType.GRASS) { index = 112; // grass <=> flattened } else if (outer == ELandscapeType.GRASS && inner == ELandscapeType.FLATTENED) { index = 172; } else if (outer == ELandscapeType.FLATTENED && inner == ELandscapeType.GRASS) { index = 174; // moor <=> grass } else if (outer == ELandscapeType.GRASS && inner == ELandscapeType.MOORBORDER) { index = 201; } else if (outer == ELandscapeType.MOORBORDER && inner == ELandscapeType.GRASS) { index = 203; } else if (outer == ELandscapeType.MOORBORDER && inner == ELandscapeType.MOORINNER) { index = 205; } else if (outer == ELandscapeType.MOORINNER && inner == ELandscapeType.MOORBORDER) { index = 207; } else if (outer == ELandscapeType.MOORINNER && inner == ELandscapeType.MOOR) { index = 209; } else if (outer == ELandscapeType.MOOR && inner == ELandscapeType.MOORINNER) { index = 211; // flattened desert <=> desert } else if (outer == ELandscapeType.DESERT && inner == ELandscapeType.SHARP_FLATTENED_DESERT) { index = 218; } else if (outer == ELandscapeType.SHARP_FLATTENED_DESERT && inner == ELandscapeType.DESERT) { index = 220; } else if (outer == ELandscapeType.DESERT && inner == ELandscapeType.FLATTENED_DESERT) { index = 222; } else if (outer == ELandscapeType.FLATTENED_DESERT && inner == ELandscapeType.DESERT) { index = 224; } else if (outer == ELandscapeType.GRAVEL && inner == ELandscapeType.MOUNTAINBORDER) { index = 231; } else if (outer == ELandscapeType.MOUNTAINBORDER && inner == ELandscapeType.GRAVEL) { index = 233; } else { index = outer.getImageNumber(); useSecond = false; // force! } if (useSecond) { index += 1; } return index; } /** * Draws a given map content. * * @param context * The context to draw at. * @param screen2 */ public void drawMapContent(MapDrawContext context, FloatRectangle screen) { // float[] geometry = getGeometry(context); GLDrawContext gl = context.getGl(); MapRectangle screenArea = context.getConverter().getMapForScreen(screen); if (!gl.isGeometryValid(geometryindex) || screenArea.getLineLength() + 1 != bufferwidth || screenArea.getLines() != bufferheight) { regenerateGeometry(gl, screenArea); } GLBuffer boundbuffer = gl.startWriteGeometry(geometryindex); reloadGeometry(boundbuffer, screenArea, context); gl.endWriteGeometry(geometryindex); gl.glPushMatrix(); gl.glTranslatef(0, 0, -.1f); gl.glScalef(1, 1, 0); gl.glMultMatrixf(context.getConverter().getMatrixWithHeight(), 0); gl.color(1, 1, 1, 1); gl.drawTrianglesWithTextureColored(getTexture(context.getGl()), geometryindex, geometrytirs); gl.glPopMatrix(); } private void regenerateGeometry(GLDrawContext gl, MapRectangle screenArea) { if (gl.isGeometryValid(geometryindex)) { gl.removeGeometry(geometryindex); } bufferwidth = niceRoundUp(screenArea.getLineLength() + 1); bufferheight = niceRoundUp(screenArea.getLines()); int count = bufferheight * bufferwidth; fogOfWarStatus = new byte[count * 4]; geometryInvalid = new BitSet(count); geometrytirs = count * 2; geometryindex = gl.generateGeometry(geometrytirs * 3 * VERTEX_SIZE); } private static int niceRoundUp(int i) { // int base = 1; // while (i > base) { // base *= 2; // return base; return i; } /** * Gets the geometry of the background as array. * * @param boundbuffer * The buffer of opengl. * @param context * The context to use. * @return The geometry as float array. */ private void reloadGeometry(GLBuffer boundbuffer, MapRectangle area, MapDrawContext context) { boolean hasInvalidFields = !geometryInvalid.isEmpty(); int width = context.getMap().getWidth(); int height = context.getMap().getHeight(); int oldbuffertop = oldBufferPosition.getLineY(0); int oldbufferbottom = oldbuffertop + bufferheight; // excluding for (int line = 0; line < bufferheight; line++) { int y = area.getLineY(line); int minx = area.getLineStartX(line); int maxx = minx + bufferwidth; int oldminx = 0; int oldmaxx = 0; // excluding if (y >= oldbuffertop && y < oldbufferbottom) { oldminx = oldBufferPosition.getLineStartX(y - oldbuffertop); oldmaxx = oldminx + bufferwidth; } boolean lineIsInMap = y >= 0 && y < height; for (int x = minx; x < maxx; x++) { int bufferPosition = getBufferPosition(y, x); if (oldminx > x || oldmaxx <= x) { redrawPoint(boundbuffer, context, x, y, false, bufferPosition); } else if (lineIsInMap && x >= 0 && x < width) { if (hasInvalidFields) { boolean invalid = false; synchronized (this) { invalid = geometryInvalid.get(bufferPosition); geometryInvalid.clear(bufferPosition); } if (invalid) { redrawPoint(boundbuffer, context, x, y, true, bufferPosition); } } else if (context.getVisibleStatus(x, y) != fogOfWarStatus[bufferPosition * 4]) { redrawPoint(boundbuffer, context, x, y, true, bufferPosition); invalidatePoint(x - 1, y); // only for next pass invalidatePoint(x - 1, y - 1); invalidatePoint(x - 1, y - 1); } } } } oldBufferPosition = area; } /** * Redraws a point on the map to the buffer. * * @param boundbuffer * The buffer to use * @param context * The context * @param x * The x coordinate of the point * @param y * The y coordinate of the point * @param wasVisible * true if and only if the point was already in the buffer. */ private void redrawPoint(GLBuffer boundbuffer, MapDrawContext context, int x, int y, boolean wasVisible, int pointOffset) { boundbuffer.position(pointOffset * 2 * 3 * VERTEX_SIZE); if (x >= 0 && y >= 0 && x < context.getMap().getWidth() - 1 && y < context.getMap().getHeight() - 1) { if (wasVisible) { dimFogOfWarBuffer(context, (pointOffset * 4), x, y); dimFogOfWarBuffer(context, (pointOffset * 4) + 1, x + 1, y); dimFogOfWarBuffer(context, (pointOffset * 4) + 2, x, y + 1); dimFogOfWarBuffer(context, (pointOffset * 4) + 3, x + 1, y + 1); } else { addFogOfWarBuffer(context, (pointOffset * 4), x, y); addFogOfWarBuffer(context, (pointOffset * 4) + 1, x + 1, y); addFogOfWarBuffer(context, (pointOffset * 4) + 2, x, y + 1); addFogOfWarBuffer(context, (pointOffset * 4) + 3, x + 1, y + 1); } addTrianglesToGeometry(context, boundbuffer, x, y, pointOffset * 4); } else { addPseudoTrianglesToGeometry(context, boundbuffer, x, y); } } private synchronized void invalidatePoint(int x, int y) { geometryInvalid.set(getBufferPosition(y, x)); } private void addFogOfWarBuffer(MapDrawContext context, int offset, int x, int y) { fogOfWarStatus[offset] = context.getVisibleStatus(x, y); } /** * Dims the fog of war buffer * * @param context * The context * @param offset * The fog of war buffer offset * @param x * The x coordinate of the tile * @param y * The y coordinate of the tile. * @return true if and only if the dim has finished. */ private void dimFogOfWarBuffer(MapDrawContext context, int offset, int x, int y) { byte newFog = context.getVisibleStatus(x, y); fogOfWarStatus[offset] = dim(fogOfWarStatus[offset], newFog); } private static byte dim(byte value, byte dimTo) { if (value < dimTo - DIM_MAX) { return (byte) (dimTo - DIM_MAX); } else if (value > dimTo + DIM_MAX) { return (byte) (dimTo + DIM_MAX); } else if (value > dimTo) { return (byte) (value - 1); } else if (value < dimTo) { return (byte) (value + 1); } else { return value; } } private final int getBufferPosition(int y, int x) { int linepos = y % bufferheight; int colpos = x % bufferwidth; while (linepos < 0) { linepos += bufferheight; } while (colpos < 0) { colpos += bufferwidth; } return (linepos * bufferwidth + colpos); } /** * Adds the two triangles for a point to the list of verteces * * @param context * @param buffer * @param offset * @param x * @param y * @param fogOfWar */ private void addTrianglesToGeometry(MapDrawContext context, GLBuffer buffer, int x, int y, int fogBase) { addTriangle1ToGeometry(context, buffer, x, y, fogBase); addTriangle2ToGeometry(context, buffer, x, y, fogBase); } private static void addPseudoTrianglesToGeometry(MapDrawContext context, GLBuffer buffer, int x, int y) { // manually do // everything... addBlackPointToGeometry(context, buffer, x, y); addBlackPointToGeometry(context, buffer, x, y + 1); addBlackPointToGeometry(context, buffer, x + 1, y + 1); addBlackPointToGeometry(context, buffer, x, y); addBlackPointToGeometry(context, buffer, x + 1, y + 1); addBlackPointToGeometry(context, buffer, x + 1, y); } // private boolean useRenderbuffer(GL2 gl) { // return gl.isExtensionAvailable("GL_EXT_framebuffer_object"); /** * Draws the triangle that is facing up * * @param context * @param buffer * @param offset * @param x * @param y */ private void addTriangle1ToGeometry(MapDrawContext context, GLBuffer buffer, int x, int y, int fogBase) { ELandscapeType toplandscape = context.getLandscape(x, y); ELandscapeType leftlandscape = context.getLandscape(x, y + 1); ELandscapeType rightlandscape = context.getLandscape(x + 1, y + 1); boolean useSecond = ((x * 37 + y * 17) & 0x1) == 0; ETextureOrientation texturePos; int textureindex; if (toplandscape == leftlandscape && toplandscape == rightlandscape) { textureindex = toplandscape.getImageNumber(); texturePos = ETextureOrientation.CONTINUOUS_UP; } else if (leftlandscape == rightlandscape) { texturePos = ETextureOrientation.BOTTOM; textureindex = getBorder(leftlandscape, toplandscape, useSecond); } else if (leftlandscape == toplandscape) { texturePos = ETextureOrientation.TOPLEFT; textureindex = getBorder(leftlandscape, rightlandscape, useSecond); } else { texturePos = ETextureOrientation.TOPRIGHT; textureindex = getBorder(toplandscape, leftlandscape, useSecond); } int[] positions = TEXTURE_POSITIONS[textureindex]; // texture position int adddx = 0; int adddy = 0; if (positions[2] >= 2) { adddx = x * DrawConstants.DISTANCE_X - y * DrawConstants.DISTANCE_X / 2; adddy = y * DrawConstants.DISTANCE_Y; adddx = realModulo(adddx, (positions[2] - 1) * TEXTURE_GRID); adddy = realModulo(adddy, (positions[2] - 1) * TEXTURE_GRID); } adddx += positions[0] * TEXTURE_GRID; adddy += positions[1] * TEXTURE_GRID; float[] relativeTexCoords = texturePos.getRelativecoords(); { // top float u = (relativeTexCoords[0] + adddx) / TEXTURE_SIZE; float v = (relativeTexCoords[1] + adddy) / TEXTURE_SIZE; addPointToGeometry(context, buffer, x, y, u, v, fogBase + 0); } { // left float u = (relativeTexCoords[2] + adddx) / TEXTURE_SIZE; float v = (relativeTexCoords[3] + adddy) / TEXTURE_SIZE; addPointToGeometry(context, buffer, x, y + 1, u, v, fogBase + 2); } { // right float u = (relativeTexCoords[4] + adddx) / TEXTURE_SIZE; float v = (relativeTexCoords[5] + adddy) / TEXTURE_SIZE; addPointToGeometry(context, buffer, x + 1, y + 1, u, v, fogBase + 3); } } private void addPointToGeometry(MapDrawContext context, GLBuffer buffer, int x, int y, float u, float v, int fogOffset) { buffer.putFloat(x); buffer.putFloat(y); buffer.putFloat(context.getHeight(x, y)); buffer.putFloat(u); buffer.putFloat(v); addVertexcolor(context, buffer, x, y, fogOffset); } private static void addBlackPointToGeometry(MapDrawContext context, GLBuffer buffer, int x, int y) { buffer.putFloat(x); buffer.putFloat(y); buffer.putFloat(context.getHeight(x, y)); buffer.putFloat(0); buffer.putFloat(0); buffer.putByte(BLACK[0]); buffer.putByte(BLACK[1]); buffer.putByte(BLACK[2]); buffer.putByte(BLACK[3]); } private void addTriangle2ToGeometry(MapDrawContext context, GLBuffer buffer, int x, int y, int fogBase) { ELandscapeType leftlandscape = context.getLandscape(x, y); ELandscapeType bottomlandscape = context.getLandscape(x + 1, y + 1); ELandscapeType rightlandscape = context.getLandscape(x + 1, y); boolean useSecond = (x & 0x1) == 0; ETextureOrientation texturePos; int textureindex; if (bottomlandscape == leftlandscape && bottomlandscape == rightlandscape) { texturePos = ETextureOrientation.CONTINUOUS_DOWN; textureindex = bottomlandscape.getImageNumber(); } else if (leftlandscape == rightlandscape) { texturePos = ETextureOrientation.TOP; textureindex = getBorder(leftlandscape, bottomlandscape, useSecond); } else if (leftlandscape == bottomlandscape) { texturePos = ETextureOrientation.BOTTOMLEFT; textureindex = getBorder(leftlandscape, rightlandscape, useSecond); } else { texturePos = ETextureOrientation.BOTTOMRIGHT; textureindex = getBorder(rightlandscape, leftlandscape, useSecond); } int[] positions = TEXTURE_POSITIONS[textureindex]; // texture position int adddx = 0; int adddy = 0; if (positions[2] >= 2) { adddx = x * DrawConstants.DISTANCE_X - y * DrawConstants.DISTANCE_X / 2; adddy = y * DrawConstants.DISTANCE_Y; adddx = realModulo(adddx, (positions[2] - 1) * TEXTURE_GRID); adddy = realModulo(adddy, (positions[2] - 1) * TEXTURE_GRID); } adddx += positions[0] * TEXTURE_GRID; adddy += positions[1] * TEXTURE_GRID; float[] relativeTexCoords = texturePos.getRelativecoords(); { // left float u = (relativeTexCoords[0] + adddx) / TEXTURE_SIZE; float v = (relativeTexCoords[1] + adddy) / TEXTURE_SIZE; addPointToGeometry(context, buffer, x, y, u, v, fogBase + 0); } { // bottom float u = (relativeTexCoords[2] + adddx) / TEXTURE_SIZE; float v = (relativeTexCoords[3] + adddy) / TEXTURE_SIZE; addPointToGeometry(context, buffer, x + 1, y + 1, u, v, fogBase + 3); } { // right float u = (relativeTexCoords[4] + adddx) / TEXTURE_SIZE; float v = (relativeTexCoords[5] + adddy) / TEXTURE_SIZE; addPointToGeometry(context, buffer, x + 1, y, u, v, fogBase + 1); } } private static int realModulo(int number, int modulo) { if (number >= 0) { return number % modulo; } else { return number % modulo + modulo; } } private void addVertexcolor(MapDrawContext context, GLBuffer buffer, int x, int y, int fogOffset) { byte color; if (x <= 0 || x >= context.getMap().getWidth() - 2 || y <= 0 || y >= context.getMap().getHeight() - 2 || context.getVisibleStatus(x, y) <= 0) { color = 0; } else { int height1 = context.getHeight(x, y - 1); int height2 = context.getHeight(x, y); float fcolor = 0.9f + (height1 - height2) * .1f; if (fcolor > 1.0f) { fcolor = 1.0f; } else if (fcolor < 0.4f) { fcolor = 0.4f; } fcolor *= (float) fogOfWarStatus[fogOffset] / CommonConstants.FOG_OF_WAR_VISIBLE; fcolor *= 255f; color = (byte) (int) fcolor; } buffer.putByte(color); buffer.putByte(color); buffer.putByte(color); buffer.putByte((byte) 255); } @Override public void backgroundChangedAt(int x, int y) { if (oldBufferPosition != null) { if (oldBufferPosition.contains(x, y)) { invalidatePoint(x, y); } if (oldBufferPosition.contains(x - 1, y)) { invalidatePoint(x - 1, y); } if (oldBufferPosition.contains(x - 1, y - 1)) { invalidatePoint(x - 1, y - 1); } if (oldBufferPosition.contains(x, y - 1)) { invalidatePoint(x, y - 1); } } } public static void invalidateTexture() { texture = -1; } }
package com.googlecode.jslint4java.cli; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Field; import java.nio.charset.Charset; import java.util.List; import com.beust.jcommander.JCommander; import com.beust.jcommander.ParameterDescription; import com.beust.jcommander.ParameterException; import com.googlecode.jslint4java.Issue; import com.googlecode.jslint4java.JSLint; import com.googlecode.jslint4java.JSLintBuilder; import com.googlecode.jslint4java.JSLintResult; import com.googlecode.jslint4java.Option; import com.googlecode.jslint4java.formatter.CheckstyleXmlFormatter; import com.googlecode.jslint4java.formatter.JSLintResultFormatter; import com.googlecode.jslint4java.formatter.JSLintXmlFormatter; import com.googlecode.jslint4java.formatter.JUnitXmlFormatter; import com.googlecode.jslint4java.formatter.PlainFormatter; import com.googlecode.jslint4java.formatter.ReportFormatter; /** * A command line interface to {@link JSLint}. * * @author dom */ class Main { /** * The default command line output. */ private static final class DefaultFormatter implements JSLintResultFormatter { public String format(JSLintResult result) { StringBuilder sb = new StringBuilder(); for (Issue issue : result.getIssues()) { sb.append(PROGNAME); sb.append(':'); sb.append(issue.toString()); sb.append('\n'); } return sb.toString(); } public String footer() { return null; } public String header() { return null; } } @SuppressWarnings("serial") private static class DieException extends RuntimeException { private final int code; public DieException(String message, int code) { super(message); this.code = code; } public int getCode() { return code; } } private static final String PROGNAME = "jslint"; /** * The main entry point. Try passing in "--help" for more details. * * @param args * One or more JavaScript files. * @throws IOException */ public static void main(String[] args) throws IOException { try { System.exit(new Main().run(args)); } catch (DieException e) { if (e.getMessage() != null) { System.err.println(PROGNAME + ": " + e.getMessage()); } System.exit(e.getCode()); } } private int run(String[] args) throws IOException { List<String> files = processOptions(args); if (formatter.header() != null) { info(formatter.header()); } for (String file : files) { lintFile(file); } if (formatter.footer() != null) { info(formatter.footer()); } return isErrored() ? 1 : 0; } private Charset encoding = Charset.defaultCharset(); private boolean errored = false; private JSLintResultFormatter formatter; private JSLint lint; private Main() throws IOException { lint = new JSLintBuilder().fromDefault(); } private void die(String message) { throw new DieException(message, 1); } /** * Fetch the named {@link Option}, or null if there is no matching one. */ private Option getOption(String optName) { try { return Option.valueOf(optName); } catch (IllegalArgumentException e) { return null; } } private void info(String message) { System.out.println(message); } private boolean isErrored() { return errored; } private void lintFile(String file) throws IOException { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding)); JSLintResult result = lint.lint(file, reader); info(formatter.format(result)); if (!result.getIssues().isEmpty()) { setErrored(true); } } catch (FileNotFoundException e) { die(file + ": No such file or directory."); } finally { if (reader != null) { reader.close(); } } } private List<String> processOptions(String[] args) { JSLintFlags jslintFlags = new JSLintFlags(); Flags flags = new Flags(); JCommander jc = new JCommander(new Object[] { flags , jslintFlags }); jc.setProgramName("jslint4java"); try { jc.parse(args); } catch (ParameterException e) { info(e.getMessage()); usage(jc); } if (flags.help) { usage(jc); } if (flags.encoding != null) { encoding = flags.encoding; } if (flags.jslint != null) { setJSLint(flags.jslint); } setResultFormatter(flags.report); for (ParameterDescription pd : jc.getParameters()) { Field field = pd.getField(); // Is it declared on JSLintFlags? if (!field.getDeclaringClass().isAssignableFrom(JSLintFlags.class)) { continue; } try { // Need to get Option. Option o = getOption(field.getName()); // Need to get value. Object val = field.get(jslintFlags); if (val == null) { continue; } Class<?> type = field.getType(); if (type.isAssignableFrom(Boolean.class)) { lint.addOption(o); } // In theory, everything else should be a String for later parsing. else if (type.isAssignableFrom(String.class)) { lint.addOption(o, (String) val); } else { die("unknown type \"" + type + "\" (for " + field.getName() + ")"); } } catch (IllegalArgumentException e) { die(e.getMessage()); } catch (IllegalAccessException e) { die(e.getMessage()); } } if (flags.files.isEmpty()) { usage(jc); return null; // can never happen } else return flags.files; } private void setErrored(boolean errored) { this.errored = errored; } private void setJSLint(String jslint) { try { lint = new JSLintBuilder().fromFile(new File(jslint)); } catch (IOException e) { die(e.getMessage()); } } private void setResultFormatter(String reportType) { if (reportType == null || reportType.equals("")) { // The original CLI behaviour: one-per-line, with prefix. formatter = new DefaultFormatter(); } else if (reportType.equals("plain")) { formatter = new PlainFormatter(); } else if (reportType.equals("xml")) { formatter = new JSLintXmlFormatter(); } else if (reportType.equals("junit")) { formatter = new JUnitXmlFormatter(); } else if (reportType.equals("report")) { formatter = new ReportFormatter(); } else if (reportType.equals("checkstyle")) { formatter = new CheckstyleXmlFormatter(); } else { die("unknown report type '" + reportType + "'"); } } private void usage(JCommander jc) { jc.usage(); info("using jslint version " + lint.getEdition()); throw new DieException(null, 0); } }
package org.junit.gen5.engine; import static org.junit.gen5.commons.meta.API.Usage.Experimental; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Optional; import org.junit.gen5.commons.meta.API; import org.junit.gen5.commons.util.ToStringBuilder; /** * {@code UniqueId} encapsulates the creation, parsing, and display of unique IDs * for {@link TestDescriptor TestDescriptors}. * * <p>Instances of this class have value semantics and are immutable.</p> * * @since 5.0 */ @API(Experimental) public class UniqueId implements Cloneable { private static final String TYPE_ENGINE = "engine"; /** * Parse a {@code UniqueId} from the supplied string representation using the * default format. * * <p>Throws a {@link org.junit.gen5.commons.JUnitException JUnitException} * if the string cannot be parsed. * * @return a properly constructed {@code UniqueId} */ public static UniqueId parse(String uniqueIdString) { return UniqueIdFormat.getDefault().parse(uniqueIdString); } /** * Create an engine's unique ID by from its {@code engineId} using the default * format. */ public static UniqueId forEngine(String engineId) { return root(TYPE_ENGINE, engineId); } /** * Create a root unique ID from the supplied {@code segmentType} and * {@code nodeValue} using the default format. */ public static UniqueId root(String segmentType, String nodeValue) { List<Segment> segments = Collections.singletonList(new Segment(segmentType, nodeValue)); return new UniqueId(UniqueIdFormat.getDefault(), segments); } private final UniqueIdFormat uniqueIdFormat; private final List<Segment> segments = new ArrayList<>(); UniqueId(UniqueIdFormat uniqueIdFormat, List<Segment> segments) { this.uniqueIdFormat = uniqueIdFormat; this.segments.addAll(segments); } /** * Create and deliver the string representation of the {@code UniqueId} */ public String getUniqueString() { return uniqueIdFormat.format(this); } public Optional<Segment> getRoot() { return getSegments().stream().findFirst(); } public Optional<String> getEngineId() { return getRoot().filter(segment -> segment.getType().equals(TYPE_ENGINE)).map(Segment::getValue); } public List<Segment> getSegments() { return new ArrayList<>(segments); } /** * Construct a new {@code UniqueId} by appending a {@link Segment} to the end of the current instance * with {@code segmentType} and {@code value}. * * <p>The current instance is left unchanged.</p> * * <p>Both {@code segmentType} and {@code segmentType} must not contain any of the special characters used * for constructing the string representation. This allows more robust parsing.</p> */ public UniqueId append(String segmentType, String value) { Segment segment = new Segment(segmentType, value); return append(segment); } public UniqueId append(Segment segment) { UniqueId clone = new UniqueId(this.uniqueIdFormat, this.segments); clone.segments.add(segment); return clone; } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; UniqueId uniqueId = (UniqueId) o; return segments.equals(uniqueId.segments); } @Override public int hashCode() { return segments.hashCode(); } @Override public String toString() { return getUniqueString(); } public static class Segment { private final String type; private final String value; Segment(String type, String value) { this.type = type; this.value = value; } public String getType() { return this.type; } public String getValue() { return this.value; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Segment that = (Segment) o; return Objects.equals(this.type, that.type) && Objects.equals(this.value, that.value); } @Override public String toString() { // @formatter:off return new ToStringBuilder(this) .append("type", this.type) .append("value", this.value) .toString(); // @formatter:on } @Override public int hashCode() { return Objects.hash(this.type, this.value); } } }
package org.junit.gen5.launcher; /** * The {@code Launcher} API is the main entry point for client code that * wishes to <em>discover</em> and <em>execute</em> tests using one or more * {@linkplain org.junit.gen5.engine.TestEngine test engines}. * * <p>Implementations of this interface are responsible for determining * the set of test engines to delegate to at runtime. For example, the * {@link org.junit.gen5.launcher.main.DefaultLauncher DefaultLauncher} * dynamically registers test engines via Java's * {@link java.util.ServiceLoader ServiceLoader} mechanism. * * <p>Discovery and execution of tests require a {@link TestDiscoveryRequest} * which is passed to all registered engines. Each engine decides which tests * it can discover and later execute according to the {@link TestDiscoveryRequest}. * * <p>Clients of this interface may optionally call {@link #discover} prior to * {@link #execute} in order to inspect the {@link TestPlan} before executing * it. * * <p>Prior to executing tests, clients of this interface should * {@linkplain #registerTestExecutionListeners register} one or more * {@link TestExecutionListener} instances in order to get feedback about the * progress and results of test execution. Listeners will be notified of events * in the order in which they were registered. * * @since 5.0 * @see TestDiscoveryRequest * @see TestPlan * @see TestExecutionListener * @see org.junit.gen5.launcher.main.DefaultLauncher * @see org.junit.gen5.engine.TestEngine */ public interface Launcher { /** * Register one or more listeners for test execution. * * @param listeners the listeners to be notified of test execution events */ void registerTestExecutionListeners(TestExecutionListener... listeners); /** * Discover tests and build a {@link TestPlan} according to the supplied * {@link TestDiscoveryRequest} by querying all registered engines and * collecting their results. * * @param testDiscoveryRequest the test discovery request * @return a {@code TestPlan} that contains all resolved {@linkplain * TestIdentifier identifiers} from all registered engines */ TestPlan discover(TestDiscoveryRequest testDiscoveryRequest); /** * Execute a {@link TestPlan} which is built according to the supplied * {@link TestDiscoveryRequest} by querying all registered engines and * collecting their results, and notify {@linkplain #registerTestExecutionListeners * registered listeners} about the progress and results of the execution. * * @param testDiscoveryRequest the test discovery request */ void execute(TestDiscoveryRequest testDiscoveryRequest); }
package com.fsck.k9.fragment; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.EnumMap; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.Future; import android.app.Activity; import android.app.DialogFragment; import android.app.Fragment; import android.app.LoaderManager; import android.app.LoaderManager.LoaderCallbacks; import android.content.BroadcastReceiver; import android.content.Context; import android.content.CursorLoader; import android.content.Intent; import android.content.IntentFilter; import android.content.Loader; import android.database.Cursor; import android.graphics.Rect; import android.net.Uri; import android.os.Bundle; import android.os.Parcelable; import android.support.v4.content.LocalBroadcastManager; import android.support.v4.widget.SwipeRefreshLayout; import android.text.TextUtils; import timber.log.Timber; import android.view.ActionMode; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.fsck.k9.Account; import com.fsck.k9.Account.SortType; import com.fsck.k9.BuildConfig; import com.fsck.k9.K9; import com.fsck.k9.Preferences; import com.fsck.k9.R; import com.fsck.k9.activity.ActivityListener; import com.fsck.k9.activity.ChooseFolder; import com.fsck.k9.activity.FolderInfoHolder; import com.fsck.k9.activity.MessageReference; import com.fsck.k9.activity.misc.ContactPictureLoader; import com.fsck.k9.cache.EmailProviderCache; import com.fsck.k9.controller.MessagingController; import com.fsck.k9.fragment.ConfirmationDialogFragment.ConfirmationDialogFragmentListener; import com.fsck.k9.fragment.MessageListFragmentComparators.ArrivalComparator; import com.fsck.k9.fragment.MessageListFragmentComparators.AttachmentComparator; import com.fsck.k9.fragment.MessageListFragmentComparators.ComparatorChain; import com.fsck.k9.fragment.MessageListFragmentComparators.DateComparator; import com.fsck.k9.fragment.MessageListFragmentComparators.FlaggedComparator; import com.fsck.k9.fragment.MessageListFragmentComparators.ReverseComparator; import com.fsck.k9.fragment.MessageListFragmentComparators.ReverseIdComparator; import com.fsck.k9.fragment.MessageListFragmentComparators.SenderComparator; import com.fsck.k9.fragment.MessageListFragmentComparators.SubjectComparator; import com.fsck.k9.fragment.MessageListFragmentComparators.UnreadComparator; import com.fsck.k9.helper.ContactPicture; import com.fsck.k9.helper.MergeCursorWithUniqueId; import com.fsck.k9.helper.MessageHelper; import com.fsck.k9.helper.Utility; import com.fsck.k9.mail.Flag; import com.fsck.k9.mail.Folder; import com.fsck.k9.mail.Message; import com.fsck.k9.mail.MessagingException; import com.fsck.k9.mailstore.LocalFolder; import com.fsck.k9.preferences.StorageEditor; import com.fsck.k9.provider.EmailProvider; import com.fsck.k9.provider.EmailProvider.MessageColumns; import com.fsck.k9.provider.EmailProvider.SpecialColumns; import com.fsck.k9.search.ConditionsTreeNode; import com.fsck.k9.search.LocalSearch; import com.fsck.k9.search.SearchSpecification; import com.fsck.k9.search.SearchSpecification.SearchCondition; import com.fsck.k9.search.SearchSpecification.SearchField; import com.fsck.k9.search.SqlQueryBuilder; import static com.fsck.k9.fragment.MLFProjectionInfo.ACCOUNT_UUID_COLUMN; import static com.fsck.k9.fragment.MLFProjectionInfo.FLAGGED_COLUMN; import static com.fsck.k9.fragment.MLFProjectionInfo.FOLDER_NAME_COLUMN; import static com.fsck.k9.fragment.MLFProjectionInfo.ID_COLUMN; import static com.fsck.k9.fragment.MLFProjectionInfo.PROJECTION; import static com.fsck.k9.fragment.MLFProjectionInfo.READ_COLUMN; import static com.fsck.k9.fragment.MLFProjectionInfo.SUBJECT_COLUMN; import static com.fsck.k9.fragment.MLFProjectionInfo.THREADED_PROJECTION; import static com.fsck.k9.fragment.MLFProjectionInfo.THREAD_COUNT_COLUMN; import static com.fsck.k9.fragment.MLFProjectionInfo.THREAD_ROOT_COLUMN; import static com.fsck.k9.fragment.MLFProjectionInfo.UID_COLUMN; public class MessageListFragment extends Fragment implements OnItemClickListener, ConfirmationDialogFragmentListener, LoaderCallbacks<Cursor> { public static MessageListFragment newInstance( LocalSearch search, boolean isThreadDisplay, boolean threadedList) { MessageListFragment fragment = new MessageListFragment(); Bundle args = new Bundle(); args.putParcelable(ARG_SEARCH, search); args.putBoolean(ARG_IS_THREAD_DISPLAY, isThreadDisplay); args.putBoolean(ARG_THREADED_LIST, threadedList); fragment.setArguments(args); return fragment; } private static final int ACTIVITY_CHOOSE_FOLDER_MOVE = 1; private static final int ACTIVITY_CHOOSE_FOLDER_COPY = 2; private static final String ARG_SEARCH = "searchObject"; private static final String ARG_THREADED_LIST = "showingThreadedList"; private static final String ARG_IS_THREAD_DISPLAY = "isThreadedDisplay"; private static final String STATE_SELECTED_MESSAGES = "selectedMessages"; private static final String STATE_ACTIVE_MESSAGE = "activeMessage"; private static final String STATE_REMOTE_SEARCH_PERFORMED = "remoteSearchPerformed"; private static final String STATE_MESSAGE_LIST = "listState"; /** * Maps a {@link SortType} to a {@link Comparator} implementation. */ private static final Map<SortType, Comparator<Cursor>> SORT_COMPARATORS; static { // fill the mapping at class time loading final Map<SortType, Comparator<Cursor>> map = new EnumMap<>(SortType.class); map.put(SortType.SORT_ATTACHMENT, new AttachmentComparator()); map.put(SortType.SORT_DATE, new DateComparator()); map.put(SortType.SORT_ARRIVAL, new ArrivalComparator()); map.put(SortType.SORT_FLAGGED, new FlaggedComparator()); map.put(SortType.SORT_SUBJECT, new SubjectComparator()); map.put(SortType.SORT_SENDER, new SenderComparator()); map.put(SortType.SORT_UNREAD, new UnreadComparator()); // make it immutable to prevent accidental alteration (content is immutable already) SORT_COMPARATORS = Collections.unmodifiableMap(map); } ListView listView; private SwipeRefreshLayout swipeRefreshLayout; Parcelable savedListState; int previewLines = 0; private MessageListAdapter adapter; private View footerView; private FolderInfoHolder currentFolder; private LayoutInflater layoutInflater; private MessagingController messagingController; private Account account; private String[] accountUuids; private int unreadMessageCount = 0; private Cursor[] cursors; private boolean[] cursorValid; int uniqueIdColumn; /** * Stores the name of the folder that we want to open as soon as possible after load. */ private String folderName; private boolean remoteSearchPerformed = false; private Future<?> remoteSearchFuture = null; private List<Message> extraSearchResults; private String title; private LocalSearch search = null; private boolean singleAccountMode; private boolean singleFolderMode; private boolean allAccounts; private final MessageListHandler handler = new MessageListHandler(this); private SortType sortType = SortType.SORT_DATE; private boolean sortAscending = true; private boolean sortDateAscending = false; boolean senderAboveSubject = false; boolean checkboxes = true; boolean stars = true; private int selectedCount = 0; Set<Long> selected = new HashSet<>(); private ActionMode actionMode; private Boolean hasConnectivity; /** * Relevant messages for the current context when we have to remember the chosen messages * between user interactions (e.g. selecting a folder for move operation). */ private List<MessageReference> activeMessages; /* package visibility for faster inner class access */ MessageHelper messageHelper; private final ActionModeCallback actionModeCallback = new ActionModeCallback(); MessageListFragmentListener fragmentListener; boolean showingThreadedList; private boolean isThreadDisplay; private Context context; private final ActivityListener activityListener = new MessageListActivityListener(); private Preferences preferences; private boolean loaderJustInitialized; MessageReference activeMessage; /** * {@code true} after {@link #onCreate(Bundle)} was executed. Used in {@link #updateTitle()} to * make sure we don't access member variables before initialization is complete. */ private boolean initialized = false; ContactPictureLoader contactsPictureLoader; private LocalBroadcastManager localBroadcastManager; private BroadcastReceiver cacheBroadcastReceiver; private IntentFilter cacheIntentFilter; /** * Stores the unique ID of the message the context menu was opened for. * * We have to save this because the message list might change between the time the menu was * opened and when the user clicks on a menu item. When this happens the 'adapter position' that * is accessible via the {@code ContextMenu} object might correspond to another list item and we * would end up using/modifying the wrong message. * * The value of this field is {@code 0} when no context menu is currently open. */ private long contextMenuUniqueId = 0; /** * @return The comparator to use to display messages in an ordered * fashion. Never {@code null}. */ private Comparator<Cursor> getComparator() { final List<Comparator<Cursor>> chain = new ArrayList<>(3 /* we add 3 comparators at most */); // Add the specified comparator final Comparator<Cursor> comparator = SORT_COMPARATORS.get(sortType); if (sortAscending) { chain.add(comparator); } else { chain.add(new ReverseComparator<>(comparator)); } // Add the date comparator if not already specified if (sortType != SortType.SORT_DATE && sortType != SortType.SORT_ARRIVAL) { final Comparator<Cursor> dateComparator = SORT_COMPARATORS.get(SortType.SORT_DATE); if (sortDateAscending) { chain.add(dateComparator); } else { chain.add(new ReverseComparator<>(dateComparator)); } } // Add the id comparator chain.add(new ReverseIdComparator()); // Build the comparator chain return new ComparatorChain<>(chain); } void folderLoading(String folder, boolean loading) { if (currentFolder != null && currentFolder.name.equals(folder)) { currentFolder.loading = loading; } updateMoreMessagesOfCurrentFolder(); updateFooterView(); } public void updateTitle() { if (!initialized) { return; } setWindowTitle(); if (!search.isManualSearch()) { setWindowProgress(); } } private void setWindowProgress() { int level = Window.PROGRESS_END; if (currentFolder != null && currentFolder.loading && activityListener.getFolderTotal() > 0) { int divisor = activityListener.getFolderTotal(); if (divisor != 0) { level = (Window.PROGRESS_END / divisor) * (activityListener.getFolderCompleted()) ; if (level > Window.PROGRESS_END) { level = Window.PROGRESS_END; } } } fragmentListener.setMessageListProgress(level); } private void setWindowTitle() { // regular folder content display if (!isManualSearch() && singleFolderMode) { Activity activity = getActivity(); String displayName = FolderInfoHolder.getDisplayName(activity, account, folderName); fragmentListener.setMessageListTitle(displayName); String operation = activityListener.getOperation(activity); if (operation.length() < 1) { fragmentListener.setMessageListSubTitle(account.getEmail()); } else { fragmentListener.setMessageListSubTitle(operation); } } else { // query result display. This may be for a search folder as opposed to a user-initiated search. if (title != null) { // This was a search folder; the search folder has overridden our title. fragmentListener.setMessageListTitle(title); } else { // This is a search result; set it to the default search result line. fragmentListener.setMessageListTitle(getString(R.string.search_results)); } fragmentListener.setMessageListSubTitle(null); } // set unread count if (unreadMessageCount <= 0) { fragmentListener.setUnreadCount(0); } else { if (!singleFolderMode && title == null) { // The unread message count is easily confused // with total number of messages in the search result, so let's hide it. fragmentListener.setUnreadCount(0); } else { fragmentListener.setUnreadCount(unreadMessageCount); } } } void progress(final boolean progress) { fragmentListener.enableActionBarProgress(progress); if (swipeRefreshLayout != null && !progress) { swipeRefreshLayout.setRefreshing(false); } } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (view == footerView) { if (currentFolder != null && !search.isManualSearch() && currentFolder.moreMessages) { messagingController.loadMoreMessages(account, folderName, null); } else if (currentFolder != null && isRemoteSearch() && extraSearchResults != null && extraSearchResults.size() > 0) { int numResults = extraSearchResults.size(); int limit = account.getRemoteSearchNumResults(); List<Message> toProcess = extraSearchResults; if (limit > 0 && numResults > limit) { toProcess = toProcess.subList(0, limit); extraSearchResults = extraSearchResults.subList(limit, extraSearchResults.size()); } else { extraSearchResults = null; updateFooter(null); } messagingController.loadSearchResults(account, currentFolder.name, toProcess, activityListener); } return; } Cursor cursor = (Cursor) parent.getItemAtPosition(position); if (cursor == null) { return; } if (selectedCount > 0) { toggleMessageSelect(position); } else { if (showingThreadedList && cursor.getInt(THREAD_COUNT_COLUMN) > 1) { Account account = getAccountFromCursor(cursor); String folderName = cursor.getString(FOLDER_NAME_COLUMN); // If threading is enabled and this item represents a thread, display the thread contents. long rootId = cursor.getLong(THREAD_ROOT_COLUMN); fragmentListener.showThread(account, folderName, rootId); } else { // This item represents a message; just display the message. openMessageAtPosition(listViewToAdapterPosition(position)); } } } @Override public void onAttach(Activity activity) { super.onAttach(activity); context = activity.getApplicationContext(); try { fragmentListener = (MessageListFragmentListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.getClass() + " must implement MessageListFragmentListener"); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Context appContext = getActivity().getApplicationContext(); preferences = Preferences.getPreferences(appContext); messagingController = MessagingController.getInstance(getActivity().getApplication()); previewLines = K9.messageListPreviewLines(); checkboxes = K9.messageListCheckboxes(); stars = K9.messageListStars(); if (K9.showContactPicture()) { contactsPictureLoader = ContactPicture.getContactPictureLoader(getActivity()); } restoreInstanceState(savedInstanceState); decodeArguments(); createCacheBroadcastReceiver(appContext); initialized = true; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { layoutInflater = inflater; View view = inflater.inflate(R.layout.message_list_fragment, container, false); initializePullToRefresh(view); initializeLayout(); listView.setVerticalFadingEdgeEnabled(false); return view; } @Override public void onDestroyView() { savedListState = listView.onSaveInstanceState(); super.onDestroyView(); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); messageHelper = MessageHelper.getInstance(getActivity()); initializeMessageList(); // This needs to be done before initializing the cursor loader below initializeSortSettings(); loaderJustInitialized = true; LoaderManager loaderManager = getLoaderManager(); int len = accountUuids.length; cursors = new Cursor[len]; cursorValid = new boolean[len]; for (int i = 0; i < len; i++) { loaderManager.initLoader(i, null, this); cursorValid[i] = false; } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); saveSelectedMessages(outState); saveListState(outState); outState.putBoolean(STATE_REMOTE_SEARCH_PERFORMED, remoteSearchPerformed); if (activeMessage != null) { outState.putString(STATE_ACTIVE_MESSAGE, activeMessage.toIdentityString()); } } /** * Restore the state of a previous {@link MessageListFragment} instance. * * @see #onSaveInstanceState(Bundle) */ private void restoreInstanceState(Bundle savedInstanceState) { if (savedInstanceState == null) { return; } restoreSelectedMessages(savedInstanceState); remoteSearchPerformed = savedInstanceState.getBoolean(STATE_REMOTE_SEARCH_PERFORMED); savedListState = savedInstanceState.getParcelable(STATE_MESSAGE_LIST); String messageReferenceString = savedInstanceState.getString(STATE_ACTIVE_MESSAGE); activeMessage = MessageReference.parse(messageReferenceString); } /** * Write the unique IDs of selected messages to a {@link Bundle}. */ private void saveSelectedMessages(Bundle outState) { long[] selected = new long[this.selected.size()]; int i = 0; for (Long id : this.selected) { selected[i++] = id; } outState.putLongArray(STATE_SELECTED_MESSAGES, selected); } /** * Restore selected messages from a {@link Bundle}. */ private void restoreSelectedMessages(Bundle savedInstanceState) { long[] selected = savedInstanceState.getLongArray(STATE_SELECTED_MESSAGES); if (selected != null) { for (long id : selected) { this.selected.add(id); } } } private void saveListState(Bundle outState) { if (savedListState != null) { // The previously saved state was never restored, so just use that. outState.putParcelable(STATE_MESSAGE_LIST, savedListState); } else if (listView != null) { outState.putParcelable(STATE_MESSAGE_LIST, listView.onSaveInstanceState()); } } private void initializeSortSettings() { if (singleAccountMode) { sortType = account.getSortType(); sortAscending = account.isSortAscending(sortType); sortDateAscending = account.isSortAscending(SortType.SORT_DATE); } else { sortType = K9.getSortType(); sortAscending = K9.isSortAscending(sortType); sortDateAscending = K9.isSortAscending(SortType.SORT_DATE); } } private void decodeArguments() { Bundle args = getArguments(); showingThreadedList = args.getBoolean(ARG_THREADED_LIST, false); isThreadDisplay = args.getBoolean(ARG_IS_THREAD_DISPLAY, false); search = args.getParcelable(ARG_SEARCH); title = search.getName(); String[] accountUuids = search.getAccountUuids(); singleAccountMode = false; if (accountUuids.length == 1 && !search.searchAllAccounts()) { singleAccountMode = true; account = preferences.getAccount(accountUuids[0]); } singleFolderMode = false; if (singleAccountMode && (search.getFolderNames().size() == 1)) { singleFolderMode = true; folderName = search.getFolderNames().get(0); currentFolder = getFolderInfoHolder(folderName, account); } allAccounts = false; if (singleAccountMode) { this.accountUuids = new String[] { account.getUuid() }; } else { if (accountUuids.length == 1 && accountUuids[0].equals(SearchSpecification.ALL_ACCOUNTS)) { allAccounts = true; List<Account> accounts = preferences.getAccounts(); this.accountUuids = new String[accounts.size()]; for (int i = 0, len = accounts.size(); i < len; i++) { this.accountUuids[i] = accounts.get(i).getUuid(); } if (this.accountUuids.length == 1) { singleAccountMode = true; account = accounts.get(0); } } else { this.accountUuids = accountUuids; } } } private void initializeMessageList() { adapter = new MessageListAdapter(this); if (folderName != null) { currentFolder = getFolderInfoHolder(folderName, account); } if (singleFolderMode) { listView.addFooterView(getFooterView(listView)); updateFooterView(); } listView.setAdapter(adapter); } private void createCacheBroadcastReceiver(Context appContext) { localBroadcastManager = LocalBroadcastManager.getInstance(appContext); cacheBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { adapter.notifyDataSetChanged(); } }; cacheIntentFilter = new IntentFilter(EmailProviderCache.ACTION_CACHE_UPDATED); } private FolderInfoHolder getFolderInfoHolder(String folderName, Account account) { try { LocalFolder localFolder = MlfUtils.getOpenFolder(folderName, account); return new FolderInfoHolder(context, localFolder, account); } catch (MessagingException e) { throw new RuntimeException(e); } } @Override public void onPause() { super.onPause(); localBroadcastManager.unregisterReceiver(cacheBroadcastReceiver); activityListener.onPause(getActivity()); messagingController.removeListener(activityListener); if (swipeRefreshLayout != null) { swipeRefreshLayout.setRefreshing(false); swipeRefreshLayout.destroyDrawingCache(); swipeRefreshLayout.clearAnimation(); } } /** * On resume we refresh messages for the folder that is currently open. * This guarantees that things like unread message count and read status * are updated. */ @Override public void onResume() { super.onResume(); senderAboveSubject = K9.messageListSenderAboveSubject(); if (!loaderJustInitialized) { restartLoader(); } else { loaderJustInitialized = false; } // Check if we have connectivity. Cache the value. if (hasConnectivity == null) { hasConnectivity = Utility.hasConnectivity(getActivity().getApplication()); } localBroadcastManager.registerReceiver(cacheBroadcastReceiver, cacheIntentFilter); activityListener.onResume(getActivity()); messagingController.addListener(activityListener); //Cancel pending new mail notifications when we open an account List<Account> accountsWithNotification; Account account = this.account; if (account != null) { accountsWithNotification = Collections.singletonList(account); } else { accountsWithNotification = preferences.getAccounts(); } for (Account accountWithNotification : accountsWithNotification) { messagingController.cancelNotificationsForAccount(accountWithNotification); } if (this.account != null && folderName != null && !search.isManualSearch()) { messagingController.getFolderUnreadMessageCount(this.account, folderName, activityListener); } updateTitle(); } private void restartLoader() { if (cursorValid == null) { return; } // Refresh the message list LoaderManager loaderManager = getLoaderManager(); for (int i = 0; i < accountUuids.length; i++) { loaderManager.restartLoader(i, null, this); cursorValid[i] = false; } } private void initializePullToRefresh(View layout) { swipeRefreshLayout = (SwipeRefreshLayout) layout.findViewById(R.id.swiperefresh); listView = (ListView) layout.findViewById(R.id.message_list); if (isRemoteSearchAllowed()) { swipeRefreshLayout.setOnRefreshListener( new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { onRemoteSearchRequested(); } } ); } else if (isCheckMailSupported()) { swipeRefreshLayout.setOnRefreshListener( new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { checkMail(); } } ); } // Disable pull-to-refresh until the message list has been loaded swipeRefreshLayout.setEnabled(false); } private void initializeLayout() { listView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); listView.setLongClickable(true); listView.setFastScrollEnabled(true); listView.setScrollingCacheEnabled(false); listView.setOnItemClickListener(this); registerForContextMenu(listView); } public void onCompose() { if (!singleAccountMode) { /* * If we have a query string, we don't have an account to let * compose start the default action. */ fragmentListener.onCompose(null); } else { fragmentListener.onCompose(account); } } private void onReply(MessageReference messageReference) { fragmentListener.onReply(messageReference); } private void onReplyAll(MessageReference messageReference) { fragmentListener.onReplyAll(messageReference); } private void onForward(MessageReference messageReference) { fragmentListener.onForward(messageReference); } private void onResendMessage(MessageReference messageReference) { fragmentListener.onResendMessage(messageReference); } public void changeSort(SortType sortType) { Boolean sortAscending = (this.sortType == sortType) ? !this.sortAscending : null; changeSort(sortType, sortAscending); } /** * User has requested a remote search. Setup the bundle and start the intent. */ private void onRemoteSearchRequested() { String searchAccount; String searchFolder; searchAccount = account.getUuid(); searchFolder = currentFolder.name; String queryString = search.getRemoteSearchArguments(); remoteSearchPerformed = true; remoteSearchFuture = messagingController.searchRemoteMessages(searchAccount, searchFolder, queryString, null, null, activityListener); swipeRefreshLayout.setEnabled(false); fragmentListener.remoteSearchStarted(); } /** * Change the sort type and sort order used for the message list. * * @param sortType * Specifies which field to use for sorting the message list. * @param sortAscending * Specifies the sort order. If this argument is {@code null} the default search order * for the sort type is used. */ // FIXME: Don't save the changes in the UI thread private void changeSort(SortType sortType, Boolean sortAscending) { this.sortType = sortType; Account account = this.account; if (account != null) { account.setSortType(this.sortType); if (sortAscending == null) { this.sortAscending = account.isSortAscending(this.sortType); } else { this.sortAscending = sortAscending; } account.setSortAscending(this.sortType, this.sortAscending); sortDateAscending = account.isSortAscending(SortType.SORT_DATE); account.save(preferences); } else { K9.setSortType(this.sortType); if (sortAscending == null) { this.sortAscending = K9.isSortAscending(this.sortType); } else { this.sortAscending = sortAscending; } K9.setSortAscending(this.sortType, this.sortAscending); sortDateAscending = K9.isSortAscending(SortType.SORT_DATE); StorageEditor editor = preferences.getStorage().edit(); K9.save(editor); editor.commit(); } reSort(); } private void reSort() { int toastString = sortType.getToast(sortAscending); Toast toast = Toast.makeText(getActivity(), toastString, Toast.LENGTH_SHORT); toast.show(); LoaderManager loaderManager = getLoaderManager(); for (int i = 0, len = accountUuids.length; i < len; i++) { loaderManager.restartLoader(i, null, this); } } public void onCycleSort() { SortType[] sorts = SortType.values(); int curIndex = 0; for (int i = 0; i < sorts.length; i++) { if (sorts[i] == sortType) { curIndex = i; break; } } curIndex++; if (curIndex == sorts.length) { curIndex = 0; } changeSort(sorts[curIndex]); } private void onDelete(MessageReference message) { onDelete(Collections.singletonList(message)); } private void onDelete(List<MessageReference> messages) { if (K9.confirmDelete()) { // remember the message selection for #onCreateDialog(int) activeMessages = messages; showDialog(R.id.dialog_confirm_delete); } else { onDeleteConfirmed(messages); } } private void onDeleteConfirmed(List<MessageReference> messages) { if (showingThreadedList) { messagingController.deleteThreads(messages); } else { messagingController.deleteMessages(messages, null); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode != Activity.RESULT_OK) { return; } switch (requestCode) { case ACTIVITY_CHOOSE_FOLDER_MOVE: case ACTIVITY_CHOOSE_FOLDER_COPY: { if (data == null) { return; } final String destFolderName = data.getStringExtra(ChooseFolder.EXTRA_NEW_FOLDER); final List<MessageReference> messages = activeMessages; if (destFolderName != null) { activeMessages = null; // don't need it any more if (messages.size() > 0) { MlfUtils.setLastSelectedFolderName(preferences, messages, destFolderName); } switch (requestCode) { case ACTIVITY_CHOOSE_FOLDER_MOVE: move(messages, destFolderName); break; case ACTIVITY_CHOOSE_FOLDER_COPY: copy(messages, destFolderName); break; } } break; } } } public void onExpunge() { if (currentFolder != null) { onExpunge(account, currentFolder.name); } } private void onExpunge(final Account account, String folderName) { messagingController.expunge(account, folderName); } private void showDialog(int dialogId) { DialogFragment fragment; switch (dialogId) { case R.id.dialog_confirm_spam: { String title = getString(R.string.dialog_confirm_spam_title); int selectionSize = activeMessages.size(); String message = getResources().getQuantityString( R.plurals.dialog_confirm_spam_message, selectionSize, selectionSize); String confirmText = getString(R.string.dialog_confirm_spam_confirm_button); String cancelText = getString(R.string.dialog_confirm_spam_cancel_button); fragment = ConfirmationDialogFragment.newInstance(dialogId, title, message, confirmText, cancelText); break; } case R.id.dialog_confirm_delete: { String title = getString(R.string.dialog_confirm_delete_title); int selectionSize = activeMessages.size(); String message = getResources().getQuantityString( R.plurals.dialog_confirm_delete_messages, selectionSize, selectionSize); String confirmText = getString(R.string.dialog_confirm_delete_confirm_button); String cancelText = getString(R.string.dialog_confirm_delete_cancel_button); fragment = ConfirmationDialogFragment.newInstance(dialogId, title, message, confirmText, cancelText); break; } case R.id.dialog_confirm_mark_all_as_read: { String title = getString(R.string.dialog_confirm_mark_all_as_read_title); String message = getString(R.string.dialog_confirm_mark_all_as_read_message); String confirmText = getString(R.string.dialog_confirm_mark_all_as_read_confirm_button); String cancelText = getString(R.string.dialog_confirm_mark_all_as_read_cancel_button); fragment = ConfirmationDialogFragment.newInstance(dialogId, title, message, confirmText, cancelText); break; } default: { throw new RuntimeException("Called showDialog(int) with unknown dialog id."); } } fragment.setTargetFragment(this, dialogId); fragment.show(getFragmentManager(), getDialogTag(dialogId)); } private String getDialogTag(int dialogId) { return "dialog-" + dialogId; } @Override public boolean onOptionsItemSelected(MenuItem item) { int itemId = item.getItemId(); switch (itemId) { case R.id.set_sort_date: { changeSort(SortType.SORT_DATE); return true; } case R.id.set_sort_arrival: { changeSort(SortType.SORT_ARRIVAL); return true; } case R.id.set_sort_subject: { changeSort(SortType.SORT_SUBJECT); return true; } case R.id.set_sort_sender: { changeSort(SortType.SORT_SENDER); return true; } case R.id.set_sort_flag: { changeSort(SortType.SORT_FLAGGED); return true; } case R.id.set_sort_unread: { changeSort(SortType.SORT_UNREAD); return true; } case R.id.set_sort_attach: { changeSort(SortType.SORT_ATTACHMENT); return true; } case R.id.select_all: { selectAll(); return true; } } if (!singleAccountMode) { // None of the options after this point are "safe" for search results //TODO: This is not true for "unread" and "starred" searches in regular folders return false; } switch (itemId) { case R.id.send_messages: { onSendPendingMessages(); return true; } case R.id.expunge: { if (currentFolder != null) { onExpunge(account, currentFolder.name); } return true; } default: { return super.onOptionsItemSelected(item); } } } public void onSendPendingMessages() { messagingController.sendPendingMessages(account, null); } @Override public boolean onContextItemSelected(android.view.MenuItem item) { if (contextMenuUniqueId == 0) { return false; } int adapterPosition = getPositionForUniqueId(contextMenuUniqueId); if (adapterPosition == AdapterView.INVALID_POSITION) { return false; } switch (item.getItemId()) { case R.id.deselect: case R.id.select: { toggleMessageSelectWithAdapterPosition(adapterPosition); break; } case R.id.reply: { onReply(getMessageAtPosition(adapterPosition)); break; } case R.id.reply_all: { onReplyAll(getMessageAtPosition(adapterPosition)); break; } case R.id.forward: { onForward(getMessageAtPosition(adapterPosition)); break; } case R.id.send_again: { onResendMessage(getMessageAtPosition(adapterPosition)); selectedCount = 0; break; } case R.id.same_sender: { Cursor cursor = (Cursor) adapter.getItem(adapterPosition); String senderAddress = MlfUtils.getSenderAddressFromCursor(cursor); if (senderAddress != null) { fragmentListener.showMoreFromSameSender(senderAddress); } break; } case R.id.delete: { MessageReference message = getMessageAtPosition(adapterPosition); onDelete(message); break; } case R.id.mark_as_read: { setFlag(adapterPosition, Flag.SEEN, true); break; } case R.id.mark_as_unread: { setFlag(adapterPosition, Flag.SEEN, false); break; } case R.id.flag: { setFlag(adapterPosition, Flag.FLAGGED, true); break; } case R.id.unflag: { setFlag(adapterPosition, Flag.FLAGGED, false); break; } // only if the account supports this case R.id.archive: { onArchive(getMessageAtPosition(adapterPosition)); break; } case R.id.spam: { onSpam(getMessageAtPosition(adapterPosition)); break; } case R.id.move: { onMove(getMessageAtPosition(adapterPosition)); break; } case R.id.copy: { onCopy(getMessageAtPosition(adapterPosition)); break; } // debug options case R.id.debug_delete_locally: { onDebugClearLocally(getMessageAtPosition(adapterPosition)); break; } } contextMenuUniqueId = 0; return true; } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; Cursor cursor = (Cursor) listView.getItemAtPosition(info.position); if (cursor == null) { return; } getActivity().getMenuInflater().inflate(R.menu.message_list_item_context, menu); menu.findItem(R.id.debug_delete_locally).setVisible(BuildConfig.DEBUG); contextMenuUniqueId = cursor.getLong(uniqueIdColumn); Account account = getAccountFromCursor(cursor); String subject = cursor.getString(SUBJECT_COLUMN); boolean read = (cursor.getInt(READ_COLUMN) == 1); boolean flagged = (cursor.getInt(FLAGGED_COLUMN) == 1); menu.setHeaderTitle(subject); if (selected.contains(contextMenuUniqueId)) { menu.findItem(R.id.select).setVisible(false); } else { menu.findItem(R.id.deselect).setVisible(false); } if (read) { menu.findItem(R.id.mark_as_read).setVisible(false); } else { menu.findItem(R.id.mark_as_unread).setVisible(false); } if (flagged) { menu.findItem(R.id.flag).setVisible(false); } else { menu.findItem(R.id.unflag).setVisible(false); } if (!messagingController.isCopyCapable(account)) { menu.findItem(R.id.copy).setVisible(false); } if (!messagingController.isMoveCapable(account)) { menu.findItem(R.id.move).setVisible(false); menu.findItem(R.id.archive).setVisible(false); menu.findItem(R.id.spam).setVisible(false); } if (!account.hasArchiveFolder()) { menu.findItem(R.id.archive).setVisible(false); } if (!account.hasSpamFolder()) { menu.findItem(R.id.spam).setVisible(false); } } public void onSwipeRightToLeft(final MotionEvent e1, final MotionEvent e2) { // Handle right-to-left as an un-select handleSwipe(e1, false); } public void onSwipeLeftToRight(final MotionEvent e1, final MotionEvent e2) { // Handle left-to-right as a select. handleSwipe(e1, true); } /** * Handle a select or unselect swipe event. * * @param downMotion * Event that started the swipe * @param selected * {@code true} if this was an attempt to select (i.e. left to right). */ private void handleSwipe(final MotionEvent downMotion, final boolean selected) { int x = (int) downMotion.getRawX(); int y = (int) downMotion.getRawY(); Rect headerRect = new Rect(); listView.getGlobalVisibleRect(headerRect); // Only handle swipes in the visible area of the message list if (headerRect.contains(x, y)) { int[] listPosition = new int[2]; listView.getLocationOnScreen(listPosition); int listX = x - listPosition[0]; int listY = y - listPosition[1]; int listViewPosition = listView.pointToPosition(listX, listY); toggleMessageSelect(listViewPosition); } } private int listViewToAdapterPosition(int position) { if (position >= 0 && position < adapter.getCount()) { return position; } return AdapterView.INVALID_POSITION; } private int adapterToListViewPosition(int position) { if (position >= 0 && position < adapter.getCount()) { return position; } return AdapterView.INVALID_POSITION; } class MessageListActivityListener extends ActivityListener { @Override public void remoteSearchFailed(String folder, final String err) { handler.post(new Runnable() { @Override public void run() { Activity activity = getActivity(); if (activity != null) { Toast.makeText(activity, R.string.remote_search_error, Toast.LENGTH_LONG).show(); } } }); } @Override public void remoteSearchStarted(String folder) { handler.progress(true); handler.updateFooter(context.getString(R.string.remote_search_sending_query)); } @Override public void enableProgressIndicator(boolean enable) { handler.progress(enable); } @Override public void remoteSearchFinished(String folder, int numResults, int maxResults, List<Message> extraResults) { handler.progress(false); handler.remoteSearchFinished(); extraSearchResults = extraResults; if (extraResults != null && extraResults.size() > 0) { handler.updateFooter(String.format(context.getString(R.string.load_more_messages_fmt), maxResults)); } else { handler.updateFooter(null); } fragmentListener.setMessageListProgress(Window.PROGRESS_END); } @Override public void remoteSearchServerQueryComplete(String folderName, int numResults, int maxResults) { handler.progress(true); if (maxResults != 0 && numResults > maxResults) { handler.updateFooter(context.getResources().getQuantityString(R.plurals.remote_search_downloading_limited, maxResults, maxResults, numResults)); } else { handler.updateFooter(context.getResources().getQuantityString(R.plurals.remote_search_downloading, numResults)); } fragmentListener.setMessageListProgress(Window.PROGRESS_START); } @Override public void informUserOfStatus() { handler.refreshTitle(); } @Override public void synchronizeMailboxStarted(Account account, String folder) { if (updateForMe(account, folder)) { handler.progress(true); handler.folderLoading(folder, true); } super.synchronizeMailboxStarted(account, folder); } @Override public void synchronizeMailboxFinished(Account account, String folder, int totalMessagesInMailbox, int numNewMessages) { if (updateForMe(account, folder)) { handler.progress(false); handler.folderLoading(folder, false); } super.synchronizeMailboxFinished(account, folder, totalMessagesInMailbox, numNewMessages); } @Override public void synchronizeMailboxFailed(Account account, String folder, String message) { if (updateForMe(account, folder)) { handler.progress(false); handler.folderLoading(folder, false); } super.synchronizeMailboxFailed(account, folder, message); } @Override public void folderStatusChanged(Account account, String folder, int unreadMessageCount) { if (isSingleAccountMode() && isSingleFolderMode() && MessageListFragment.this.account.equals(account) && folderName.equals(folder)) { MessageListFragment.this.unreadMessageCount = unreadMessageCount; } super.folderStatusChanged(account, folder, unreadMessageCount); } private boolean updateForMe(Account account, String folder) { if (account == null || folder == null) { return false; } if (!Utility.arrayContains(accountUuids, account.getUuid())) { return false; } List<String> folderNames = search.getFolderNames(); return (folderNames.isEmpty() || folderNames.contains(folder)); } } private View getFooterView(ViewGroup parent) { if (footerView == null) { footerView = layoutInflater.inflate(R.layout.message_list_item_footer, parent, false); FooterViewHolder holder = new FooterViewHolder(); holder.main = (TextView) footerView.findViewById(R.id.main_text); footerView.setTag(holder); } return footerView; } private void updateFooterView() { if (!search.isManualSearch() && currentFolder != null && account != null) { if (currentFolder.loading) { updateFooter(context.getString(R.string.status_loading_more)); } else if (!currentFolder.moreMessages) { updateFooter(null); } else { String message; if (!currentFolder.lastCheckFailed) { if (account.getDisplayCount() == 0) { message = context.getString(R.string.message_list_load_more_messages_action); } else { message = String.format(context.getString(R.string.load_more_messages_fmt), account.getDisplayCount()); } } else { message = context.getString(R.string.status_loading_more_failed); } updateFooter(message); } } else { updateFooter(null); } } public void updateFooter(final String text) { if (footerView == null) { return; } FooterViewHolder holder = (FooterViewHolder) footerView.getTag(); if (text != null) { holder.main.setText(text); holder.main.setVisibility(View.VISIBLE); } else { holder.main.setVisibility(View.GONE); } } static class FooterViewHolder { public TextView main; } /** * Set selection state for all messages. * * @param selected * If {@code true} all messages get selected. Otherwise, all messages get deselected and * action mode is finished. */ private void setSelectionState(boolean selected) { if (selected) { if (adapter.getCount() == 0) { // Nothing to do if there are no messages return; } selectedCount = 0; for (int i = 0, end = adapter.getCount(); i < end; i++) { Cursor cursor = (Cursor) adapter.getItem(i); long uniqueId = cursor.getLong(uniqueIdColumn); this.selected.add(uniqueId); if (showingThreadedList) { int threadCount = cursor.getInt(THREAD_COUNT_COLUMN); selectedCount += (threadCount > 1) ? threadCount : 1; } else { selectedCount++; } } if (actionMode == null) { startAndPrepareActionMode(); } computeBatchDirection(); updateActionModeTitle(); computeSelectAllVisibility(); } else { this.selected.clear(); selectedCount = 0; if (actionMode != null) { actionMode.finish(); actionMode = null; } } adapter.notifyDataSetChanged(); } private void toggleMessageSelect(int listViewPosition) { int adapterPosition = listViewToAdapterPosition(listViewPosition); if (adapterPosition == AdapterView.INVALID_POSITION) { return; } toggleMessageSelectWithAdapterPosition(adapterPosition); } void toggleMessageFlagWithAdapterPosition(int adapterPosition) { Cursor cursor = (Cursor) adapter.getItem(adapterPosition); boolean flagged = (cursor.getInt(FLAGGED_COLUMN) == 1); setFlag(adapterPosition,Flag.FLAGGED, !flagged); } void toggleMessageSelectWithAdapterPosition(int adapterPosition) { Cursor cursor = (Cursor) adapter.getItem(adapterPosition); long uniqueId = cursor.getLong(uniqueIdColumn); boolean selected = this.selected.contains(uniqueId); if (!selected) { this.selected.add(uniqueId); } else { this.selected.remove(uniqueId); } int selectedCountDelta = 1; if (showingThreadedList) { int threadCount = cursor.getInt(THREAD_COUNT_COLUMN); if (threadCount > 1) { selectedCountDelta = threadCount; } } if (actionMode != null) { if (selectedCount == selectedCountDelta && selected) { actionMode.finish(); actionMode = null; return; } } else { startAndPrepareActionMode(); } if (selected) { selectedCount -= selectedCountDelta; } else { selectedCount += selectedCountDelta; } computeBatchDirection(); updateActionModeTitle(); computeSelectAllVisibility(); adapter.notifyDataSetChanged(); } private void updateActionModeTitle() { actionMode.setTitle(String.format(getString(R.string.actionbar_selected), selectedCount)); } private void computeSelectAllVisibility() { actionModeCallback.showSelectAll(selected.size() != adapter.getCount()); } private void computeBatchDirection() { boolean isBatchFlag = false; boolean isBatchRead = false; for (int i = 0, end = adapter.getCount(); i < end; i++) { Cursor cursor = (Cursor) adapter.getItem(i); long uniqueId = cursor.getLong(uniqueIdColumn); if (selected.contains(uniqueId)) { boolean read = (cursor.getInt(READ_COLUMN) == 1); boolean flagged = (cursor.getInt(FLAGGED_COLUMN) == 1); if (!flagged) { isBatchFlag = true; } if (!read) { isBatchRead = true; } if (isBatchFlag && isBatchRead) { break; } } } actionModeCallback.showMarkAsRead(isBatchRead); actionModeCallback.showFlag(isBatchFlag); } private void setFlag(int adapterPosition, final Flag flag, final boolean newState) { if (adapterPosition == AdapterView.INVALID_POSITION) { return; } Cursor cursor = (Cursor) adapter.getItem(adapterPosition); Account account = preferences.getAccount(cursor.getString(ACCOUNT_UUID_COLUMN)); if (showingThreadedList && cursor.getInt(THREAD_COUNT_COLUMN) > 1) { long threadRootId = cursor.getLong(THREAD_ROOT_COLUMN); messagingController.setFlagForThreads(account, Collections.singletonList(threadRootId), flag, newState); } else { long id = cursor.getLong(ID_COLUMN); messagingController.setFlag(account, Collections.singletonList(id), flag, newState); } computeBatchDirection(); } private void setFlagForSelected(final Flag flag, final boolean newState) { if (selected.isEmpty()) { return; } Map<Account, List<Long>> messageMap = new HashMap<>(); Map<Account, List<Long>> threadMap = new HashMap<>(); Set<Account> accounts = new HashSet<>(); for (int position = 0, end = adapter.getCount(); position < end; position++) { Cursor cursor = (Cursor) adapter.getItem(position); long uniqueId = cursor.getLong(uniqueIdColumn); if (selected.contains(uniqueId)) { String uuid = cursor.getString(ACCOUNT_UUID_COLUMN); Account account = preferences.getAccount(uuid); accounts.add(account); if (showingThreadedList && cursor.getInt(THREAD_COUNT_COLUMN) > 1) { List<Long> threadRootIdList = threadMap.get(account); if (threadRootIdList == null) { threadRootIdList = new ArrayList<>(); threadMap.put(account, threadRootIdList); } threadRootIdList.add(cursor.getLong(THREAD_ROOT_COLUMN)); } else { List<Long> messageIdList = messageMap.get(account); if (messageIdList == null) { messageIdList = new ArrayList<>(); messageMap.put(account, messageIdList); } messageIdList.add(cursor.getLong(ID_COLUMN)); } } } for (Account account : accounts) { List<Long> messageIds = messageMap.get(account); List<Long> threadRootIds = threadMap.get(account); if (messageIds != null) { messagingController.setFlag(account, messageIds, flag, newState); } if (threadRootIds != null) { messagingController.setFlagForThreads(account, threadRootIds, flag, newState); } } computeBatchDirection(); } private void onMove(MessageReference message) { onMove(Collections.singletonList(message)); } /** * Display the message move activity. * * @param messages * Never {@code null}. */ private void onMove(List<MessageReference> messages) { if (!checkCopyOrMovePossible(messages, FolderOperation.MOVE)) { return; } String folderName; if (isThreadDisplay) { folderName = messages.get(0).getFolderName(); } else if (singleFolderMode) { folderName = currentFolder.folder.getName(); } else { folderName = null; } displayFolderChoice(ACTIVITY_CHOOSE_FOLDER_MOVE, folderName, messages.get(0).getAccountUuid(), null, messages); } private void onCopy(MessageReference message) { onCopy(Collections.singletonList(message)); } /** * Display the message copy activity. * * @param messages * Never {@code null}. */ private void onCopy(List<MessageReference> messages) { if (!checkCopyOrMovePossible(messages, FolderOperation.COPY)) { return; } String folderName; if (isThreadDisplay) { folderName = messages.get(0).getFolderName(); } else if (singleFolderMode) { folderName = currentFolder.folder.getName(); } else { folderName = null; } displayFolderChoice(ACTIVITY_CHOOSE_FOLDER_COPY, folderName, messages.get(0).getAccountUuid(), null, messages); } private void onDebugClearLocally(MessageReference message) { messagingController.debugClearMessagesLocally(Collections.singletonList(message)); } /** * Helper method to manage the invocation of {@link #startActivityForResult(Intent, int)} for a * folder operation ({@link ChooseFolder} activity), while saving a list of associated messages. * * @param requestCode * If {@code >= 0}, this code will be returned in {@code onActivityResult()} when the * activity exits. * * @see #startActivityForResult(Intent, int) */ private void displayFolderChoice(int requestCode, String sourceFolderName, String accountUuid, String lastSelectedFolderName, List<MessageReference> messages) { Intent intent = new Intent(getActivity(), ChooseFolder.class); intent.putExtra(ChooseFolder.EXTRA_ACCOUNT, accountUuid); intent.putExtra(ChooseFolder.EXTRA_SEL_FOLDER, lastSelectedFolderName); if (sourceFolderName == null) { intent.putExtra(ChooseFolder.EXTRA_SHOW_CURRENT, "yes"); } else { intent.putExtra(ChooseFolder.EXTRA_CUR_FOLDER, sourceFolderName); } // remember the selected messages for #onActivityResult activeMessages = messages; startActivityForResult(intent, requestCode); } private void onArchive(MessageReference message) { onArchive(Collections.singletonList(message)); } private void onArchive(final List<MessageReference> messages) { Map<Account, List<MessageReference>> messagesByAccount = groupMessagesByAccount(messages); for (Entry<Account, List<MessageReference>> entry : messagesByAccount.entrySet()) { Account account = entry.getKey(); String archiveFolder = account.getArchiveFolderName(); if (!K9.FOLDER_NONE.equals(archiveFolder)) { move(entry.getValue(), archiveFolder); } } } private Map<Account, List<MessageReference>> groupMessagesByAccount(final List<MessageReference> messages) { Map<Account, List<MessageReference>> messagesByAccount = new HashMap<>(); for (MessageReference message : messages) { Account account = preferences.getAccount(message.getAccountUuid()); List<MessageReference> msgList = messagesByAccount.get(account); if (msgList == null) { msgList = new ArrayList<>(); messagesByAccount.put(account, msgList); } msgList.add(message); } return messagesByAccount; } private void onSpam(MessageReference message) { onSpam(Collections.singletonList(message)); } /** * Move messages to the spam folder. * * @param messages * The messages to move to the spam folder. Never {@code null}. */ private void onSpam(List<MessageReference> messages) { if (K9.confirmSpam()) { // remember the message selection for #onCreateDialog(int) activeMessages = messages; showDialog(R.id.dialog_confirm_spam); } else { onSpamConfirmed(messages); } } private void onSpamConfirmed(List<MessageReference> messages) { Map<Account, List<MessageReference>> messagesByAccount = groupMessagesByAccount(messages); for (Entry<Account, List<MessageReference>> entry : messagesByAccount.entrySet()) { Account account = entry.getKey(); String spamFolder = account.getSpamFolderName(); if (!K9.FOLDER_NONE.equals(spamFolder)) { move(entry.getValue(), spamFolder); } } } private enum FolderOperation { COPY, MOVE } /** * Display a Toast message if any message isn't synchronized * * @param messages * The messages to copy or move. Never {@code null}. * @param operation * The type of operation to perform. Never {@code null}. * * @return {@code true}, if operation is possible. */ private boolean checkCopyOrMovePossible(final List<MessageReference> messages, final FolderOperation operation) { if (messages.isEmpty()) { return false; } boolean first = true; for (MessageReference message : messages) { if (first) { first = false; Account account = preferences.getAccount(message.getAccountUuid()); if ((operation == FolderOperation.MOVE && !messagingController.isMoveCapable(account)) || (operation == FolderOperation.COPY && !messagingController.isCopyCapable(account))) { return false; } } // message check if ((operation == FolderOperation.MOVE && !messagingController.isMoveCapable(message)) || (operation == FolderOperation.COPY && !messagingController.isCopyCapable(message))) { final Toast toast = Toast.makeText(getActivity(), R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); return false; } } return true; } /** * Copy the specified messages to the specified folder. * * @param messages * List of messages to copy. Never {@code null}. * @param destination * The name of the destination folder. Never {@code null}. */ private void copy(List<MessageReference> messages, final String destination) { copyOrMove(messages, destination, FolderOperation.COPY); } /** * Move the specified messages to the specified folder. * * @param messages * The list of messages to move. Never {@code null}. * @param destination * The name of the destination folder. Never {@code null}. */ private void move(List<MessageReference> messages, final String destination) { copyOrMove(messages, destination, FolderOperation.MOVE); } /** * The underlying implementation for {@link #copy(List, String)} and * {@link #move(List, String)}. This method was added mainly because those 2 * methods share common behavior. * * @param messages * The list of messages to copy or move. Never {@code null}. * @param destination * The name of the destination folder. Never {@code null} or {@link K9#FOLDER_NONE}. * @param operation * Specifies what operation to perform. Never {@code null}. */ private void copyOrMove(List<MessageReference> messages, final String destination, final FolderOperation operation) { Map<String, List<MessageReference>> folderMap = new HashMap<>(); for (MessageReference message : messages) { if ((operation == FolderOperation.MOVE && !messagingController.isMoveCapable(message)) || (operation == FolderOperation.COPY && !messagingController.isCopyCapable(message))) { Toast.makeText(getActivity(), R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG).show(); // XXX return meaningful error value? // message isn't synchronized return; } String folderName = message.getFolderName(); if (folderName.equals(destination)) { // Skip messages already in the destination folder continue; } List<MessageReference> outMessages = folderMap.get(folderName); if (outMessages == null) { outMessages = new ArrayList<>(); folderMap.put(folderName, outMessages); } outMessages.add(message); } for (Map.Entry<String, List<MessageReference>> entry : folderMap.entrySet()) { String folderName = entry.getKey(); List<MessageReference> outMessages = entry.getValue(); Account account = preferences.getAccount(outMessages.get(0).getAccountUuid()); if (operation == FolderOperation.MOVE) { if (showingThreadedList) { messagingController.moveMessagesInThread(account, folderName, outMessages, destination); } else { messagingController.moveMessages(account, folderName, outMessages, destination); } } else { if (showingThreadedList) { messagingController.copyMessagesInThread(account, folderName, outMessages, destination); } else { messagingController.copyMessages(account, folderName, outMessages, destination); } } } } class ActionModeCallback implements ActionMode.Callback { private MenuItem mSelectAll; private MenuItem mMarkAsRead; private MenuItem mMarkAsUnread; private MenuItem mFlag; private MenuItem mUnflag; @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { mSelectAll = menu.findItem(R.id.select_all); mMarkAsRead = menu.findItem(R.id.mark_as_read); mMarkAsUnread = menu.findItem(R.id.mark_as_unread); mFlag = menu.findItem(R.id.flag); mUnflag = menu.findItem(R.id.unflag); // we don't support cross account actions atm if (!singleAccountMode) { // show all menu.findItem(R.id.move).setVisible(true); menu.findItem(R.id.archive).setVisible(true); menu.findItem(R.id.spam).setVisible(true); menu.findItem(R.id.copy).setVisible(true); Set<String> accountUuids = getAccountUuidsForSelected(); for (String accountUuid : accountUuids) { Account account = preferences.getAccount(accountUuid); if (account != null) { setContextCapabilities(account, menu); } } } return true; } /** * Get the set of account UUIDs for the selected messages. */ private Set<String> getAccountUuidsForSelected() { int maxAccounts = accountUuids.length; Set<String> accountUuids = new HashSet<>(maxAccounts); for (int position = 0, end = adapter.getCount(); position < end; position++) { Cursor cursor = (Cursor) adapter.getItem(position); long uniqueId = cursor.getLong(uniqueIdColumn); if (selected.contains(uniqueId)) { String accountUuid = cursor.getString(ACCOUNT_UUID_COLUMN); accountUuids.add(accountUuid); if (accountUuids.size() == MessageListFragment.this.accountUuids.length) { break; } } } return accountUuids; } @Override public void onDestroyActionMode(ActionMode mode) { actionMode = null; mSelectAll = null; mMarkAsRead = null; mMarkAsUnread = null; mFlag = null; mUnflag = null; setSelectionState(false); } @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { MenuInflater inflater = mode.getMenuInflater(); inflater.inflate(R.menu.message_list_context, menu); // check capabilities setContextCapabilities(account, menu); return true; } /** * Disables menu options not supported by the account type or current "search view". * * @param account * The account to query for its capabilities. * @param menu * The menu to adapt. */ private void setContextCapabilities(Account account, Menu menu) { if (!singleAccountMode) { // We don't support cross-account copy/move operations right now menu.findItem(R.id.move).setVisible(false); menu.findItem(R.id.copy).setVisible(false); //TODO: we could support the archive and spam operations if all selected messages // belong to non-POP3 accounts menu.findItem(R.id.archive).setVisible(false); menu.findItem(R.id.spam).setVisible(false); } else { // hide unsupported if (!messagingController.isCopyCapable(account)) { menu.findItem(R.id.copy).setVisible(false); } if (!messagingController.isMoveCapable(account)) { menu.findItem(R.id.move).setVisible(false); menu.findItem(R.id.archive).setVisible(false); menu.findItem(R.id.spam).setVisible(false); } if (!account.hasArchiveFolder()) { menu.findItem(R.id.archive).setVisible(false); } if (!account.hasSpamFolder()) { menu.findItem(R.id.spam).setVisible(false); } } } public void showSelectAll(boolean show) { if (actionMode != null) { mSelectAll.setVisible(show); } } public void showMarkAsRead(boolean show) { if (actionMode != null) { mMarkAsRead.setVisible(show); mMarkAsUnread.setVisible(!show); } } public void showFlag(boolean show) { if (actionMode != null) { mFlag.setVisible(show); mUnflag.setVisible(!show); } } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { /* * In the following we assume that we can't move or copy * mails to the same folder. Also that spam isn't available if we are * in the spam folder,same for archive. * * This is the case currently so safe assumption. */ switch (item.getItemId()) { case R.id.delete: { List<MessageReference> messages = getCheckedMessages(); onDelete(messages); selectedCount = 0; break; } case R.id.mark_as_read: { setFlagForSelected(Flag.SEEN, true); break; } case R.id.mark_as_unread: { setFlagForSelected(Flag.SEEN, false); break; } case R.id.flag: { setFlagForSelected(Flag.FLAGGED, true); break; } case R.id.unflag: { setFlagForSelected(Flag.FLAGGED, false); break; } case R.id.select_all: { selectAll(); break; } // only if the account supports this case R.id.archive: { onArchive(getCheckedMessages()); selectedCount = 0; break; } case R.id.spam: { onSpam(getCheckedMessages()); selectedCount = 0; break; } case R.id.move: { onMove(getCheckedMessages()); selectedCount = 0; break; } case R.id.copy: { onCopy(getCheckedMessages()); selectedCount = 0; break; } } if (selectedCount == 0) { actionMode.finish(); } return true; } } @Override public void doPositiveClick(int dialogId) { switch (dialogId) { case R.id.dialog_confirm_spam: { onSpamConfirmed(activeMessages); // No further need for this reference activeMessages = null; break; } case R.id.dialog_confirm_delete: { onDeleteConfirmed(activeMessages); activeMessage = null; break; } case R.id.dialog_confirm_mark_all_as_read: { markAllAsRead(); break; } } } @Override public void doNegativeClick(int dialogId) { switch (dialogId) { case R.id.dialog_confirm_spam: case R.id.dialog_confirm_delete: { // No further need for this reference activeMessages = null; break; } } } @Override public void dialogCancelled(int dialogId) { doNegativeClick(dialogId); } public void checkMail() { if (isSingleAccountMode() && isSingleFolderMode()) { messagingController.synchronizeMailbox(account, folderName, activityListener, null); messagingController.sendPendingMessages(account, activityListener); } else if (allAccounts) { messagingController.checkMail(context, null, true, true, activityListener); } else { for (String accountUuid : accountUuids) { Account account = preferences.getAccount(accountUuid); messagingController.checkMail(context, account, true, true, activityListener); } } } /** * We need to do some special clean up when leaving a remote search result screen. If no * remote search is in progress, this method does nothing special. */ @Override public void onStop() { // If we represent a remote search, then kill that before going back. if (isRemoteSearch() && remoteSearchFuture != null) { try { Timber.i("Remote search in progress, attempting to abort..."); // Canceling the future stops any message fetches in progress. final boolean cancelSuccess = remoteSearchFuture.cancel(true); // mayInterruptIfRunning = true if (!cancelSuccess) { Timber.e("Could not cancel remote search future."); } // Closing the folder will kill off the connection if we're mid-search. final Account searchAccount = account; final Folder remoteFolder = currentFolder.folder; remoteFolder.close(); // Send a remoteSearchFinished() message for good measure. activityListener .remoteSearchFinished(currentFolder.name, 0, searchAccount.getRemoteSearchNumResults(), null); } catch (Exception e) { // Since the user is going back, log and squash any exceptions. Timber.e(e, "Could not abort remote search before going back"); } } super.onStop(); } public void selectAll() { setSelectionState(true); } public void onMoveUp() { int currentPosition = listView.getSelectedItemPosition(); if (currentPosition == AdapterView.INVALID_POSITION || listView.isInTouchMode()) { currentPosition = listView.getFirstVisiblePosition(); } if (currentPosition > 0) { listView.setSelection(currentPosition - 1); } } public void onMoveDown() { int currentPosition = listView.getSelectedItemPosition(); if (currentPosition == AdapterView.INVALID_POSITION || listView.isInTouchMode()) { currentPosition = listView.getFirstVisiblePosition(); } if (currentPosition < listView.getCount()) { listView.setSelection(currentPosition + 1); } } public boolean openPrevious(MessageReference messageReference) { int position = getPosition(messageReference); if (position <= 0) { return false; } openMessageAtPosition(position - 1); return true; } public boolean openNext(MessageReference messageReference) { int position = getPosition(messageReference); if (position < 0 || position == adapter.getCount() - 1) { return false; } openMessageAtPosition(position + 1); return true; } public boolean isFirst(MessageReference messageReference) { return adapter.isEmpty() || messageReference.equals(getReferenceForPosition(0)); } public boolean isLast(MessageReference messageReference) { return adapter.isEmpty() || messageReference.equals(getReferenceForPosition(adapter.getCount() - 1)); } private MessageReference getReferenceForPosition(int position) { Cursor cursor = (Cursor) adapter.getItem(position); String accountUuid = cursor.getString(ACCOUNT_UUID_COLUMN); String folderName = cursor.getString(FOLDER_NAME_COLUMN); String messageUid = cursor.getString(UID_COLUMN); return new MessageReference(accountUuid, folderName, messageUid, null); } private void openMessageAtPosition(int position) { // Scroll message into view if necessary int listViewPosition = adapterToListViewPosition(position); if (listViewPosition != AdapterView.INVALID_POSITION && (listViewPosition < listView.getFirstVisiblePosition() || listViewPosition > listView.getLastVisiblePosition())) { listView.setSelection(listViewPosition); } MessageReference ref = getReferenceForPosition(position); // For some reason the listView.setSelection() above won't do anything when we call // onOpenMessage() (and consequently adapter.notifyDataSetChanged()) right away. So we // defer the call using MessageListHandler. handler.openMessage(ref); } private int getPosition(MessageReference messageReference) { for (int i = 0, len = adapter.getCount(); i < len; i++) { Cursor cursor = (Cursor) adapter.getItem(i); String accountUuid = cursor.getString(ACCOUNT_UUID_COLUMN); String folderName = cursor.getString(FOLDER_NAME_COLUMN); String uid = cursor.getString(UID_COLUMN); if (accountUuid.equals(messageReference.getAccountUuid()) && folderName.equals(messageReference.getFolderName()) && uid.equals(messageReference.getUid())) { return i; } } return -1; } public interface MessageListFragmentListener { void enableActionBarProgress(boolean enable); void setMessageListProgress(int level); void showThread(Account account, String folderName, long rootId); void showMoreFromSameSender(String senderAddress); void onResendMessage(MessageReference message); void onForward(MessageReference message); void onReply(MessageReference message); void onReplyAll(MessageReference message); void openMessage(MessageReference messageReference); void setMessageListTitle(String title); void setMessageListSubTitle(String subTitle); void setUnreadCount(int unread); void onCompose(Account account); boolean startSearch(Account account, String folderName); void remoteSearchStarted(); void goBack(); void updateMenu(); } public void onReverseSort() { changeSort(sortType); } private MessageReference getSelectedMessage() { int listViewPosition = listView.getSelectedItemPosition(); int adapterPosition = listViewToAdapterPosition(listViewPosition); return getMessageAtPosition(adapterPosition); } private int getAdapterPositionForSelectedMessage() { int listViewPosition = listView.getSelectedItemPosition(); return listViewToAdapterPosition(listViewPosition); } private int getPositionForUniqueId(long uniqueId) { for (int position = 0, end = adapter.getCount(); position < end; position++) { Cursor cursor = (Cursor) adapter.getItem(position); if (cursor.getLong(uniqueIdColumn) == uniqueId) { return position; } } return AdapterView.INVALID_POSITION; } private MessageReference getMessageAtPosition(int adapterPosition) { if (adapterPosition == AdapterView.INVALID_POSITION) { return null; } Cursor cursor = (Cursor) adapter.getItem(adapterPosition); String accountUuid = cursor.getString(ACCOUNT_UUID_COLUMN); String folderName = cursor.getString(FOLDER_NAME_COLUMN); String messageUid = cursor.getString(UID_COLUMN); return new MessageReference(accountUuid, folderName, messageUid, null); } private List<MessageReference> getCheckedMessages() { List<MessageReference> messages = new ArrayList<>(selected.size()); for (int position = 0, end = adapter.getCount(); position < end; position++) { Cursor cursor = (Cursor) adapter.getItem(position); long uniqueId = cursor.getLong(uniqueIdColumn); if (selected.contains(uniqueId)) { MessageReference message = getMessageAtPosition(position); if (message != null) { messages.add(message); } } } return messages; } public void onDelete() { MessageReference message = getSelectedMessage(); if (message != null) { onDelete(Collections.singletonList(message)); } } public void toggleMessageSelect() { toggleMessageSelect(listView.getSelectedItemPosition()); } public void onToggleFlagged() { onToggleFlag(Flag.FLAGGED, FLAGGED_COLUMN); } public void onToggleRead() { onToggleFlag(Flag.SEEN, READ_COLUMN); } private void onToggleFlag(Flag flag, int flagColumn) { int adapterPosition = getAdapterPositionForSelectedMessage(); if (adapterPosition == ListView.INVALID_POSITION) { return; } Cursor cursor = (Cursor) adapter.getItem(adapterPosition); boolean flagState = (cursor.getInt(flagColumn) == 1); setFlag(adapterPosition, flag, !flagState); } public void onMove() { MessageReference message = getSelectedMessage(); if (message != null) { onMove(message); } } public void onArchive() { MessageReference message = getSelectedMessage(); if (message != null) { onArchive(message); } } public void onCopy() { MessageReference message = getSelectedMessage(); if (message != null) { onCopy(message); } } public boolean isOutbox() { return (folderName != null && folderName.equals(account.getOutboxFolderName())); } public boolean isRemoteFolder() { if (search.isManualSearch() || isOutbox()) { return false; } if (!messagingController.isMoveCapable(account)) { // For POP3 accounts only the Inbox is a remote folder. return (folderName != null && folderName.equals(account.getInboxFolderName())); } return true; } public boolean isManualSearch() { return search.isManualSearch(); } public boolean isAccountExpungeCapable() { try { return (account != null && account.getRemoteStore().isExpungeCapable()); } catch (Exception e) { return false; } } public void onRemoteSearch() { // Remote search is useless without the network. if (hasConnectivity) { onRemoteSearchRequested(); } else { Toast.makeText(getActivity(), getText(R.string.remote_search_unavailable_no_network), Toast.LENGTH_SHORT).show(); } } public boolean isRemoteSearch() { return remoteSearchPerformed; } public boolean isRemoteSearchAllowed() { if (!search.isManualSearch() || remoteSearchPerformed || !singleFolderMode) { return false; } boolean allowRemoteSearch = false; final Account searchAccount = account; if (searchAccount != null) { allowRemoteSearch = searchAccount.allowRemoteSearch(); } return allowRemoteSearch; } public boolean onSearchRequested() { String folderName = (currentFolder != null) ? currentFolder.name : null; return fragmentListener.startSearch(account, folderName); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { String accountUuid = accountUuids[id]; Account account = preferences.getAccount(accountUuid); String threadId = getThreadId(search); Uri uri; String[] projection; boolean needConditions; if (threadId != null) { uri = Uri.withAppendedPath(EmailProvider.CONTENT_URI, "account/" + accountUuid + "/thread/" + threadId); projection = PROJECTION; needConditions = false; } else if (showingThreadedList) { uri = Uri.withAppendedPath(EmailProvider.CONTENT_URI, "account/" + accountUuid + "/messages/threaded"); projection = THREADED_PROJECTION; needConditions = true; } else { uri = Uri.withAppendedPath(EmailProvider.CONTENT_URI, "account/" + accountUuid + "/messages"); projection = PROJECTION; needConditions = true; } StringBuilder query = new StringBuilder(); List<String> queryArgs = new ArrayList<>(); if (needConditions) { boolean selectActive = activeMessage != null && activeMessage.getAccountUuid().equals(accountUuid); if (selectActive) { query.append("(" + MessageColumns.UID + " = ? AND " + SpecialColumns.FOLDER_NAME + " = ?) OR ("); queryArgs.add(activeMessage.getUid()); queryArgs.add(activeMessage.getFolderName()); } SqlQueryBuilder.buildWhereClause(account, search.getConditions(), query, queryArgs); if (selectActive) { query.append(')'); } } String selection = query.toString(); String[] selectionArgs = queryArgs.toArray(new String[0]); String sortOrder = buildSortOrder(); return new CursorLoader(getActivity(), uri, projection, selection, selectionArgs, sortOrder); } private String getThreadId(LocalSearch search) { for (ConditionsTreeNode node : search.getLeafSet()) { SearchCondition condition = node.mCondition; if (condition.field == SearchField.THREAD_ID) { return condition.value; } } return null; } private String buildSortOrder() { String sortColumn; switch (sortType) { case SORT_ARRIVAL: { sortColumn = MessageColumns.INTERNAL_DATE; break; } case SORT_ATTACHMENT: { sortColumn = "(" + MessageColumns.ATTACHMENT_COUNT + " < 1)"; break; } case SORT_FLAGGED: { sortColumn = "(" + MessageColumns.FLAGGED + " != 1)"; break; } case SORT_SENDER: { //FIXME sortColumn = MessageColumns.SENDER_LIST; break; } case SORT_SUBJECT: { sortColumn = MessageColumns.SUBJECT + " COLLATE NOCASE"; break; } case SORT_UNREAD: { sortColumn = MessageColumns.READ; break; } case SORT_DATE: default: { sortColumn = MessageColumns.DATE; } } String sortDirection = (sortAscending) ? " ASC" : " DESC"; String secondarySort; if (sortType == SortType.SORT_DATE || sortType == SortType.SORT_ARRIVAL) { secondarySort = ""; } else { secondarySort = MessageColumns.DATE + ((sortDateAscending) ? " ASC, " : " DESC, "); } return sortColumn + sortDirection + ", " + secondarySort + MessageColumns.ID + " DESC"; } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (isThreadDisplay && data.getCount() == 0) { handler.goBack(); return; } swipeRefreshLayout.setRefreshing(false); swipeRefreshLayout.setEnabled(isPullToRefreshAllowed()); final int loaderId = loader.getId(); cursors[loaderId] = data; cursorValid[loaderId] = true; Cursor cursor; if (cursors.length > 1) { cursor = new MergeCursorWithUniqueId(cursors, getComparator()); uniqueIdColumn = cursor.getColumnIndex("_id"); } else { cursor = data; uniqueIdColumn = ID_COLUMN; } if (isThreadDisplay) { if (cursor.moveToFirst()) { title = cursor.getString(SUBJECT_COLUMN); if (!TextUtils.isEmpty(title)) { title = Utility.stripSubject(title); } if (TextUtils.isEmpty(title)) { title = getString(R.string.general_no_subject); } updateTitle(); } else { //TODO: empty thread view -> return to full message list } } cleanupSelected(cursor); updateContextMenu(cursor); adapter.swapCursor(cursor); resetActionMode(); computeBatchDirection(); if (isLoadFinished()) { if (savedListState != null) { handler.restoreListPosition(); } fragmentListener.updateMenu(); } } private void updateMoreMessagesOfCurrentFolder() { if (folderName != null) { try { LocalFolder folder = MlfUtils.getOpenFolder(folderName, account); currentFolder.setMoreMessagesFromFolder(folder); } catch (MessagingException e) { throw new RuntimeException(e); } } } public boolean isLoadFinished() { if (cursorValid == null) { return false; } for (boolean cursorValid : this.cursorValid) { if (!cursorValid) { return false; } } return true; } /** * Close the context menu when the message it was opened for is no longer in the message list. */ private void updateContextMenu(Cursor cursor) { if (contextMenuUniqueId == 0) { return; } for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { long uniqueId = cursor.getLong(uniqueIdColumn); if (uniqueId == contextMenuUniqueId) { return; } } contextMenuUniqueId = 0; Activity activity = getActivity(); if (activity != null) { activity.closeContextMenu(); } } private void cleanupSelected(Cursor cursor) { if (selected.isEmpty()) { return; } Set<Long> selected = new HashSet<>(); for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { long uniqueId = cursor.getLong(uniqueIdColumn); if (this.selected.contains(uniqueId)) { selected.add(uniqueId); } } this.selected = selected; } /** * Starts or finishes the action mode when necessary. */ private void resetActionMode() { if (selected.isEmpty()) { if (actionMode != null) { actionMode.finish(); } return; } if (actionMode == null) { startAndPrepareActionMode(); } recalculateSelectionCount(); updateActionModeTitle(); } private void startAndPrepareActionMode() { actionMode = getActivity().startActionMode(actionModeCallback); actionMode.invalidate(); } /** * Recalculates the selection count. * * <p> * For non-threaded lists this is simply the number of visibly selected messages. If threaded * view is enabled this method counts the number of messages in the selected threads. * </p> */ private void recalculateSelectionCount() { if (!showingThreadedList) { selectedCount = selected.size(); return; } selectedCount = 0; for (int i = 0, end = adapter.getCount(); i < end; i++) { Cursor cursor = (Cursor) adapter.getItem(i); long uniqueId = cursor.getLong(uniqueIdColumn); if (selected.contains(uniqueId)) { int threadCount = cursor.getInt(THREAD_COUNT_COLUMN); selectedCount += (threadCount > 1) ? threadCount : 1; } } } @Override public void onLoaderReset(Loader<Cursor> loader) { selected.clear(); adapter.swapCursor(null); } Account getAccountFromCursor(Cursor cursor) { String accountUuid = cursor.getString(ACCOUNT_UUID_COLUMN); return preferences.getAccount(accountUuid); } void remoteSearchFinished() { remoteSearchFuture = null; } /** * Mark a message as 'active'. * * <p> * The active message is the one currently displayed in the message view portion of the split * view. * </p> * * @param messageReference * {@code null} to not mark any message as being 'active'. */ public void setActiveMessage(MessageReference messageReference) { activeMessage = messageReference; // Reload message list with modified query that always includes the active message if (isAdded()) { restartLoader(); } // Redraw list immediately if (adapter != null) { adapter.notifyDataSetChanged(); } } public boolean isSingleAccountMode() { return singleAccountMode; } public boolean isSingleFolderMode() { return singleFolderMode; } public boolean isInitialized() { return initialized; } public boolean isMarkAllAsReadSupported() { return (isSingleAccountMode() && isSingleFolderMode()); } public void confirmMarkAllAsRead() { if (K9.confirmMarkAllRead()) { showDialog(R.id.dialog_confirm_mark_all_as_read); } else { markAllAsRead(); } } private void markAllAsRead() { if (isMarkAllAsReadSupported()) { messagingController.markAllMessagesRead(account, folderName); } } public boolean isCheckMailSupported() { return (allAccounts || !isSingleAccountMode() || !isSingleFolderMode() || isRemoteFolder()); } private boolean isCheckMailAllowed() { return (!isManualSearch() && isCheckMailSupported()); } private boolean isPullToRefreshAllowed() { return (isRemoteSearchAllowed() || isCheckMailAllowed()); } LayoutInflater getK9LayoutInflater() { return layoutInflater; } }
package com.intellij.injected.editor; import com.intellij.ide.DataManager; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.RangeMarker; import com.intellij.openapi.editor.event.DocumentListener; import com.intellij.openapi.editor.ex.*; import com.intellij.openapi.editor.impl.DocumentImpl; import com.intellij.openapi.editor.markup.MarkupModel; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.UserDataHolderBase; import com.intellij.openapi.util.ProperTextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiLanguageInjectionHost; import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil; import com.intellij.util.text.CharArrayUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.beans.PropertyChangeListener; import java.util.Arrays; import java.util.List; /** * @author Alexey */ public class DocumentWindowImpl extends UserDataHolderBase implements Disposable, DocumentWindow, DocumentEx { private static final Logger LOG = Logger.getInstance("com.intellij.openapi.editor.impl.injected.DocumentRangee"); private final DocumentEx myDelegate; //sorted by startOffset private final RangeMarker[] myRelevantRangesInHostDocument; private final boolean myOneLine; private final String[] myPrefixes; private final String[] mySuffixes; private final int myPrefixLineCount; private final int mySuffixLineCount; public DocumentWindowImpl(@NotNull DocumentEx delegate, boolean oneLine, List<PsiLanguageInjectionHost.Shred> shreds) { myDelegate = delegate; myOneLine = oneLine; myPrefixes = new String[shreds.size()]; mySuffixes = new String[shreds.size()]; myRelevantRangesInHostDocument = new RangeMarker[shreds.size()]; for (int i = 0; i < shreds.size(); i++) { PsiLanguageInjectionHost.Shred shred = shreds.get(i); myPrefixes[i] = shred.prefix; mySuffixes[i] = shred.suffix; myRelevantRangesInHostDocument[i] = shred.getHostRangeMarker(); if (i != 0) { assert myRelevantRangesInHostDocument[i].getStartOffset() >= myRelevantRangesInHostDocument[i - 1].getStartOffset() : Arrays.asList(myRelevantRangesInHostDocument); } } myPrefixLineCount = Math.max(1, 1 + StringUtil.countNewLines(myPrefixes[0])); mySuffixLineCount = Math.max(1, 1 + StringUtil.countNewLines(mySuffixes[mySuffixes.length - 1])); } public int getLineCount() { return 1 + StringUtil.countNewLines(getText()); } public int getLineStartOffset(int line) { assert line >= 0 : line; return new DocumentImpl(getText()).getLineStartOffset(line); } public int getLineEndOffset(int line) { if (line==0 && myPrefixes[0].length()==0) return getTextLength(); return new DocumentImpl(getText()).getLineEndOffset(line); } public String getText() { StringBuilder text = new StringBuilder(); String hostText = myDelegate.getText(); for (int i = 0; i < myRelevantRangesInHostDocument.length; i++) { RangeMarker hostRange = myRelevantRangesInHostDocument[i]; if (hostRange.isValid()) { text.append(myPrefixes[i]); text.append(hostText, hostRange.getStartOffset(), hostRange.getEndOffset()); text.append(mySuffixes[i]); } } return text.toString(); } public CharSequence getCharsSequence() { return getText(); } public char[] getChars() { return CharArrayUtil.fromSequence(getText()); } public int getTextLength() { int length = 0; for (int i = 0; i < myRelevantRangesInHostDocument.length; i++) { RangeMarker hostRange = myRelevantRangesInHostDocument[i]; length += myPrefixes[i].length(); length += hostRange.getEndOffset() - hostRange.getStartOffset(); length += mySuffixes[i].length(); } return length; } public int getLineNumber(int offset) { int lineNumber = 0; String hostText = myDelegate.getText(); for (int i = 0; i < myRelevantRangesInHostDocument.length; i++) { String prefix = myPrefixes[i]; String suffix = mySuffixes[i]; lineNumber += StringUtil.getLineBreakCount(prefix.substring(0, Math.min(offset, prefix.length()))); if (offset < prefix.length()) { return lineNumber; } offset -= prefix.length(); RangeMarker currentRange = myRelevantRangesInHostDocument[i]; int rangeLength = currentRange.getEndOffset() - currentRange.getStartOffset(); String rangeText = hostText.substring(currentRange.getStartOffset(), currentRange.getEndOffset()); lineNumber += StringUtil.getLineBreakCount(rangeText.substring(0, Math.min(offset, rangeLength))); if (offset < rangeLength) { return lineNumber; } offset -= rangeLength; lineNumber += StringUtil.getLineBreakCount(suffix.substring(0, Math.min(offset, suffix.length()))); if (offset < suffix.length()) { return lineNumber; } offset -= suffix.length(); } lineNumber = getLineCount() - 1; return lineNumber < 0 ? 0 : lineNumber; } public TextRange getHostRange(int hostOffset) { for (RangeMarker currentRange : myRelevantRangesInHostDocument) { TextRange textRange = InjectedLanguageUtil.toTextRange(currentRange); if (textRange.grown(1).contains(hostOffset)) return textRange; } return null; } public void insertString(final int offset, CharSequence s) { LOG.assertTrue(offset >= myPrefixes[0].length()); LOG.assertTrue(offset <= getTextLength() - mySuffixes[mySuffixes.length-1].length()); if (isOneLine()) { s = StringUtil.replace(s.toString(), "\n", ""); } myDelegate.insertString(injectedToHost(offset), s); } public void deleteString(final int startOffset, final int endOffset) { assert intersectWithEditable(new TextRange(startOffset, startOffset)) != null; assert intersectWithEditable(new TextRange(endOffset, endOffset)) != null; //todo handle delete that span ranges myDelegate.deleteString(injectedToHost(startOffset), injectedToHost(endOffset)); } public void replaceString(final int startOffset, final int endOffset, CharSequence s) { if (intersectWithEditable(new TextRange(startOffset, startOffset)) == null || intersectWithEditable(new TextRange(endOffset, endOffset)) == null) { LOG.assertTrue(s.equals(getText().substring(startOffset, endOffset))); return; } if (isOneLine()) { s = StringUtil.replace(s.toString(), "\n", ""); } //LOG.assertTrue(startOffset >= myPrefix.length()); //LOG.assertTrue(startOffset <= getTextLength() - mySuffix.length()); //LOG.assertTrue(endOffset >= myPrefix.length()); //LOG.assertTrue(endOffset <= getTextLength() - mySuffix.length()); //todo handle delete that span ranges myDelegate.replaceString(injectedToHost(startOffset), injectedToHost(endOffset), s); } public boolean isWritable() { return myDelegate.isWritable(); } public long getModificationStamp() { return myDelegate.getModificationStamp(); } public void fireReadOnlyModificationAttempt() { myDelegate.fireReadOnlyModificationAttempt(); } public void addDocumentListener(final DocumentListener listener) { myDelegate.addDocumentListener(listener); } public void addDocumentListener(DocumentListener listener, Disposable parentDisposable) { myDelegate.addDocumentListener(listener, parentDisposable); } public void removeDocumentListener(final DocumentListener listener) { myDelegate.removeDocumentListener(listener); } public RangeMarker createRangeMarker(final int startOffset, final int endOffset) { assert startOffset <= endOffset; TextRange hostRange = injectedToHost(new ProperTextRange(startOffset, endOffset)); RangeMarker hostMarker = myDelegate.createRangeMarker(hostRange); return new RangeMarkerWindow(this, (RangeMarkerEx)hostMarker); } public RangeMarker createRangeMarker(final int startOffset, final int endOffset, final boolean surviveOnExternalChange) { if (!surviveOnExternalChange) { return createRangeMarker(startOffset, endOffset); } TextRange hostRange = injectedToHost(new ProperTextRange(startOffset, endOffset)); //todo persistent? return myDelegate.createRangeMarker(hostRange.getStartOffset(), hostRange.getEndOffset(), surviveOnExternalChange); } public MarkupModel getMarkupModel() { //noinspection deprecation return new MarkupModelWindow((MarkupModelEx)myDelegate.getMarkupModel(), this); } @NotNull public MarkupModel getMarkupModel(final Project project) { return new MarkupModelWindow((MarkupModelEx)myDelegate.getMarkupModel(project), this); } public void addPropertyChangeListener(final PropertyChangeListener listener) { myDelegate.addPropertyChangeListener(listener); } public void removePropertyChangeListener(final PropertyChangeListener listener) { myDelegate.removePropertyChangeListener(listener); } public void setReadOnly(final boolean isReadOnly) { myDelegate.setReadOnly(isReadOnly); } public RangeMarker createGuardedBlock(final int startOffset, final int endOffset) { TextRange hostRange = injectedToHost(new ProperTextRange(startOffset, endOffset)); return myDelegate.createGuardedBlock(hostRange.getStartOffset(), hostRange.getEndOffset()); } public void removeGuardedBlock(final RangeMarker block) { myDelegate.removeGuardedBlock(block); } public RangeMarker getOffsetGuard(final int offset) { return myDelegate.getOffsetGuard(injectedToHost(offset)); } public RangeMarker getRangeGuard(final int startOffset, final int endOffset) { TextRange hostRange = injectedToHost(new ProperTextRange(startOffset, endOffset)); return myDelegate.getRangeGuard(hostRange.getStartOffset(), hostRange.getEndOffset()); } public void startGuardedBlockChecking() { myDelegate.startGuardedBlockChecking(); } public void stopGuardedBlockChecking() { myDelegate.stopGuardedBlockChecking(); } public void setCyclicBufferSize(final int bufferSize) { myDelegate.setCyclicBufferSize(bufferSize); } public void setText(CharSequence text) { LOG.assertTrue(text.toString().startsWith(myPrefixes[0])); LOG.assertTrue(text.toString().endsWith(mySuffixes[mySuffixes.length-1])); if (isOneLine()) { text = StringUtil.replace(text.toString(), "\n", ""); } String[] changes = calculateMinEditSequence(text.toString()); assert changes.length == myRelevantRangesInHostDocument.length; for (int i = 0; i < changes.length; i++) { String change = changes[i]; RangeMarker hostRange = myRelevantRangesInHostDocument[i]; myDelegate.replaceString(hostRange.getStartOffset(), hostRange.getEndOffset(), change); } } @NotNull public RangeMarker[] getHostRanges() { return myRelevantRangesInHostDocument; } public RangeMarker createRangeMarker(final TextRange textRange) { TextRange hostRange = injectedToHost(new ProperTextRange(textRange)); RangeMarker hostMarker = myDelegate.createRangeMarker(hostRange); return new RangeMarkerWindow(this, (RangeMarkerEx)hostMarker); } public void stripTrailingSpaces(final boolean inChangedLinesOnly) { myDelegate.stripTrailingSpaces(inChangedLinesOnly); } public void setStripTrailingSpacesEnabled(final boolean isEnabled) { myDelegate.setStripTrailingSpacesEnabled(isEnabled); } public int getLineSeparatorLength(final int line) { return myDelegate.getLineSeparatorLength(injectedToHostLine(line)); } public LineIterator createLineIterator() { return myDelegate.createLineIterator(); } public void setModificationStamp(final long modificationStamp) { myDelegate.setModificationStamp(modificationStamp); } public void addEditReadOnlyListener(final EditReadOnlyListener listener) { myDelegate.addEditReadOnlyListener(listener); } public void removeEditReadOnlyListener(final EditReadOnlyListener listener) { myDelegate.removeEditReadOnlyListener(listener); } public void replaceText(final CharSequence chars, final long newModificationStamp) { setText(chars); myDelegate.setModificationStamp(newModificationStamp); } public int getListenersCount() { return myDelegate.getListenersCount(); } public void suppressGuardedExceptions() { myDelegate.suppressGuardedExceptions(); } public void unSuppressGuardedExceptions() { myDelegate.unSuppressGuardedExceptions(); } public boolean isInEventsHandling() { return myDelegate.isInEventsHandling(); } public void clearLineModificationFlags() { } public void removeRangeMarker(RangeMarkerEx rangeMarker) { myDelegate.removeRangeMarker(rangeMarker); //todo } public void addRangeMarker(RangeMarkerEx rangeMarker) { myDelegate.addRangeMarker(rangeMarker); //todo } public boolean isInBulkUpdate() { return false; } public void setInBulkUpdate(boolean value) { } @NotNull public DocumentEx getDelegate() { return myDelegate; } //todo use escaper? public int hostToInjected(int hostOffset) { if (hostOffset < myRelevantRangesInHostDocument[0].getStartOffset()) return myPrefixes[0].length(); int offset = 0; for (int i = 0; i < myRelevantRangesInHostDocument.length; i++) { offset += myPrefixes[i].length(); RangeMarker currentRange = myRelevantRangesInHostDocument[i]; RangeMarker nextRange = i==myRelevantRangesInHostDocument.length-1 ? null : myRelevantRangesInHostDocument[i+1]; if (nextRange == null || hostOffset < nextRange.getStartOffset()) { if (hostOffset >= currentRange.getEndOffset()) hostOffset = currentRange.getEndOffset(); return offset + hostOffset - currentRange.getStartOffset(); } offset += currentRange.getEndOffset() - currentRange.getStartOffset(); offset += mySuffixes[i].length(); } return getTextLength() - mySuffixes[mySuffixes.length-1].length(); } public int injectedToHost(int offset) { int offsetInLeftFragment = injectedToHost(offset, true); int offsetInRightFragment = injectedToHost(offset, false); if (offsetInLeftFragment == offsetInRightFragment) return offsetInLeftFragment; // heuristics: return offset closest to caret Editor editor = PlatformDataKeys.EDITOR.getData(DataManager.getInstance().getDataContext()); if (editor instanceof EditorWindow) editor = ((EditorWindow)editor).getDelegate(); if (editor != null) { int caret = editor.getCaretModel().getOffset(); return Math.abs(caret - offsetInLeftFragment) < Math.abs(caret - offsetInRightFragment) ? offsetInLeftFragment : offsetInRightFragment; } return offsetInLeftFragment; } private int injectedToHost(int offset, boolean preferLeftFragment) { if (offset < myPrefixes[0].length()) return myRelevantRangesInHostDocument[0].getStartOffset(); int prevEnd = 0; for (int i = 0; i < myRelevantRangesInHostDocument.length; i++) { RangeMarker currentRange = myRelevantRangesInHostDocument[i]; offset -= myPrefixes[i].length(); int length = currentRange.getEndOffset() - currentRange.getStartOffset(); if (offset < 0) { return preferLeftFragment ? prevEnd : currentRange.getStartOffset() - 1; } else if (offset == 0) { return preferLeftFragment && i != 0 ? prevEnd : currentRange.getStartOffset(); } else if (offset < length || offset == length && preferLeftFragment) { return currentRange.getStartOffset() + offset; } offset -= length; offset -= mySuffixes[i].length(); prevEnd = currentRange.getEndOffset(); } return myRelevantRangesInHostDocument[myRelevantRangesInHostDocument.length-1].getEndOffset(); } @NotNull public TextRange injectedToHost(@NotNull TextRange injected) { ProperTextRange.assertProperRange(injected); int start = injectedToHost(injected.getStartOffset(), false); int end = injectedToHost(injected.getEndOffset(), true); if (end < start) { end = injectedToHost(injected.getEndOffset(), false); } return new ProperTextRange(start, end); } public int injectedToHostLine(int line) { if (line < myPrefixLineCount) { return myDelegate.getLineNumber(myRelevantRangesInHostDocument[0].getStartOffset()); } int lineCount = getLineCount(); if (line > lineCount - mySuffixLineCount) { return lineCount; } int offset = getLineStartOffset(line); int hostOffset = injectedToHost(offset); return myDelegate.getLineNumber(hostOffset); } public boolean containsRange(int start, int end) { if (end - start > myRelevantRangesInHostDocument[0].getEndOffset() - myRelevantRangesInHostDocument[0].getStartOffset()) return false; for (RangeMarker hostRange : myRelevantRangesInHostDocument) { if (InjectedLanguageUtil.toTextRange(hostRange).contains(new ProperTextRange(start, end))) return true; } return false; } @Deprecated @Nullable public TextRange intersectWithEditable(@NotNull TextRange rangeToEdit) { int offset = 0; int startOffset = -1; int endOffset = -1; for (int i = 0; i < myRelevantRangesInHostDocument.length; i++) { RangeMarker hostRange = myRelevantRangesInHostDocument[i]; offset += myPrefixes[i].length(); int length = hostRange.getEndOffset() - hostRange.getStartOffset(); TextRange intersection = new ProperTextRange(offset, offset + length).intersection(rangeToEdit); if (intersection != null) { if (startOffset == -1) { startOffset = intersection.getStartOffset(); } endOffset = intersection.getEndOffset(); } offset += length; offset += mySuffixes[i].length(); } if (startOffset == -1) return null; return new ProperTextRange(startOffset, endOffset); } public boolean intersects(DocumentWindowImpl documentWindow) { int i = 0; int j = 0; while (i < myRelevantRangesInHostDocument.length && j < documentWindow.myRelevantRangesInHostDocument.length) { RangeMarker range = myRelevantRangesInHostDocument[i]; RangeMarker otherRange = documentWindow.myRelevantRangesInHostDocument[j]; if (InjectedLanguageUtil.toTextRange(range).intersects(InjectedLanguageUtil.toTextRange(otherRange))) return true; if (range.getEndOffset() > otherRange.getStartOffset()) i++; else if (range.getStartOffset() < otherRange.getEndOffset()) j++; else { i++; j++; } } return false; } // minimum sequence of text replacement operations for each host range // result[i] == null means no change // result[i] == "" means delete // result[i] == string means replace public String[] calculateMinEditSequence(String newText) { String[] result = new String[myRelevantRangesInHostDocument.length]; String hostText = myDelegate.getText(); calculateMinEditSequence(hostText, newText, result, 0, result.length - 1); for (int i = 0; i < result.length; i++) { String change = result[i]; if (change == null) continue; assert change.startsWith(myPrefixes[i]) : change + " " + myPrefixes[i]; assert change.endsWith(mySuffixes[i]) : change + " " + mySuffixes[i]; result[i] = StringUtil.trimEnd(StringUtil.trimStart(change, myPrefixes[i]), mySuffixes[i]); } return result; } private String getRangeText(String hostText, int i) { return myPrefixes[i] + hostText.substring(myRelevantRangesInHostDocument[i].getStartOffset(), myRelevantRangesInHostDocument[i].getEndOffset()) + mySuffixes[i]; } private void calculateMinEditSequence(String hostText, String newText, String[] result, int i, int j) { String rangeText1 = getRangeText(hostText, i); if (i == j) { result[i] = rangeText1.equals(newText) ? null : newText; return; } if (StringUtil.startsWith(newText, rangeText1)) { result[i] = null; //no change calculateMinEditSequence(hostText, newText.substring(rangeText1.length()), result, i+1, j); return; } String rangeText2 = getRangeText(hostText, j); if (StringUtil.endsWith(newText, rangeText2)) { result[j] = null; //no change calculateMinEditSequence(hostText, newText.substring(0, newText.length() - rangeText2.length()), result, i, j-1); return; } if (i+1 == j) { String separator = mySuffixes[i] + myPrefixes[j]; if (separator.length() != 0) { int sep = newText.indexOf(separator); assert sep != -1; result[i] = newText.substring(0, sep + mySuffixes[i].length()); result[j] = newText.substring(sep + mySuffixes[i].length() + myPrefixes[j].length(), newText.length()); return; } String prefix = StringUtil.commonPrefix(rangeText1, newText); result[i] = prefix; result[j] = newText.substring(prefix.length()); return; } String middleText = getRangeText(hostText, i + 1); int m = newText.indexOf(middleText); if (m != -1) { result[i] = newText.substring(0, m); result[i+1] = null; calculateMinEditSequence(hostText, newText.substring(m+middleText.length(), newText.length()), result, i+2, j); return; } middleText = getRangeText(hostText, j - 1); m = newText.lastIndexOf(middleText); if (m != -1) { result[j] = newText.substring(m+middleText.length()); result[j-1] = null; calculateMinEditSequence(hostText, newText.substring(0, m), result, i, j-2); return; } result[i] = ""; result[j] = ""; calculateMinEditSequence(hostText, newText, result, i+1, j-1); } public boolean areRangesEqual(@NotNull DocumentWindow otherd) { DocumentWindowImpl window = (DocumentWindowImpl)otherd; if (myRelevantRangesInHostDocument.length != window.myRelevantRangesInHostDocument.length) return false; for (int i = 0; i < myRelevantRangesInHostDocument.length; i++) { if (!myPrefixes[i].equals(window.myPrefixes[i])) return false; if (!mySuffixes[i].equals(window.mySuffixes[i])) return false; RangeMarker hostRange = myRelevantRangesInHostDocument[i]; RangeMarker other = window.myRelevantRangesInHostDocument[i]; if (hostRange.getStartOffset() != other.getStartOffset()) return false; if (hostRange.getEndOffset() != other.getEndOffset()) return false; } return true; } public boolean isValid() { for (RangeMarker range : myRelevantRangesInHostDocument) { if (!range.isValid()) return false; } return true; } public boolean equals(Object o) { if (!(o instanceof DocumentWindowImpl)) return false; DocumentWindowImpl window = (DocumentWindowImpl)o; return myDelegate.equals(window.getDelegate()) && areRangesEqual(window); } public int hashCode() { return myRelevantRangesInHostDocument[0].getStartOffset(); } public boolean isOneLine() { return myOneLine; } public void dispose() { } }
package org.jboss.as.web; import static io.undertow.util.Headers.X_FORWARDED_FOR_STRING; import static io.undertow.util.Headers.X_FORWARDED_PROTO_STRING; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.OperationStepHandler; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.ProcessType; import org.jboss.as.controller.RunningMode; import org.jboss.as.controller.SimpleMapAttributeDefinition; import org.jboss.as.controller.SimpleOperationDefinitionBuilder; import org.jboss.as.controller.StringListAttributeDefinition; import org.jboss.as.controller.access.management.SensitiveTargetAccessConstraintDefinition; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.controller.descriptions.ResourceDescriptionResolver; import org.jboss.as.controller.operations.MultistepUtil; import org.jboss.as.controller.operations.common.GenericSubsystemDescribeHandler; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.as.controller.registry.OperationEntry; import org.jboss.as.controller.registry.Resource; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.jboss.dmr.ValueExpression; import org.wildfly.extension.io.IOExtension; import org.wildfly.extension.undertow.Constants; import org.wildfly.extension.undertow.UndertowExtension; import org.wildfly.extension.undertow.filters.CustomFilterDefinition; import org.wildfly.extension.undertow.filters.ExpressionFilterDefinition; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import static org.jboss.as.controller.OperationContext.Stage.MODEL; import static org.jboss.as.controller.PathAddress.pathAddress; import static org.jboss.as.controller.PathElement.pathElement; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADDRESS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.AUTHENTICATION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CORE_SERVICE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.EXTENSION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FAILURE_DESCRIPTION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.HOST; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.MANAGEMENT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.MODULE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PATH; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PROTOCOL; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RELATIVE_TO; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SECURITY_REALM; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVER_IDENTITY; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SOCKET_BINDING; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SSL; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.TRUSTSTORE; import static org.jboss.as.controller.operations.common.Util.createAddOperation; import static org.jboss.as.controller.operations.common.Util.createOperation; import static org.jboss.as.controller.operations.common.Util.createRemoveOperation; import static org.wildfly.extension.undertow.UndertowExtension.PATH_FILTERS; import java.util.regex.Matcher; import java.util.regex.Pattern; public class WebMigrateOperation implements OperationStepHandler { private static final String UNDERTOW_EXTENSION = "org.wildfly.extension.undertow"; private static final String IO_EXTENSION = "org.wildfly.extension.io"; private static final String REALM_NAME = "jbossweb-migration-security-realm"; private static final OperationStepHandler DESCRIBE_MIGRATION_INSTANCE = new WebMigrateOperation(true); private static final OperationStepHandler MIGRATE_INSTANCE = new WebMigrateOperation(false); public static final PathElement DEFAULT_SERVER_PATH = pathElement(Constants.SERVER, "default-server"); public static final PathAddress EXTENSION_ADDRESS = pathAddress(pathElement(EXTENSION, "org.jboss.as.web")); private static final PathAddress VALVE_ACCESS_LOG_ADDRESS = pathAddress(UndertowExtension.SUBSYSTEM_PATH, DEFAULT_SERVER_PATH, pathElement(Constants.HOST), UndertowExtension.PATH_ACCESS_LOG); public static final String MIGRATE = "migrate"; public static final String MIGRATION_WARNINGS = "migration-warnings"; public static final String MIGRATION_ERROR = "migration-error"; public static final String MIGRATION_OPERATIONS = "migration-operations"; public static final String DESCRIBE_MIGRATION = "describe-migration"; private static final Pattern ACCESS_LOG_PATTERN = Pattern.compile("%\\{(.*?)\\}(\\w)"); public static final StringListAttributeDefinition MIGRATION_WARNINGS_ATTR = new StringListAttributeDefinition.Builder(MIGRATION_WARNINGS) .setAllowNull(true) .build(); public static final SimpleMapAttributeDefinition MIGRATION_ERROR_ATTR = new SimpleMapAttributeDefinition.Builder(MIGRATION_ERROR, ModelType.OBJECT, true) .setValueType(ModelType.OBJECT) .setAllowNull(true) .build(); private final boolean describe; private WebMigrateOperation(boolean describe) { this.describe = describe; } static void registerOperations(ManagementResourceRegistration registry, ResourceDescriptionResolver resourceDescriptionResolver) { registry.registerOperationHandler(new SimpleOperationDefinitionBuilder(MIGRATE, resourceDescriptionResolver) .setRuntimeOnly() .setAccessConstraints(SensitiveTargetAccessConstraintDefinition.READ_WHOLE_CONFIG) .setReplyParameters(MIGRATION_WARNINGS_ATTR, MIGRATION_ERROR_ATTR) .build(), WebMigrateOperation.MIGRATE_INSTANCE); registry.registerOperationHandler(new SimpleOperationDefinitionBuilder(DESCRIBE_MIGRATION, resourceDescriptionResolver) .setRuntimeOnly() .setAccessConstraints(SensitiveTargetAccessConstraintDefinition.READ_WHOLE_CONFIG) .setReplyParameters(MIGRATION_WARNINGS_ATTR) .build(), WebMigrateOperation.DESCRIBE_MIGRATION_INSTANCE); } @Override public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { if (!describe && context.getRunningMode() != RunningMode.ADMIN_ONLY) { throw WebLogger.ROOT_LOGGER.migrateOperationAllowedOnlyInAdminOnly(); } final List<String> warnings = new ArrayList<>(); // node containing the description (list of add operations) of the legacy subsystem final ModelNode legacyModelAddOps = new ModelNode(); //we don't preserve order, instead we sort by address length final Map<PathAddress, ModelNode> sortedMigrationOperations = new TreeMap<>(new Comparator<PathAddress>() { @Override public int compare(PathAddress o1, PathAddress o2) { final int compare = Integer.compare(o1.size(), o2.size()); if (compare != 0) { return compare; } return o1.toString().compareTo(o2.toString()); } }); // invoke an OSH to describe the legacy messaging subsystem describeLegacyWebResources(context, legacyModelAddOps); // invoke an OSH to add the messaging-activemq extension addExtension(context, sortedMigrationOperations, describe, UNDERTOW_EXTENSION); addExtension(context, sortedMigrationOperations, describe, IO_EXTENSION); context.addStep(new OperationStepHandler() { @Override public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { addDefaultResources(sortedMigrationOperations, legacyModelAddOps, warnings); // transform the legacy add operations and put them in migrationOperations ProcessType processType = context.getCallEnvironment().getProcessType(); boolean domainMode = processType != ProcessType.STANDALONE_SERVER && processType != ProcessType.SELF_CONTAINED; PathAddress baseAddres; if(domainMode) { baseAddres = pathAddress(operation.get(ADDRESS)).getParent(); } else { baseAddres = pathAddress(); } //create the new IO subsystem createIoSubsystem(context, sortedMigrationOperations, baseAddres); createWelcomeContentHandler(sortedMigrationOperations); transformResources(context, legacyModelAddOps, sortedMigrationOperations, warnings, domainMode); fixAddressesForDomainMode(pathAddress(operation.get(ADDRESS)), sortedMigrationOperations); // put the /subsystem=web:remove operation //we need the removes to be last, so we create a new linked hash map and add our sorted ops to it LinkedHashMap<PathAddress, ModelNode> orderedMigrationOperations = new LinkedHashMap<>(sortedMigrationOperations); removeWebSubsystem(orderedMigrationOperations, context.getProcessType() == ProcessType.STANDALONE_SERVER, pathAddress(operation.get(ADDRESS))); if (describe) { // :describe-migration operation // for describe-migration operation, do nothing and return the list of operations that would // be executed in the composite operation final Collection<ModelNode> values = orderedMigrationOperations.values(); ModelNode result = new ModelNode(); if(!warnings.isEmpty()) { ModelNode rw = new ModelNode().setEmptyList(); for (String warning : warnings) { rw.add(warning); } result.get(MIGRATION_WARNINGS).set(rw); } result.get(MIGRATION_OPERATIONS).set(values); context.getResult().set(result); } else { // :migrate operation // invoke an OSH on a composite operation with all the migration operations final Map<PathAddress, ModelNode> migrateOpResponses = migrateSubsystems(context, orderedMigrationOperations); context.completeStep(new OperationContext.ResultHandler() { @Override public void handleResult(OperationContext.ResultAction resultAction, OperationContext context, ModelNode operation) { final ModelNode result = new ModelNode(); ModelNode rw = new ModelNode().setEmptyList(); for (String warning : warnings) { rw.add(warning); } result.get(MIGRATION_WARNINGS).set(rw); if (resultAction == OperationContext.ResultAction.ROLLBACK) { for (Map.Entry<PathAddress, ModelNode> entry : migrateOpResponses.entrySet()) { if (entry.getValue().hasDefined(FAILURE_DESCRIPTION)) { //we check for failure description, as every node has 'failed', but one //the real error has a failure description //we break when we find the first one, as there will only ever be one failure //as the op stops after the first failure ModelNode desc = new ModelNode(); desc.get(OP).set(orderedMigrationOperations.get(entry.getKey())); desc.get(RESULT).set(entry.getValue()); result.get(MIGRATION_ERROR).set(desc); break; } } context.getFailureDescription().set(new ModelNode(WebLogger.ROOT_LOGGER.migrationFailed())); } context.getResult().set(result); } }); } } }, MODEL); } /** * Creates the security realm * * @param context * @param migrationOperations * @return */ private SSLInformation createSecurityRealm(OperationContext context, Map<PathAddress, ModelNode> migrationOperations, ModelNode legacyModelAddOps, String connector, List<String> warnings, boolean domainMode) { ModelNode legacyAddOp = findResource(pathAddress(WebExtension.SUBSYSTEM_PATH, pathElement(WebExtension.CONNECTOR_PATH.getKey(), connector), pathElement("configuration", "ssl")), legacyModelAddOps); if (legacyAddOp == null) { return null; } //we have SSL //read all the info from the SSL definition ModelNode keyAlias = legacyAddOp.get(WebSSLDefinition.KEY_ALIAS.getName()); ModelNode password = legacyAddOp.get(WebSSLDefinition.PASSWORD.getName()); ModelNode certificateKeyFile = legacyAddOp.get(WebSSLDefinition.CERTIFICATE_KEY_FILE.getName()); ModelNode cipherSuite = legacyAddOp.get(WebSSLDefinition.CIPHER_SUITE.getName()); ModelNode protocol = legacyAddOp.get(WebSSLDefinition.PROTOCOL.getName()); ModelNode verifyClient = legacyAddOp.get(WebSSLDefinition.VERIFY_CLIENT.getName()); ModelNode verifyDepth = legacyAddOp.get(WebSSLDefinition.VERIFY_DEPTH.getName()); ModelNode certificateFile = legacyAddOp.get(WebSSLDefinition.CERTIFICATE_FILE.getName()); ModelNode caCertificateFile = legacyAddOp.get(WebSSLDefinition.CA_CERTIFICATE_FILE.getName()); ModelNode caCertificatePassword = legacyAddOp.get(WebSSLDefinition.CA_CERTIFICATE_PASSWORD.getName()); ModelNode csRevocationURL = legacyAddOp.get(WebSSLDefinition.CA_REVOCATION_URL.getName()); ModelNode trustStoreType = legacyAddOp.get(WebSSLDefinition.TRUSTSTORE_TYPE.getName()); ModelNode keystoreType = legacyAddOp.get(WebSSLDefinition.KEYSTORE_TYPE.getName()); ModelNode sessionCacheSize = legacyAddOp.get(WebSSLDefinition.SESSION_CACHE_SIZE.getName()); ModelNode sessionTimeout = legacyAddOp.get(WebSSLDefinition.SESSION_TIMEOUT.getName()); ModelNode sslProvider = legacyAddOp.get(WebSSLDefinition.SSL_PROTOCOL.getName()); if(verifyDepth.isDefined()) { warnings.add(WebLogger.ROOT_LOGGER.couldNotMigrateResource(WebSSLDefinition.VERIFY_DEPTH.getName(), pathAddress(legacyAddOp.get(ADDRESS)))); } if(certificateFile.isDefined()) { warnings.add(WebLogger.ROOT_LOGGER.couldNotMigrateResource(WebSSLDefinition.CERTIFICATE_FILE.getName(), pathAddress(legacyAddOp.get(ADDRESS)))); } if(sslProvider.isDefined()) { warnings.add(WebLogger.ROOT_LOGGER.couldNotMigrateResource(WebSSLDefinition.SSL_PROTOCOL.getName(), pathAddress(legacyAddOp.get(ADDRESS)))); } if(csRevocationURL.isDefined()) { warnings.add(WebLogger.ROOT_LOGGER.couldNotMigrateResource(WebSSLDefinition.CA_REVOCATION_URL.getName(), pathAddress(legacyAddOp.get(ADDRESS)))); } String realmName; PathAddress managementCoreService; if(domainMode) { Set<String> hosts = new HashSet<>(); Resource hostResource = context.readResourceFromRoot(pathAddress(), false); hosts.addAll(hostResource.getChildrenNames(HOST)); //now we need to find a unique name //in domain mode different profiles could have different SSL configurations //but the realms are not scoped to a profile //if we hard coded a name migration would fail when migrating domains with multiple profiles int counter = 1; realmName = REALM_NAME + counter; while(true) { boolean hostOk = true; for(String host : hosts) { Resource root = context.readResourceFromRoot(pathAddress(pathElement(HOST, host), pathElement(CORE_SERVICE, MANAGEMENT)), false); if (root.getChildrenNames(SECURITY_REALM).contains(realmName)) { counter++; realmName = REALM_NAME + counter; hostOk = false; break; } } if(hostOk) { break; } } for (String host : hosts) { createHostSSLConfig(realmName, migrationOperations, keyAlias, password, certificateKeyFile, protocol, caCertificateFile, caCertificatePassword, trustStoreType, keystoreType, pathAddress(pathElement(HOST, host), pathElement(CORE_SERVICE, MANAGEMENT))); } } else { managementCoreService = pathAddress(CORE_SERVICE, MANAGEMENT); //now we need to find a unique name //in domain mode different profiles could have different SSL configurations //but the realms are not scoped to a profile //if we hard coded a name migration would fail when migrating domains with multiple profiles int counter = 1; realmName = REALM_NAME + counter; boolean ok = false; do { Resource root = context.readResourceFromRoot(managementCoreService, false); if (root.getChildrenNames(SECURITY_REALM).contains(realmName)) { counter++; realmName = REALM_NAME + counter; } else { ok = true; } } while (!ok); //we have a unique realm name createHostSSLConfig(realmName, migrationOperations, keyAlias, password, certificateKeyFile, protocol, caCertificateFile, caCertificatePassword, trustStoreType, keystoreType, managementCoreService); } return new SSLInformation(realmName, verifyClient, sessionCacheSize, sessionTimeout, protocol, cipherSuite); } private String createHostSSLConfig(String realmName, Map<PathAddress, ModelNode> migrationOperations, ModelNode keyAlias, ModelNode password, ModelNode certificateKeyFile, ModelNode protocol, ModelNode caCertificateFile, ModelNode caCertificatePassword, ModelNode trustStoreType, ModelNode keystoreType, PathAddress managementCoreService) { //add the realm PathAddress addres = pathAddress(managementCoreService, pathElement(SECURITY_REALM, realmName)); migrationOperations.put(addres, createAddOperation(addres)); //now lets add the trust store addres = pathAddress(managementCoreService, pathElement(SECURITY_REALM, realmName), pathElement(AUTHENTICATION, TRUSTSTORE)); ModelNode addOp = createAddOperation(addres); addOp.get(ModelDescriptionConstants.KEYSTORE_PATH).set(caCertificateFile); addOp.get(ModelDescriptionConstants.KEYSTORE_PASSWORD).set(password); addOp.get(ModelDescriptionConstants.KEYSTORE_PROVIDER).set(trustStoreType); migrationOperations.put(addres, addOp); //now lets add the key store addres = pathAddress(managementCoreService, pathElement(SECURITY_REALM, realmName), pathElement(SERVER_IDENTITY, SSL)); addOp = createAddOperation(addres); addOp.get(ModelDescriptionConstants.KEYSTORE_PATH).set(certificateKeyFile); addOp.get(ModelDescriptionConstants.KEYSTORE_PASSWORD).set(password); addOp.get(ModelDescriptionConstants.KEYSTORE_PROVIDER).set(keystoreType); addOp.get(ModelDescriptionConstants.ALIAS).set(keyAlias); addOp.get(PROTOCOL).set(protocol); //addOp.get(KeystoreAttributes.KEY_PASSWORD.getName()).set(password); //TODO: is this correct? both key and keystore have same password? migrationOperations.put(addres, addOp); return realmName; } private void fixAddressesForDomainMode(PathAddress migrateAddress, Map<PathAddress, ModelNode> migrationOperations) { int i = 0; while (i < migrateAddress.size()) { if (migrateAddress.getElement(i).equals(WebExtension.SUBSYSTEM_PATH)) { break; } ++i; } if (i == 0) { //not domain mode, no need for a prefix return; } PathAddress prefix = migrateAddress.subAddress(0, i); Map<PathAddress, ModelNode> old = new HashMap<>(migrationOperations); migrationOperations.clear(); for (Map.Entry<PathAddress, ModelNode> e : old.entrySet()) { if (e.getKey().getElement(0).getKey().equals(SUBSYSTEM)) { final PathAddress oldAddress = pathAddress(e.getValue().get(ADDRESS)); List<PathElement> elements = new ArrayList<>(); for (PathElement j : prefix) { elements.add(j); } for (PathElement j : oldAddress) { elements.add(j); } PathAddress newAddress = pathAddress(elements); e.getValue().get(ADDRESS).set(newAddress.toModelNode()); migrationOperations.put(newAddress, e.getValue()); } else { //not targeted at a subsystem migrationOperations.put(e.getKey(), e.getValue()); } } } /** * We need to create the IO subsystem, if it does not already exist */ private void createIoSubsystem(OperationContext context, Map<PathAddress, ModelNode> migrationOperations, PathAddress baseAddress) { Resource root = context.readResourceFromRoot(baseAddress, false); if (root.getChildrenNames(SUBSYSTEM).contains(IOExtension.SUBSYSTEM_NAME)) { // subsystem is already added, do nothing return; } //these addresses will be fixed later, no need to use the base address PathAddress address = pathAddress(pathElement(SUBSYSTEM, IOExtension.SUBSYSTEM_NAME)); migrationOperations.put(address, createAddOperation(address)); address = pathAddress(pathElement(SUBSYSTEM, IOExtension.SUBSYSTEM_NAME), pathElement("worker", "default")); migrationOperations.put(address, createAddOperation(address)); address = pathAddress(pathElement(SUBSYSTEM, IOExtension.SUBSYSTEM_NAME), pathElement("buffer-pool", "default")); migrationOperations.put(address, createAddOperation(address)); } /** * create a handler for serving welcome content */ private void createWelcomeContentHandler(Map<PathAddress, ModelNode> migrationOperations) { PathAddress address = pathAddress(pathElement(SUBSYSTEM, UndertowExtension.SUBSYSTEM_NAME), pathElement(Constants.CONFIGURATION, Constants.HANDLER)); migrationOperations.put(address, createAddOperation(address)); address = pathAddress(pathElement(SUBSYSTEM, UndertowExtension.SUBSYSTEM_NAME), pathElement(Constants.CONFIGURATION, Constants.HANDLER), pathElement(Constants.FILE, "welcome-content")); final ModelNode add = createAddOperation(address); add.get(Constants.PATH).set(new ModelNode(new ValueExpression("${jboss.home.dir}/welcome-content"))); migrationOperations.put(address, add); } private void addDefaultResources(Map<PathAddress, ModelNode> migrationOperations, final ModelNode legacyModelDescription, List<String> warnings) { //add the default server PathAddress address = pathAddress(pathElement(SUBSYSTEM, UndertowExtension.SUBSYSTEM_NAME), DEFAULT_SERVER_PATH); ModelNode add = createAddOperation(address); ModelNode defaultSessionTimeout = null; //static resources ModelNode directoryListing = null; //todo: add support for some of these ModelNode sendfile = null; ModelNode fileEncoding = null; ModelNode readOnly = null; ModelNode webdav = null; ModelNode secret = null; ModelNode maxDepth = null; ModelNode disabled = null; for (ModelNode legacyAddOp : legacyModelDescription.get(RESULT).asList()) { final PathAddress la = pathAddress(legacyAddOp.get(ADDRESS)); if (la.equals(pathAddress(WebExtension.SUBSYSTEM_PATH))) { ModelNode defaultHost = legacyAddOp.get(WebDefinition.DEFAULT_VIRTUAL_SERVER.getName()); if (defaultHost.isDefined()) { add.get(Constants.DEFAULT_HOST).set(defaultHost.clone()); } ModelNode sessionTimeout = legacyAddOp.get(WebDefinition.DEFAULT_SESSION_TIMEOUT.getName()); if (sessionTimeout.isDefined()) { defaultSessionTimeout = sessionTimeout; } } else if (la.equals(pathAddress(WebExtension.SUBSYSTEM_PATH, WebExtension.STATIC_RESOURCES_PATH))) { ModelNode node = legacyAddOp.get(WebStaticResources.LISTINGS.getName()); if (node.isDefined()) { directoryListing = node; } node = legacyAddOp.get(WebStaticResources.SENDFILE.getName()); if (node.isDefined()) { warnings.add(WebLogger.ROOT_LOGGER.couldNotMigrateResource(WebStaticResources.SENDFILE.getName(), pathAddress(legacyAddOp.get(ADDRESS)))); sendfile = node; } node = legacyAddOp.get(WebStaticResources.FILE_ENCODING.getName()); if (node.isDefined()) { warnings.add(WebLogger.ROOT_LOGGER.couldNotMigrateResource(WebStaticResources.FILE_ENCODING.getName(), pathAddress(legacyAddOp.get(ADDRESS)))); fileEncoding = node; } node = legacyAddOp.get(WebStaticResources.READ_ONLY.getName()); if (node.isDefined()) { warnings.add(WebLogger.ROOT_LOGGER.couldNotMigrateResource(WebStaticResources.READ_ONLY.getName(), pathAddress(legacyAddOp.get(ADDRESS)))); readOnly = node; } node = legacyAddOp.get(WebStaticResources.WEBDAV.getName()); if (node.isDefined()) { warnings.add(WebLogger.ROOT_LOGGER.couldNotMigrateResource(WebStaticResources.WEBDAV.getName(), pathAddress(legacyAddOp.get(ADDRESS)))); webdav = node; } node = legacyAddOp.get(WebStaticResources.SECRET.getName()); if (node.isDefined()) { warnings.add(WebLogger.ROOT_LOGGER.couldNotMigrateResource(WebStaticResources.SECRET.getName(), pathAddress(legacyAddOp.get(ADDRESS)))); secret = node; } node = legacyAddOp.get(WebStaticResources.MAX_DEPTH.getName()); if (node.isDefined()) { warnings.add(WebLogger.ROOT_LOGGER.couldNotMigrateResource(WebStaticResources.MAX_DEPTH.getName(), pathAddress(legacyAddOp.get(ADDRESS)))); maxDepth = node; } node = legacyAddOp.get(WebStaticResources.DISABLED.getName()); if (node.isDefined()) { warnings.add(WebLogger.ROOT_LOGGER.couldNotMigrateResource(WebStaticResources.DISABLED.getName(), pathAddress(legacyAddOp.get(ADDRESS)))); disabled = node; } } } migrationOperations.put(address, add); address = pathAddress(pathElement(SUBSYSTEM, UndertowExtension.SUBSYSTEM_NAME), pathElement(Constants.BUFFER_CACHE, "default")); add = createAddOperation(address); migrationOperations.put(address, add); address = pathAddress(pathElement(SUBSYSTEM, UndertowExtension.SUBSYSTEM_NAME), pathElement(Constants.SERVLET_CONTAINER, "default")); add = createAddOperation(address); if (defaultSessionTimeout != null) { add.get(Constants.DEFAULT_SESSION_TIMEOUT).set(defaultSessionTimeout.clone()); } if (directoryListing != null) { add.get(Constants.DIRECTORY_LISTING).set(directoryListing); } migrationOperations.put(address, add); } /** * It's possible that the extension is already present. In that case, this method does nothing. */ private void addExtension(OperationContext context, Map<PathAddress, ModelNode> migrationOperations, boolean describe, String extension) { Resource root = context.readResourceFromRoot(PathAddress.EMPTY_ADDRESS, false); if (root.getChildrenNames(EXTENSION).contains(extension)) { // extension is already added, do nothing return; } PathAddress extensionAddress = pathAddress(EXTENSION, extension); OperationEntry addEntry = context.getRootResourceRegistration().getOperationEntry(extensionAddress, ADD); ModelNode addOperation = createAddOperation(extensionAddress); addOperation.get(MODULE).set(extension); if (describe) { migrationOperations.put(extensionAddress, addOperation); } else { context.addStep(context.getResult().get(extensionAddress.toString()), addOperation, addEntry.getOperationHandler(), MODEL); } } private void removeWebSubsystem(Map<PathAddress, ModelNode> migrationOperations, boolean standalone, PathAddress subsystemAddress) { ModelNode removeOperation = createRemoveOperation(subsystemAddress); migrationOperations.put(subsystemAddress, removeOperation); //only add this if we are describing //to maintain the order we manually execute this last if(standalone) { removeOperation = createRemoveOperation(EXTENSION_ADDRESS); migrationOperations.put(EXTENSION_ADDRESS, removeOperation); } } private Map<PathAddress, ModelNode> migrateSubsystems(OperationContext context, final Map<PathAddress, ModelNode> migrationOperations) throws OperationFailedException { final Map<PathAddress, ModelNode> result = new LinkedHashMap<>(); MultistepUtil.recordOperationSteps(context, migrationOperations, result); return result; } private void transformResources(final OperationContext context, final ModelNode legacyModelDescription, final Map<PathAddress, ModelNode> newAddOperations, List<String> warnings, boolean domainMode) throws OperationFailedException { Set<String> hosts = new LinkedHashSet<>(); for (ModelNode legacyAddOp : legacyModelDescription.get(RESULT).asList()) { final ModelNode newAddOp = legacyAddOp.clone(); PathAddress address = pathAddress(newAddOp.get(ADDRESS)); if (address.size() == 1) { //subsystem migrateSubsystem(newAddOperations, newAddOp); } else if (address.equals(pathAddress(WebExtension.SUBSYSTEM_PATH, WebExtension.STATIC_RESOURCES_PATH))) { //covered in the servlet container add, so just ignore } else if (address.equals(pathAddress(WebExtension.SUBSYSTEM_PATH, WebExtension.JSP_CONFIGURATION_PATH))) { migrateJSPConfig(newAddOperations, newAddOp); } else if (address.equals(pathAddress(WebExtension.SUBSYSTEM_PATH, WebExtension.CONTAINER_PATH))) { migrateMimeMapping(newAddOperations, newAddOp); } else if (wildcardEquals(address, pathAddress(WebExtension.SUBSYSTEM_PATH, WebExtension.CONNECTOR_PATH))) { migrateConnector(context, newAddOperations, newAddOp, address, legacyModelDescription, warnings, domainMode); } else if (wildcardEquals(address, pathAddress(WebExtension.SUBSYSTEM_PATH, WebExtension.CONNECTOR_PATH, WebExtension.SSL_PATH))) { // ignore, handled as part of connector migration } else if (wildcardEquals(address, pathAddress(WebExtension.SUBSYSTEM_PATH, WebExtension.HOST_PATH))) { String host = address.getLastElement().getValue(); hosts.add(host); migrateVirtualHost(newAddOperations, newAddOp, host); } else if (wildcardEquals(address, pathAddress(WebExtension.SUBSYSTEM_PATH, WebExtension.VALVE_PATH))) { migrateValves(newAddOperations, newAddOp, address, warnings); } else if (wildcardEquals(address, pathAddress(WebExtension.SUBSYSTEM_PATH, WebExtension.HOST_PATH, WebExtension.ACCESS_LOG_PATH))) { migrateAccessLog(newAddOperations, newAddOp, address, legacyModelDescription, warnings); } else if (wildcardEquals(address, pathAddress(WebExtension.SUBSYSTEM_PATH, WebExtension.HOST_PATH, WebExtension.ACCESS_LOG_PATH, WebExtension.DIRECTORY_PATH))) { //ignore, handled by access-log } else if (wildcardEquals(address, pathAddress(WebExtension.SUBSYSTEM_PATH, WebExtension.HOST_PATH, WebExtension.SSO_PATH))) { migrateSso(newAddOperations, newAddOp, address, warnings); } else { warnings.add(WebLogger.ROOT_LOGGER.couldNotMigrateResource(legacyAddOp)); } } if (!hosts.isEmpty()) { migrateVirtualHostChildren(newAddOperations, hosts); } newAddOperations.remove(VALVE_ACCESS_LOG_ADDRESS); } private void migrateSso(Map<PathAddress, ModelNode> newAddOperations, ModelNode newAddOp, PathAddress address, List<String> warnings) { PathAddress newAddress = pathAddress(UndertowExtension.SUBSYSTEM_PATH, DEFAULT_SERVER_PATH, pathElement(Constants.HOST, address.getElement(address.size() - 2).getValue()), UndertowExtension.PATH_SSO); ModelNode add = createAddOperation(newAddress); add.get(Constants.DOMAIN).set(newAddOp.get(WebSSODefinition.DOMAIN.getName()).clone()); add.get(Constants.HTTP_ONLY).set(newAddOp.get(WebSSODefinition.HTTP_ONLY.getName()).clone()); if (newAddOp.hasDefined(WebSSODefinition.CACHE_CONTAINER.getName())) { warnings.add(WebLogger.ROOT_LOGGER.couldNotMigrateResource(WebSSODefinition.CACHE_CONTAINER.getName(), pathAddress(newAddOp.get(ADDRESS)))); } if (newAddOp.hasDefined(WebSSODefinition.REAUTHENTICATE.getName())) { warnings.add(WebLogger.ROOT_LOGGER.couldNotMigrateResource(WebSSODefinition.REAUTHENTICATE.getName(), pathAddress(newAddOp.get(ADDRESS)))); } if (newAddOp.hasDefined(WebSSODefinition.CACHE_NAME.getName())) { warnings.add(WebLogger.ROOT_LOGGER.couldNotMigrateResource(WebSSODefinition.CACHE_NAME.getName(), pathAddress(newAddOp.get(ADDRESS)))); } newAddOperations.put(newAddress, add); } private void migrateAccessLog(Map<PathAddress, ModelNode> newAddOperations, ModelNode newAddOp, PathAddress address, ModelNode legacyAddOps, List<String> warnings) { PathAddress newAddress = pathAddress(UndertowExtension.SUBSYSTEM_PATH, DEFAULT_SERVER_PATH, pathElement(Constants.HOST, address.getElement(address.size() - 2).getValue()), UndertowExtension.PATH_ACCESS_LOG); ModelNode add = createAddOperation(newAddress); //TODO: parse the pattern and modify to Undertow version ModelNode patternNode = newAddOp.get(WebAccessLogDefinition.PATTERN.getName()); if(patternNode.isDefined()) { add.get(Constants.PATTERN).set(migrateAccessLogPattern(patternNode.asString())); } add.get(Constants.PREFIX).set(newAddOp.get(WebAccessLogDefinition.PREFIX.getName()).clone()); add.get(Constants.ROTATE).set(newAddOp.get(WebAccessLogDefinition.ROTATE.getName()).clone()); if (newAddOp.hasDefined(WebAccessLogDefinition.RESOLVE_HOSTS.getName())) { warnings.add(WebLogger.ROOT_LOGGER.couldNotMigrateResource(WebAccessLogDefinition.RESOLVE_HOSTS.getName(), pathAddress(newAddOp.get(ADDRESS)))); } add.get(Constants.EXTENDED).set(newAddOp.get(WebAccessLogDefinition.EXTENDED.getName()).clone()); ModelNode directory = findResource(pathAddress(pathAddress(newAddOp.get(ADDRESS)), WebExtension.DIRECTORY_PATH), legacyAddOps); if(directory != null){ add.get(Constants.DIRECTORY).set(directory.get(PATH)); add.get(Constants.RELATIVE_TO).set(directory.get(RELATIVE_TO)); } newAddOperations.put(newAddress, add); } private String migrateAccessLogPattern(String legacyPattern) { Matcher m = ACCESS_LOG_PATTERN.matcher(legacyPattern); StringBuilder sb = new StringBuilder(); int lastIndex = 0; while (m.find()) { sb.append(legacyPattern.substring(lastIndex, m.start())); lastIndex = m.end(); sb.append("%{"); sb.append(m.group(2)); sb.append(","); sb.append(m.group(1)); sb.append("}"); } sb.append(legacyPattern.substring(lastIndex)); return sb.toString(); } private void migrateAccessLogValve(Map<PathAddress, ModelNode> newAddOperations, ModelNode newAddOp, String valveName, List<String> warnings) { ModelNode add = createAddOperation(VALVE_ACCESS_LOG_ADDRESS); final ModelNode params = newAddOp.get(WebValveDefinition.PARAMS.getName()); //TODO: parse the pattern and modify to Undertow version final ModelNode patternNode = params.get(Constants.PATTERN); if(patternNode.isDefined()) { add.get(Constants.PATTERN).set(migrateAccessLogPattern(patternNode.asString())); } add.get(Constants.PREFIX).set(params.get(Constants.PREFIX).clone()); add.get(Constants.SUFFIX).set(params.get(Constants.SUFFIX).clone()); add.get(Constants.ROTATE).set(params.get("rotatable").clone()); add.get(Constants.EXTENDED).set(newAddOp.get(Constants.EXTENDED).clone()); if(params.hasDefined(Constants.DIRECTORY)){ add.get(Constants.DIRECTORY).set(params.get(Constants.DIRECTORY).clone()); } if(params.hasDefined("conditionIf")) { add.get(Constants.PREDICATE).set("exists(%{r," + params.get("conditionIf").asString() + "})"); } if(params.hasDefined("conditionUnless")) { add.get(Constants.PREDICATE).set("not exists(%{r," + params.get("conditionUnless").asString() + "})"); } if(params.hasDefined("condition")) { add.get(Constants.PREDICATE).set("not exists(%{r," + params.get("condition").asString() + "})"); } final String[] unsupportedConfigParams = new String[] {"resolveHosts", "fileDateFormat", "renameOnRotate", "encoding", "locale", "requestAttributesEnabled", "buffered"}; for(String unsupportedConfigParam : unsupportedConfigParams) { if(params.hasDefined(unsupportedConfigParam)) { warnings.add(WebLogger.ROOT_LOGGER.couldNotMigrateValveAttribute(unsupportedConfigParam, valveName)); } } newAddOperations.put(VALVE_ACCESS_LOG_ADDRESS, add); } private boolean wildcardEquals(PathAddress a1, PathAddress a2) { if (a1.size() != a2.size()) { return false; } for (int i = 0; i < a1.size(); ++i) { PathElement p1 = a1.getElement(i); PathElement p2 = a2.getElement(i); if (!p1.getKey().equals(p2.getKey())) { return false; } if (!p1.isWildcard() && !p2.isWildcard()) { if (!p1.getValue().equals(p2.getValue())) { return false; } } } return true; } private void migrateVirtualHost(Map<PathAddress, ModelNode> newAddOperations, ModelNode newAddOp, String host) { PathAddress newAddress = pathAddress(UndertowExtension.SUBSYSTEM_PATH, DEFAULT_SERVER_PATH, pathElement(Constants.HOST, host)); ModelNode add = createAddOperation(newAddress); if (newAddOp.hasDefined(WebVirtualHostDefinition.ENABLE_WELCOME_ROOT.getName()) && newAddOp.get(WebVirtualHostDefinition.ENABLE_WELCOME_ROOT.getName()).asBoolean()) { PathAddress welcomeAddress = pathAddress(newAddress, pathElement(Constants.LOCATION, "/")); ModelNode welcomeAdd = createAddOperation(welcomeAddress); welcomeAdd.get(Constants.HANDLER).set("welcome-content"); newAddOperations.put(welcomeAddress, welcomeAdd); } add.get(Constants.ALIAS).set(newAddOp.get(WebVirtualHostDefinition.ALIAS.getName()).clone()); add.get(Constants.DEFAULT_WEB_MODULE).set(newAddOp.get(WebVirtualHostDefinition.DEFAULT_WEB_MODULE.getName())); newAddOperations.put(newAddress, add); } private void migrateVirtualHostChildren(Map<PathAddress, ModelNode> newAddOperations, Set<String> hosts) { final PathAddress customFilterAddresses = pathAddress(UndertowExtension.SUBSYSTEM_PATH, PATH_FILTERS, pathElement(CustomFilterDefinition.INSTANCE.getPathElement().getKey())); final PathAddress expressionFilterAddresses = pathAddress(UndertowExtension.SUBSYSTEM_PATH, PATH_FILTERS, pathElement(ExpressionFilterDefinition.INSTANCE.getPathElement().getKey())); List<PathAddress> filterAddresses = new ArrayList<>(); for(PathAddress a : newAddOperations.keySet()) { if(wildcardEquals(customFilterAddresses, a) || wildcardEquals(expressionFilterAddresses, a)) { filterAddresses.add(a); } } boolean hasAccessLogValve = newAddOperations.containsKey(VALVE_ACCESS_LOG_ADDRESS); if (hasAccessLogValve || !filterAddresses.isEmpty()) { for (String host : hosts) { PathAddress hostAddress = pathAddress(UndertowExtension.SUBSYSTEM_PATH, DEFAULT_SERVER_PATH, pathElement(Constants.HOST, host)); for (PathAddress filterAddress : filterAddresses) { PathAddress filterRefAddress = pathAddress(hostAddress, pathElement(Constants.FILTER_REF, filterAddress.getLastElement().getValue())); ModelNode filterRefAdd = createAddOperation(filterRefAddress); newAddOperations.put(filterRefAddress, filterRefAdd); } if (hasAccessLogValve) { PathAddress accessLogAddress = pathAddress(hostAddress, UndertowExtension.PATH_ACCESS_LOG); if(!newAddOperations.containsKey(accessLogAddress)) { ModelNode operation = newAddOperations.get(VALVE_ACCESS_LOG_ADDRESS).clone(); operation.get(OP_ADDR).set(accessLogAddress.toModelNode()); newAddOperations.put(accessLogAddress, operation); } } } } } private void migrateValves(Map<PathAddress, ModelNode> newAddOperations, ModelNode newAddOp, PathAddress address, List<String> warnings) { if (newAddOp.hasDefined(WebValveDefinition.CLASS_NAME.getName())) { String valveClassName = newAddOp.get(WebValveDefinition.CLASS_NAME.getName()).asString(); String valveName = address.getLastElement().getValue(); switch (valveClassName) { case "org.apache.catalina.valves.CrawlerSessionManagerValve": PathAddress crawlerAddress = pathAddress(pathElement(SUBSYSTEM, UndertowExtension.SUBSYSTEM_NAME), pathElement(Constants.SERVLET_CONTAINER, "default"), pathElement(Constants.SETTING, Constants.CRAWLER_SESSION_MANAGEMENT)); ModelNode crawlerAdd = createAddOperation(crawlerAddress); if (newAddOp.hasDefined(WebValveDefinition.PARAMS.getName())) { ModelNode params = newAddOp.get(WebValveDefinition.PARAMS.getName()); if (params.hasDefined("crawlerUserAgents")) { crawlerAdd.get(Constants.USER_AGENTS).set(params.get("crawlerUserAgents")); } if (params.hasDefined("sessionInactiveInterval")) { crawlerAdd.get(Constants.SESSION_TIMEOUT).set(params.get("sessionInactiveInterval")); } } newAddOperations.put(crawlerAddress, crawlerAdd); break; case "org.apache.catalina.valves.RequestDumperValve": newAddOperations.putIfAbsent(pathAddress(UndertowExtension.SUBSYSTEM_PATH, PATH_FILTERS), createAddOperation(pathAddress(UndertowExtension.SUBSYSTEM_PATH, PATH_FILTERS))); PathAddress filterAddress = pathAddress(UndertowExtension.SUBSYSTEM_PATH, PATH_FILTERS, pathElement(ExpressionFilterDefinition.INSTANCE.getPathElement().getKey(), valveName)); ModelNode filterAdd = createAddOperation(filterAddress); filterAdd.get(ExpressionFilterDefinition.EXPRESSION.getName()).set("dump-request"); newAddOperations.put(filterAddress, filterAdd); break; case "org.apache.catalina.valves.StuckThreadDetectionValve": newAddOperations.putIfAbsent(pathAddress(UndertowExtension.SUBSYSTEM_PATH, PATH_FILTERS), createAddOperation(pathAddress(UndertowExtension.SUBSYSTEM_PATH, PATH_FILTERS))); PathAddress filterAddressStuckThread = pathAddress(UndertowExtension.SUBSYSTEM_PATH, PATH_FILTERS, pathElement(ExpressionFilterDefinition.INSTANCE.getPathElement().getKey(), valveName)); ModelNode filterAddStuckThread = createAddOperation(filterAddressStuckThread); StringBuilder expressionStruckThread = new StringBuilder("stuck-thread-detector"); if (newAddOp.hasDefined(WebValveDefinition.PARAMS.getName())) { ModelNode params = newAddOp.get(WebValveDefinition.PARAMS.getName()); if (params.hasDefined("threshold")) { expressionStruckThread.append("(threshhold='").append(params.get("threshold").asInt()).append("')"); } if (params.hasDefined("interruptThreadThreshold")) { warnings.add(WebLogger.ROOT_LOGGER.couldNotMigrateValveAttribute("interruptThreadThreshold", valveName)); } } filterAddStuckThread.get(ExpressionFilterDefinition.EXPRESSION.getName()).set(expressionStruckThread.toString()); newAddOperations.put(filterAddressStuckThread, filterAddStuckThread); break; case "org.apache.catalina.valves.AccessLogValve": newAddOp.get(WebAccessLogDefinition.EXTENDED.getName()).set(false); migrateAccessLogValve(newAddOperations, newAddOp, valveName, warnings); break; case "org.apache.catalina.valves.ExtendedAccessLogValve": newAddOp.get(WebAccessLogDefinition.EXTENDED.getName()).set(true); migrateAccessLogValve(newAddOperations, newAddOp, valveName, warnings); break; case "org.apache.catalina.valves.RemoteHostValve": createAccesControlExpressionFilter(newAddOperations, warnings, valveName, "%h", newAddOp); break; case "org.apache.catalina.valves.RemoteAddrValve": createAccesControlExpressionFilter(newAddOperations, warnings, valveName, "%a", newAddOp); break; case "org.apache.catalina.valves.RemoteIpValve": if (newAddOp.hasDefined(WebValveDefinition.PARAMS.getName())) { StringBuilder expression = new StringBuilder(); ModelNode params = newAddOp.get(WebValveDefinition.PARAMS.getName()); if(params.hasDefined("remoteIpHeader") && ! X_FORWARDED_FOR_STRING.equalsIgnoreCase(params.get("remoteIpHeader").asString())) { warnings.add(WebLogger.ROOT_LOGGER.couldNotMigrateValveAttribute("remoteIpHeader", valveName)); } if(params.hasDefined("protocolHeader") && ! X_FORWARDED_PROTO_STRING.equalsIgnoreCase(params.get("protocolHeader").asString())) { warnings.add(WebLogger.ROOT_LOGGER.couldNotMigrateValveAttribute("protocolHeader", valveName)); } if(params.hasDefined("httpServerPort")) { warnings.add(WebLogger.ROOT_LOGGER.couldNotMigrateValveAttribute("httpServerPort", valveName)); } if(params.hasDefined("httpsServerPort")) { warnings.add(WebLogger.ROOT_LOGGER.couldNotMigrateValveAttribute("httpsServerPort", valveName)); } if(params.hasDefined("proxiesHeader")) { warnings.add(WebLogger.ROOT_LOGGER.couldNotMigrateValveAttribute("proxiesHeader", valveName)); } if(params.hasDefined("protocolHeaderHttpsValue")) { warnings.add(WebLogger.ROOT_LOGGER.couldNotMigrateValveAttribute("protocolHeaderHttpsValue", valveName)); } boolean trustedProxies = false; if (params.hasDefined("trustedProxies")) { expression.append("regex(pattern=\"").append(params.get("trustedProxies").asString()).append("\", value=%{i,x-forwarded-for}, full-match=true)"); trustedProxies = true; } String internalProxies; if (params.hasDefined("internalProxies")) { internalProxies = params.get("internalProxies").asString(); } else { internalProxies = "10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|192\\.168\\.\\d{1,3}\\.\\d{1,3}|169\\.254\\.\\d{1,3}\\.\\d{1,3}|127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"; } if (trustedProxies) { expression.append(" and "); } expression.append("regex(pattern=\"").append(internalProxies).append("\", value=%{i,x-forwarded-for}, full-match=true)"); expression.append(" -> proxy-peer-address"); createExpressionFilter(newAddOperations, valveName, expression.toString()); } break; default: warnings.add(WebLogger.ROOT_LOGGER.couldNotMigrateValve(valveName)); break; } } } private void createAccesControlExpressionFilter(Map<PathAddress, ModelNode> newAddOperations, List<String> warnings, String name, String attribute, ModelNode newAddOp) { if (newAddOp.hasDefined(WebValveDefinition.PARAMS.getName())) { StringBuilder expression = new StringBuilder(); expression.append("access-control(acl={"); ModelNode params = newAddOp.get(WebValveDefinition.PARAMS.getName()); boolean isValid = false; if (params.hasDefined("deny")) { isValid = true; String[] denied = params.get("deny").asString().split(","); for (String deny : denied) { expression.append('\'').append(deny.trim()).append(" deny\', "); } } if (params.hasDefined("allow")) { isValid = true; String[] allowed = params.get("allow").asString().split(","); for (String allow : allowed) { expression.append('\'').append(allow.trim()).append(" allow\', "); } } if (isValid) { expression.delete(expression.length() - 2, expression.length()); expression.append("} , attribute=").append(attribute.trim()).append(')'); createExpressionFilter(newAddOperations, name, expression.toString()); } else { warnings.add(WebLogger.ROOT_LOGGER.couldNotMigrateValve(name)); } } else { warnings.add(WebLogger.ROOT_LOGGER.couldNotMigrateValve(name)); } } private void createExpressionFilter(Map<PathAddress, ModelNode> newAddOperations, String name, String expression) { newAddOperations.putIfAbsent(pathAddress(UndertowExtension.SUBSYSTEM_PATH, PATH_FILTERS), createAddOperation(pathAddress(UndertowExtension.SUBSYSTEM_PATH, PATH_FILTERS))); PathAddress filterAddress = pathAddress(UndertowExtension.SUBSYSTEM_PATH, PATH_FILTERS, pathElement(ExpressionFilterDefinition.INSTANCE.getPathElement().getKey(), name)); ModelNode filterAdd = createAddOperation(filterAddress); filterAdd.get(ExpressionFilterDefinition.EXPRESSION.getName()).set(expression); newAddOperations.put(filterAddress, filterAdd); } private void migrateConnector(OperationContext context, Map<PathAddress, ModelNode> newAddOperations, ModelNode newAddOp, PathAddress address, ModelNode legacyModelAddOps, List<String> warnings, boolean domainMode) throws OperationFailedException { String protocol = newAddOp.get(WebConnectorDefinition.PROTOCOL.getName()).asString(); String scheme = null; if (newAddOp.hasDefined(WebConnectorDefinition.SCHEME.getName())) { scheme = newAddOp.get(WebConnectorDefinition.SCHEME.getName()).asString(); } final PathAddress newAddress; final ModelNode addConnector; switch (protocol) { case "org.apache.coyote.http11.Http11Protocol": case "org.apache.coyote.http11.Http11NioProtocol": case "org.apache.coyote.http11.Http11AprProtocol": case "HTTP/1.1": if (scheme == null || scheme.equals("http")) { newAddress = pathAddress(UndertowExtension.SUBSYSTEM_PATH, DEFAULT_SERVER_PATH, pathElement(Constants.HTTP_LISTENER, address.getLastElement().getValue())); addConnector = createAddOperation(newAddress); } else if (scheme.equals("https")) { newAddress = pathAddress(UndertowExtension.SUBSYSTEM_PATH, DEFAULT_SERVER_PATH, pathElement(Constants.HTTPS_LISTENER, address.getLastElement().getValue())); addConnector = createAddOperation(newAddress); SSLInformation sslInfo = createSecurityRealm(context, newAddOperations, legacyModelAddOps, newAddress.getLastElement().getValue(), warnings, domainMode); if (sslInfo == null) { throw WebLogger.ROOT_LOGGER.noSslConfig(); } else { addConnector.get(Constants.SECURITY_REALM).set(sslInfo.realmName); ModelNode verify = sslInfo.verifyClient; if(verify.isDefined()) { if(verify.getType() == ModelType.EXPRESSION) { warnings.add(WebLogger.ROOT_LOGGER.couldNotTranslateVerifyClientExpression(verify.toString())); addConnector.get(Constants.VERIFY_CLIENT).set(verify); } else { String translated = translateVerifyClient(verify.asString(), warnings); if(translated != null) { addConnector.get(Constants.VERIFY_CLIENT).set(translated); } } } addConnector.get(Constants.SSL_SESSION_CACHE_SIZE).set(sslInfo.sessionCacheSize); addConnector.get(Constants.SSL_SESSION_TIMEOUT).set(sslInfo.sessionTimeout); addConnector.get(Constants.ENABLED_PROTOCOLS).set(sslInfo.sslProtocol); addConnector.get(Constants.ENABLED_CIPHER_SUITES).set(sslInfo.cipherSuites); } } else { newAddress = null; addConnector = null; } break; case "org.apache.coyote.ajp.AjpAprProtocol": case "org.apache.coyote.ajp.AjpProtocol": case "AJP/1.3": newAddress = pathAddress(UndertowExtension.SUBSYSTEM_PATH, DEFAULT_SERVER_PATH, pathElement(Constants.AJP_LISTENER, address.getLastElement().getValue())); addConnector = createAddOperation(newAddress); addConnector.get(Constants.SCHEME).set(newAddOp.get(Constants.SCHEME)); break; default: newAddress = null; addConnector = null; } if (newAddress == null) { warnings.add(WebLogger.ROOT_LOGGER.couldNotMigrateResource(newAddOp)); return; } addConnector.get(Constants.SOCKET_BINDING).set(newAddOp.get(SOCKET_BINDING)); addConnector.get(Constants.SECURE).set(newAddOp.get(WebConnectorDefinition.SECURE.getName())); addConnector.get(Constants.REDIRECT_SOCKET).set(newAddOp.get(WebConnectorDefinition.REDIRECT_BINDING.getName())); addConnector.get(Constants.ENABLED).set(newAddOp.get(WebConnectorDefinition.ENABLED.getName())); addConnector.get(Constants.RESOLVE_PEER_ADDRESS).set(newAddOp.get(WebConnectorDefinition.ENABLE_LOOKUPS.getName())); addConnector.get(Constants.MAX_POST_SIZE).set(newAddOp.get(WebConnectorDefinition.MAX_POST_SIZE.getName())); addConnector.get(Constants.REDIRECT_SOCKET).set(newAddOp.get(WebConnectorDefinition.REDIRECT_BINDING.getName())); addConnector.get(Constants.MAX_CONNECTIONS).set(newAddOp.get(WebConnectorDefinition.MAX_CONNECTIONS.getName())); addConnector.get(Constants.MAX_BUFFERED_REQUEST_SIZE).set(newAddOp.get(WebConnectorDefinition.MAX_SAVE_POST_SIZE.getName())); addConnector.get(Constants.SECURE).set(newAddOp.get(WebConnectorDefinition.SECURE.getName())); if(newAddOp.hasDefined(WebConnectorDefinition.REDIRECT_PORT.getName())) { warnings.add(WebLogger.ROOT_LOGGER.couldNotMigrateResource(WebConnectorDefinition.REDIRECT_PORT.getName(), pathAddress(newAddOp.get(ADDRESS)))); } if(newAddOp.hasDefined(WebConnectorDefinition.PROXY_BINDING.getName())) { warnings.add(WebLogger.ROOT_LOGGER.couldNotMigrateResource(WebConnectorDefinition.PROXY_BINDING.getName(), pathAddress(newAddOp.get(ADDRESS)))); } if (newAddOp.hasDefined(WebConnectorDefinition.EXECUTOR.getName())) { //TODO: migrate executor to worker warnings.add(WebLogger.ROOT_LOGGER.couldNotMigrateResource(WebConnectorDefinition.EXECUTOR.getName(), pathAddress(newAddOp.get(ADDRESS)))); } newAddOperations.put(pathAddress(newAddOp.get(OP_ADDR)), addConnector); } private String translateVerifyClient(String s, List<String> warnings) { switch(s) { case "optionalNoCA": case "optional": { return "REQUESTED"; } case "require" : { return "REQUIRED"; } case "none": { return "NOT_REQUESTED"; } case "true": { return "REQUIRED"; } case "false": { return "NOT_REQUESTED"; } default: { warnings.add(WebLogger.ROOT_LOGGER.couldNotTranslateVerifyClient(s)); return null; } } } private void migrateMimeMapping(Map<PathAddress, ModelNode> newAddOperations, ModelNode newAddOp) { migrateWelcomeFiles(newAddOperations, newAddOp); ModelNode mime = newAddOp.get("mime-mapping"); if (mime.isDefined()) { for (ModelNode w : mime.asList()) { PathAddress wa = pathAddress(pathAddress(UndertowExtension.SUBSYSTEM_PATH, pathElement(Constants.SERVLET_CONTAINER, "default"), pathElement(Constants.MIME_MAPPING, w.asProperty().getName()))); ModelNode add = createAddOperation(wa); add.get(Constants.VALUE).set(w.asProperty().getValue()); newAddOperations.put(wa, add); } } } private void migrateWelcomeFiles(Map<PathAddress, ModelNode> newAddOperations, ModelNode newAddOp) { ModelNode welcome = newAddOp.get("welcome-file"); if (welcome.isDefined()) { for (ModelNode w : welcome.asList()) { PathAddress wa = pathAddress(pathAddress(UndertowExtension.SUBSYSTEM_PATH, pathElement(Constants.SERVLET_CONTAINER, "default"), pathElement(Constants.WELCOME_FILE, w.asString()))); ModelNode add = createAddOperation(wa); newAddOperations.put(wa, add); } } } private void migrateJSPConfig(Map<PathAddress, ModelNode> newAddOperations, ModelNode newAddOp) { newAddOp.get(ADDRESS).set(pathAddress(UndertowExtension.SUBSYSTEM_PATH, pathElement(Constants.SERVLET_CONTAINER, "default"), UndertowExtension.PATH_JSP).toModelNode()); newAddOperations.put(pathAddress(newAddOp.get(OP_ADDR)), newAddOp); } private void migrateSubsystem(Map<PathAddress, ModelNode> newAddOperations, ModelNode newAddOp) { newAddOp.get(ADDRESS).set(pathAddress(pathElement(SUBSYSTEM, UndertowExtension.SUBSYSTEM_NAME)).toModelNode()); PathAddress address = pathAddress(newAddOp.get(OP_ADDR)); newAddOperations.put(address, createAddOperation(address)); } private void describeLegacyWebResources(OperationContext context, ModelNode legacyModelDescription) { ModelNode describeLegacySubsystem = createOperation(GenericSubsystemDescribeHandler.DEFINITION, context.getCurrentAddress()); context.addStep(legacyModelDescription, describeLegacySubsystem, GenericSubsystemDescribeHandler.INSTANCE, MODEL, true); } private static ModelNode findResource(PathAddress address, ModelNode legacyAddOps) { for (ModelNode legacyAddOp : legacyAddOps.get(RESULT).asList()) { final PathAddress la = pathAddress(legacyAddOp.get(ADDRESS)); if (la.equals(address)) { return legacyAddOp; } } return null; } private class SSLInformation { final String realmName; final ModelNode verifyClient; final ModelNode sessionCacheSize; final ModelNode sessionTimeout; final ModelNode sslProtocol; final ModelNode cipherSuites; private SSLInformation(String realmName, ModelNode verifyClient, ModelNode sessionCacheSize, ModelNode sessionTimeout, ModelNode sslProtocol, ModelNode cipherSuites) { this.realmName = realmName; this.verifyClient = verifyClient; this.sessionCacheSize = sessionCacheSize; this.sessionTimeout = sessionTimeout; this.sslProtocol = sslProtocol; this.cipherSuites = cipherSuites; } } }
package com.handmark.pulltorefresh.library; import android.graphics.drawable.Drawable; import android.view.View; import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode; import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener; import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2; public interface IPullToRefresh<T extends View> { /** * Get the mode that this view is currently in. This is only really useful * when using <code>Mode.BOTH</code>. * * @return Mode that the view is currently in */ public Mode getCurrentMode(); /** * Returns whether the Touch Events are filtered or not. If true is * returned, then the View will only use touch events where the difference * in the Y-axis is greater than the difference in the X-axis. This means * that the View will not interfere when it is used in a horizontal * scrolling View (such as a ViewPager). * * @return boolean - true if the View is filtering Touch Events */ public boolean getFilterTouchEvents(); /** * Get the mode that this view has been set to. If this returns * <code>Mode.BOTH</code>, you can use <code>getCurrentMode()</code> to * check which mode the view is currently in * * @return Mode that the view has been set to */ public Mode getMode(); /** * Get the Wrapped Refreshable View. Anything returned here has already been * added to the content view. * * @return The View which is currently wrapped */ public T getRefreshableView(); /** * Get whether the 'Refreshing' View should be automatically shown when * refreshing. Returns true by default. * * @return - true if the Refreshing View will be show */ public boolean getShowViewWhileRefreshing(); /** * @deprecated Use the value from <code>getCurrentMode()</code> instead * @return true if the current mode is Mode.PULL_DOWN_TO_REFRESH */ public boolean hasPullFromTop(); /** * Returns whether the widget has disabled scrolling on the Refreshable View * while refreshing. * * @return true if the widget has disabled scrolling while refreshing */ public boolean isDisableScrollingWhileRefreshing(); /** * Gets whether Overscroll support is enabled. This is different to * Android's standard Overscroll support (the edge-glow) which is available * from GINGERBREAD onwards * * @return true - if both PullToRefresh-OverScroll and Android's inbuilt * OverScroll are enabled */ public boolean isPullToRefreshOverScrollEnabled(); /** * Whether Pull-to-Refresh is enabled * * @return enabled */ public boolean isPullToRefreshEnabled(); /** * Returns whether the Widget is currently in the Refreshing mState * * @return true if the Widget is currently refreshing */ public boolean isRefreshing(); /** * Mark the current Refresh as complete. Will Reset the UI and hide the * Refreshing View */ public void onRefreshComplete(); /** * By default the Widget disabled scrolling on the Refreshable View while * refreshing. This method can change this behaviour. * * @param disableScrollingWhileRefreshing * - true if you want to disable scrolling while refreshing */ public void setDisableScrollingWhileRefreshing(boolean disableScrollingWhileRefreshing); /** * Set the Touch Events to be filtered or not. If set to true, then the View * will only use touch events where the difference in the Y-axis is greater * than the difference in the X-axis. This means that the View will not * interfere when it is used in a horizontal scrolling View (such as a * ViewPager), but will restrict which types of finger scrolls will trigger * the View. * * @param filterEvents * - true if you want to filter Touch Events. Default is true. */ public void setFilterTouchEvents(boolean filterEvents); /** * Set the Last Updated Text. This displayed under the main label when * Pulling * * @param label * - Label to set */ public void setLastUpdatedLabel(CharSequence label); /** * Set the drawable used in the loading layout. This is the same as calling * <code>setLoadingDrawable(drawable, Mode.BOTH)</code> * * @param drawable * - Drawable to display */ public void setLoadingDrawable(Drawable drawable); /** * Set the drawable used in the loading layout. * * @param drawable * - Drawable to display * @param mode * - Controls which Header/Footer Views will be updated. * <code>Mode.BOTH</code> will update all available, other values * will update the relevant View. */ public void setLoadingDrawable(Drawable drawable, Mode mode); /** * Set the mode of Pull-to-Refresh that this view will use. * * @param mode * - Mode to set the View to */ public void setMode(Mode mode); /** * Set OnRefreshListener for the Widget * * @param listener * - Listener to be used when the Widget is set to Refresh */ public void setOnRefreshListener(OnRefreshListener<T> listener); /** * Set OnRefreshListener for the Widget * * @param listener * - Listener to be used when the Widget is set to Refresh */ public void setOnRefreshListener(OnRefreshListener2<T> listener); /** * Sets whether Overscroll support is enabled. This is different to * Android's standard Overscroll support (the edge-glow). This setting only * takes effect when running on device with Android v2.3 or greater. * * @param enabled * - true if you want Overscroll enabled */ public void setPullToRefreshOverScrollEnabled(boolean enabled); /** * Set Text to show when the Widget is being Pulled * <code>setPullLabel(releaseLabel, Mode.BOTH)</code> * * @param releaseLabel * - String to display */ public void setPullLabel(String pullLabel); /** * Set Text to show when the Widget is being Pulled * * @param pullLabel * - String to display * @param mode * - Controls which Header/Footer Views will be updated. * <code>Mode.BOTH</code> will update all available, other values * will update the relevant View. */ public void setPullLabel(String pullLabel, Mode mode); /** * @deprecated This simple calls setMode with an appropriate mode based on * the passed value. * * @param enable * Whether Pull-To-Refresh should be used */ public void setPullToRefreshEnabled(boolean enable); public void setRefreshing(); /** * Sets the Widget to be in the refresh state. The UI will be updated to * show the 'Refreshing' view. * * @param doScroll * - true if you want to force a scroll to the Refreshing view. */ public void setRefreshing(boolean doScroll); /** * Set Text to show when the Widget is refreshing * <code>setRefreshingLabel(releaseLabel, Mode.BOTH)</code> * * @param releaseLabel * - String to display */ public void setRefreshingLabel(String refreshingLabel); /** * Set Text to show when the Widget is refreshing * * @param refreshingLabel * - String to display * @param mode * - Controls which Header/Footer Views will be updated. * <code>Mode.BOTH</code> will update all available, other values * will update the relevant View. */ public void setRefreshingLabel(String refreshingLabel, Mode mode); /** * Set Text to show when the Widget is being pulled, and will refresh when * released. This is the same as calling * <code>setReleaseLabel(releaseLabel, Mode.BOTH)</code> * * @param releaseLabel * - String to display */ public void setReleaseLabel(String releaseLabel); /** * Set Text to show when the Widget is being pulled, and will refresh when * released * * @param releaseLabel * - String to display * @param mode * - Controls which Header/Footer Views will be updated. * <code>Mode.BOTH</code> will update all available, other values * will update the relevant View. */ public void setReleaseLabel(String releaseLabel, Mode mode); /** * A mutator to enable/disable whether the 'Refreshing' View should be * automatically shown when refreshing. * * @param showView */ public void setShowViewWhileRefreshing(boolean showView); }
package com.facebook.litho.widget; import android.content.res.ColorStateList; import android.content.res.TypedArray; import android.graphics.Color; import android.graphics.Path; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Typeface; import android.os.Build; import android.support.v4.text.TextDirectionHeuristicCompat; import android.support.v4.text.TextDirectionHeuristicsCompat; import android.support.v4.util.Pools.SynchronizedPool; import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat; import android.text.Layout; import android.text.Layout.Alignment; import android.text.Spanned; import android.text.TextPaint; import android.text.TextUtils; import android.text.TextUtils.TruncateAt; import android.text.style.ClickableSpan; import android.util.Log; import com.facebook.R; import com.facebook.litho.ComponentContext; import com.facebook.litho.ComponentLayout; import com.facebook.litho.ComponentsLogger; import com.facebook.litho.config.ComponentsConfiguration; import com.facebook.litho.Output; import com.facebook.litho.Size; import com.facebook.litho.SizeSpec; import com.facebook.litho.annotations.FromBoundsDefined; import com.facebook.litho.annotations.FromMeasure; import com.facebook.litho.annotations.GetExtraAccessibilityNodeAt; import com.facebook.litho.annotations.GetExtraAccessibilityNodesCount; import com.facebook.litho.annotations.MountSpec; import com.facebook.litho.annotations.OnBoundsDefined; import com.facebook.litho.annotations.OnCreateMountContent; import com.facebook.litho.annotations.OnLoadStyle; import com.facebook.litho.annotations.OnMeasure; import com.facebook.litho.annotations.OnMount; import com.facebook.litho.annotations.OnPopulateAccessibilityNode; import com.facebook.litho.annotations.OnPopulateExtraAccessibilityNode; import com.facebook.litho.annotations.OnUnmount; import com.facebook.litho.annotations.Prop; import com.facebook.litho.annotations.PropDefault; import com.facebook.litho.annotations.ResType; import com.facebook.yoga.YogaDirection; import com.facebook.fbui.textlayoutbuilder.TextLayoutBuilder; import com.facebook.fbui.textlayoutbuilder.util.LayoutMeasureUtil; import com.facebook.widget.accessibility.delegates.AccessibleClickableSpan; import static android.support.v4.widget.ExploreByTouchHelper.INVALID_ID; import static android.text.Layout.Alignment.ALIGN_NORMAL; import static com.facebook.litho.SizeSpec.AT_MOST; import static com.facebook.litho.SizeSpec.EXACTLY; import static com.facebook.litho.SizeSpec.UNSPECIFIED; import static com.facebook.litho.annotations.ResType.BOOL; import static com.facebook.litho.annotations.ResType.STRING; @MountSpec(isPureRender = true, shouldUseDisplayList = true, poolSize = 30) class TextSpec { private static final Alignment[] ALIGNMENT = Alignment.values(); private static final TruncateAt[] TRUNCATE_AT = TruncateAt.values(); private static final Typeface DEFAULT_TYPEFACE = Typeface.DEFAULT; private static final int DEFAULT_COLOR = 0; private static final int DEFAULT_EMS = -1; private static final int DEFAULT_MIN_WIDTH = 0; private static final int DEFAULT_MAX_WIDTH = Integer.MAX_VALUE; private static final int[][] DEFAULT_TEXT_COLOR_STATE_LIST_STATES = {{0}}; private static final int[] DEFAULT_TEXT_COLOR_STATE_LIST_COLORS = {Color.BLACK}; private static final String TAG = "TextSpec"; @PropDefault protected static final int minLines = Integer.MIN_VALUE; @PropDefault protected static final int maxLines = Integer.MAX_VALUE; @PropDefault protected static final int minEms = DEFAULT_EMS; @PropDefault protected static final int maxEms = DEFAULT_EMS; @PropDefault protected static final int minWidth = DEFAULT_MIN_WIDTH; @PropDefault protected static final int maxWidth = DEFAULT_MAX_WIDTH; @PropDefault protected static final int shadowColor = Color.GRAY; @PropDefault protected static final int textColor = DEFAULT_COLOR; @PropDefault protected static final int linkColor = DEFAULT_COLOR; @PropDefault protected static final ColorStateList textColorStateList = new ColorStateList( DEFAULT_TEXT_COLOR_STATE_LIST_STATES, DEFAULT_TEXT_COLOR_STATE_LIST_COLORS); @PropDefault protected static final int textSize = 13; @PropDefault protected static final int textStyle = DEFAULT_TYPEFACE.getStyle(); @PropDefault protected static final Typeface typeface = DEFAULT_TYPEFACE; @PropDefault protected static final float spacingMultiplier = 1.0f; @PropDefault protected static final VerticalGravity verticalGravity = VerticalGravity.TOP; @PropDefault protected static final boolean glyphWarming = false; @PropDefault protected static final boolean shouldIncludeFontPadding = true; @PropDefault protected static final Alignment textAlignment = ALIGN_NORMAL; private static final Path sTempPath = new Path(); private static final Rect sTempRect = new Rect(); private static final RectF sTempRectF = new RectF(); private static final SynchronizedPool<TextLayoutBuilder> sTextLayoutBuilderPool = new SynchronizedPool<>(2); @OnLoadStyle static void onLoadStyle( ComponentContext c, Output<TruncateAt> ellipsize, Output<Boolean> shouldIncludeFontPadding, Output<Float> spacingMultiplier, Output<Integer> minLines, Output<Integer> maxLines, Output<Integer> minEms, Output<Integer> maxEms, Output<Integer> minWidth, Output<Integer> maxWidth, Output<Boolean> isSingleLine, Output<CharSequence> text, Output<ColorStateList> textColorStateList, Output<Integer> linkColor, Output<Integer> highlightColor, Output<Integer> textSize, Output<Alignment> textAlignment, Output<Integer> textStyle, Output<Float> shadowRadius, Output<Float> shadowDx, Output<Float> shadowDy, Output<Integer> shadowColor) { final TypedArray a = c.obtainStyledAttributes(R.styleable.Text, 0); for (int i = 0, size = a.getIndexCount(); i < size; i++) { final int attr = a.getIndex(i); if (attr == R.styleable.Text_android_text) { text.set(a.getString(attr)); } else if (attr == R.styleable.Text_android_textColor) { textColorStateList.set(a.getColorStateList(attr)); } else if (attr == R.styleable.Text_android_textSize) { textSize.set(a.getDimensionPixelSize(attr, 0)); } else if (attr == R.styleable.Text_android_ellipsize) { final int index = a.getInteger(attr, 0); if (index > 0) { ellipsize.set(TRUNCATE_AT[index - 1]); } } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && attr == R.styleable.Text_android_textAlignment) { textAlignment.set(ALIGNMENT[a.getInteger(attr, 0)]); } else if (attr == R.styleable.Text_android_includeFontPadding) { shouldIncludeFontPadding.set(a.getBoolean(attr, false)); } else if (attr == R.styleable.Text_android_minLines) { minLines.set(a.getInteger(attr, -1)); } else if (attr == R.styleable.Text_android_maxLines) { maxLines.set(a.getInteger(attr, -1)); } else if (attr == R.styleable.Text_android_singleLine) { isSingleLine.set(a.getBoolean(attr, false)); } else if (attr == R.styleable.Text_android_textColorLink) { linkColor.set(a.getColor(attr, 0)); } else if (attr == R.styleable.Text_android_textColorHighlight) { highlightColor.set(a.getColor(attr, 0)); } else if (attr == R.styleable.Text_android_textStyle) { textStyle.set(a.getInteger(attr, 0)); } else if (attr == R.styleable.Text_android_lineSpacingMultiplier) { spacingMultiplier.set(a.getFloat(attr, 0)); } else if (attr == R.styleable.Text_android_shadowDx) { shadowDx.set(a.getFloat(attr, 0)); } else if (attr == R.styleable.Text_android_shadowDy) { shadowDy.set(a.getFloat(attr, 0)); } else if (attr == R.styleable.Text_android_shadowRadius) { shadowRadius.set(a.getFloat(attr, 0)); } else if (attr == R.styleable.Text_android_shadowColor) { shadowColor.set(a.getColor(attr, 0)); } else if (attr == R.styleable.Text_android_minEms) { minEms.set(a.getInteger(attr, DEFAULT_EMS)); } else if (attr == R.styleable.Text_android_maxEms) { maxEms.set(a.getInteger(attr, DEFAULT_EMS)); } else if (attr == R.styleable.Text_android_minWidth) { minWidth.set(a.getInteger(attr, DEFAULT_MIN_WIDTH)); } else if (attr == R.styleable.Text_android_maxWidth) { maxWidth.set(a.getInteger(attr, DEFAULT_MAX_WIDTH)); } } a.recycle(); } @OnMeasure static void onMeasure( ComponentContext context, ComponentLayout layout, int widthSpec, int heightSpec, Size size, @Prop(resType = ResType.STRING) CharSequence text, @Prop(optional = true) TruncateAt ellipsize, @Prop(optional = true, resType = ResType.BOOL) boolean shouldIncludeFontPadding, @Prop(optional = true, resType = ResType.INT) int minLines, @Prop(optional = true, resType = ResType.INT) int maxLines, @Prop(optional = true, resType = ResType.INT) int minEms, @Prop(optional = true, resType = ResType.INT) int maxEms, @Prop(optional = true, resType = ResType.INT) int minWidth, @Prop(optional = true, resType = ResType.INT) int maxWidth, @Prop(optional = true, resType = ResType.DIMEN_OFFSET) float shadowRadius, @Prop(optional = true, resType = ResType.DIMEN_OFFSET) float shadowDx, @Prop(optional = true, resType = ResType.DIMEN_OFFSET) float shadowDy, @Prop(optional = true, resType = ResType.COLOR) int shadowColor, @Prop(optional = true, resType = ResType.BOOL) boolean isSingleLine, @Prop(optional = true, resType = ResType.COLOR) int textColor, @Prop(optional = true) ColorStateList textColorStateList, @Prop(optional = true, resType = ResType.COLOR) int linkColor, @Prop(optional = true, resType = ResType.DIMEN_TEXT) int textSize, @Prop(optional = true, resType = ResType.DIMEN_OFFSET) float extraSpacing, @Prop(optional = true, resType = ResType.FLOAT) float spacingMultiplier, @Prop(optional = true) int textStyle, @Prop(optional = true) Typeface typeface, @Prop(optional = true) Alignment textAlignment, @Prop(optional = true) boolean glyphWarming, @Prop(optional = true) TextDirectionHeuristicCompat textDirection, Output<Layout> measureLayout, Output<Integer> measuredWidth, Output<Integer> measuredHeight) { if (TextUtils.isEmpty(text)) { measureLayout.set(null); size.width = 0; size.height = 0; return; } Layout newLayout = createTextLayout( widthSpec, ellipsize, shouldIncludeFontPadding, maxLines, shadowRadius, shadowDx, shadowDy, shadowColor, isSingleLine, text, textColor, textColorStateList, linkColor, textSize, extraSpacing, spacingMultiplier, textStyle, typeface, textAlignment, glyphWarming, layout.getResolvedLayoutDirection(), minEms, maxEms, minWidth, maxWidth, textDirection); measureLayout.set(newLayout); size.width = SizeSpec.resolveSize(widthSpec, newLayout.getWidth()); // Adjust height according to the minimum number of lines. int preferredHeight = LayoutMeasureUtil.getHeight(newLayout); final int lineCount = newLayout.getLineCount(); if (lineCount < minLines) { final TextPaint paint = newLayout.getPaint(); final int lineHeight = Math.round(paint.getFontMetricsInt(null) * spacingMultiplier + extraSpacing); preferredHeight += lineHeight * (minLines - lineCount); } size.height = SizeSpec.resolveSize(heightSpec, preferredHeight); // Some devices seem to be returning negative sizes in some cases. if (size.width < 0 || size.height < 0) { size.width = Math.max(size.width, 0); size.height = Math.max(size.height, 0); final ComponentsLogger logger = context.getLogger(); if (logger != null) { logger.softError("Text layout measured to less than 0 pixels"); } } measuredWidth.set(size.width); measuredHeight.set(size.height); } private static Layout createTextLayout( int widthSpec, TruncateAt ellipsize, boolean shouldIncludeFontPadding, int maxLines, float shadowRadius, float shadowDx, float shadowDy, int shadowColor, boolean isSingleLine, CharSequence text, int textColor, ColorStateList textColorStateList, int linkColor, int textSize, float extraSpacing, float spacingMultiplier, int textStyle, Typeface typeface, Alignment textAlignment, boolean glyphWarming, YogaDirection layoutDirection, int minEms, int maxEms, int minWidth, int maxWidth, TextDirectionHeuristicCompat textDirection) { Layout newLayout; TextLayoutBuilder layoutBuilder = sTextLayoutBuilderPool.acquire(); if (layoutBuilder == null) { layoutBuilder = new TextLayoutBuilder(); layoutBuilder.setShouldCacheLayout(false); } final @TextLayoutBuilder.MeasureMode int textMeasureMode; switch (SizeSpec.getMode(widthSpec)) { case UNSPECIFIED: textMeasureMode = TextLayoutBuilder.MEASURE_MODE_UNSPECIFIED; break; case EXACTLY: textMeasureMode = TextLayoutBuilder.MEASURE_MODE_EXACTLY; break; case AT_MOST: textMeasureMode = TextLayoutBuilder.MEASURE_MODE_AT_MOST; break; default: throw new IllegalStateException("Unexpected size mode: " + SizeSpec.getMode(widthSpec)); } layoutBuilder .setEllipsize(ellipsize) .setMaxLines(maxLines) .setShadowLayer(shadowRadius, shadowDx, shadowDy, shadowColor) .setSingleLine(isSingleLine) .setText(text) .setTextSize(textSize) .setWidth( SizeSpec.getSize(widthSpec), textMeasureMode); if (minEms != DEFAULT_EMS) { layoutBuilder.setMinEms(minEms); } else { layoutBuilder.setMinWidth(minWidth); } if (maxEms != DEFAULT_EMS) { layoutBuilder.setMaxEms(maxEms); } else { layoutBuilder.setMaxWidth(maxWidth); } if (textColor != 0) { layoutBuilder.setTextColor(textColor); } else { layoutBuilder.setTextColor(textColorStateList); } if (typeface != DEFAULT_TYPEFACE) { layoutBuilder.setTypeface(typeface); } else { layoutBuilder.setTextStyle(textStyle); } if (textDirection != null) { layoutBuilder.setTextDirection(textDirection); } else { layoutBuilder.setTextDirection(layoutDirection == YogaDirection.RTL ? TextDirectionHeuristicsCompat.FIRSTSTRONG_RTL : TextDirectionHeuristicsCompat.FIRSTSTRONG_LTR); } layoutBuilder.setIncludeFontPadding(shouldIncludeFontPadding); layoutBuilder.setTextSpacingExtra(extraSpacing); layoutBuilder.setTextSpacingMultiplier(spacingMultiplier); layoutBuilder.setAlignment(textAlignment); layoutBuilder.setLinkColor(linkColor); newLayout = layoutBuilder.build(); layoutBuilder.setText(null); sTextLayoutBuilderPool.release(layoutBuilder); if (glyphWarming && !ComponentsConfiguration.shouldGenerateDisplayLists) { GlyphWarmer.getInstance().warmLayout(newLayout); } return newLayout; } @OnBoundsDefined static void onBoundsDefined( ComponentContext c, ComponentLayout layout, @Prop(resType = ResType.STRING) CharSequence text, @Prop(optional = true) TruncateAt ellipsize, @Prop(optional = true, resType = ResType.BOOL) boolean shouldIncludeFontPadding, @Prop(optional = true, resType = ResType.INT) int maxLines, @Prop(optional = true, resType = ResType.INT) int minEms, @Prop(optional = true, resType = ResType.INT) int maxEms, @Prop(optional = true, resType = ResType.INT) int minWidth, @Prop(optional = true, resType = ResType.INT) int maxWidth, @Prop(optional = true, resType = ResType.DIMEN_OFFSET) float shadowRadius, @Prop(optional = true, resType = ResType.DIMEN_OFFSET) float shadowDx, @Prop(optional = true, resType = ResType.DIMEN_OFFSET) float shadowDy, @Prop(optional = true, resType = ResType.COLOR) int shadowColor, @Prop(optional = true, resType = ResType.BOOL) boolean isSingleLine, @Prop(optional = true, resType = ResType.COLOR) int textColor, @Prop(optional = true) ColorStateList textColorStateList, @Prop(optional = true, resType = ResType.COLOR) int linkColor, @Prop(optional = true, resType = ResType.DIMEN_TEXT) int textSize, @Prop(optional = true, resType = ResType.DIMEN_OFFSET) float extraSpacing, @Prop(optional = true, resType = ResType.FLOAT) float spacingMultiplier, @Prop(optional = true) VerticalGravity verticalGravity, @Prop(optional = true) int textStyle, @Prop(optional = true) Typeface typeface, @Prop(optional = true) Alignment textAlignment, @Prop(optional = true) boolean glyphWarming, @Prop(optional = true) TextDirectionHeuristicCompat textDirection, @FromMeasure Layout measureLayout, @FromMeasure Integer measuredWidth, @FromMeasure Integer measuredHeight, Output<Layout> textLayout, Output<Float> textLayoutTranslationY, Output<ClickableSpan[]> clickableSpans) { if (TextUtils.isEmpty(text)) { return; } final float layoutWidth = layout.getWidth() - layout.getPaddingLeft() - layout.getPaddingRight(); final float layoutHeight = layout.getHeight() - layout.getPaddingTop() - layout.getPaddingBottom(); if (measureLayout != null && measuredWidth == layoutWidth && measuredHeight == layoutHeight) { textLayout.set(measureLayout); } else { if (measureLayout != null) { Log.w( TAG, "Remeasuring Text component. This is expensive: consider changing parent layout " + "so that double measurement is not necessary."); } textLayout.set( createTextLayout( SizeSpec.makeSizeSpec((int) layoutWidth, EXACTLY), ellipsize, shouldIncludeFontPadding, maxLines, shadowRadius, shadowDx, shadowDy, shadowColor, isSingleLine, text, textColor, textColorStateList, linkColor, textSize, extraSpacing, spacingMultiplier, textStyle, typeface, textAlignment, glyphWarming, layout.getResolvedLayoutDirection(), minEms, maxEms, minWidth, maxWidth, textDirection)); } final float textHeight = LayoutMeasureUtil.getHeight(textLayout.get()); switch (verticalGravity) { case CENTER: textLayoutTranslationY.set((layoutHeight - textHeight) / 2); break; case BOTTOM: textLayoutTranslationY.set(layoutHeight - textHeight); break; default: textLayoutTranslationY.set(0f); break; } if (text instanceof Spanned) { clickableSpans.set(((Spanned) text).getSpans( 0, text.length() - 1, ClickableSpan.class)); } } @OnCreateMountContent static TextDrawable onCreateMountContent(ComponentContext c) { return new TextDrawable(); } @OnMount static void onMount( ComponentContext c,
package org.multibit.hd.ui.languages; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.Lists; import org.bitcoinj.core.Address; import org.bitcoinj.core.Coin; import org.bitcoinj.protocols.payments.PaymentSession; import org.bitcoinj.uri.BitcoinURI; import org.multibit.hd.core.config.BitcoinConfiguration; import org.multibit.hd.core.config.Configurations; import org.multibit.hd.core.config.LanguageConfiguration; import org.multibit.hd.core.dto.PaymentSessionSummary; import org.multibit.hd.core.events.TransactionSeenEvent; import org.multibit.hd.core.utils.BitcoinSymbol; import org.multibit.hd.core.utils.Coins; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.math.BigDecimal; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.Locale; /** * <p>Utility to provide the following to controllers:</p> * <ul> * <li>Access to international formats for date/time and decimal data</li> * <li>Access to alert layouts in different languages</li> * </ul> * * @since 0.0.1 * */ public class Formats { private static final Logger log = LoggerFactory.getLogger(Formats.class); /** * The number of decimal places for showing the exchange rate depends on the bitcoin symbol used, with this offset */ public static final int EXCHANGE_RATE_DECIMAL_PLACES_OFFSET = 2; /** * <p>Provide a split representation for the Bitcoin balance display.</p> * <p>For example, 12345.6789 becomes "12,345.67", "89" </p> * <p>The amount will be adjusted by the symbolic multiplier from the current configuration</p> * * @param coin The amount in coins * @param languageConfiguration The language configuration to use as the basis for presentation * @param bitcoinConfiguration The Bitcoin configuration to use as the basis for the symbol * * @return The left [0] and right [1] components suitable for presentation as a balance with no symbolic decoration */ public static String[] formatCoinAsSymbolic( Coin coin, LanguageConfiguration languageConfiguration, BitcoinConfiguration bitcoinConfiguration ) { return formatCoinAsSymbolic(coin, languageConfiguration, bitcoinConfiguration, true); } /** * <p>Provide a split representation for the Bitcoin balance display.</p> * <p>For example, 123456789 in uBTC becomes "1,234,567.", "89" </p> * <p>The amount will be adjusted by the symbolic multiplier from the current configuration</p> * * @param coin The amount in coins * @param languageConfiguration The language configuration to use as the basis for presentation * @param bitcoinConfiguration The Bitcoin configuration to use as the basis for the symbol * @param showNegative If true, show '-' for negative numbers * * @return The left [0] and right [1] components suitable for presentation as a balance with no symbolic decoration */ public static String[] formatCoinAsSymbolic( Coin coin, LanguageConfiguration languageConfiguration, BitcoinConfiguration bitcoinConfiguration, boolean showNegative ) { Preconditions.checkNotNull(coin, "'coin' must be present"); Preconditions.checkNotNull(languageConfiguration, "'languageConfiguration' must be present"); Preconditions.checkNotNull(bitcoinConfiguration, "'bitcoinConfiguration' must be present"); Locale currentLocale = languageConfiguration.getLocale(); BitcoinSymbol bitcoinSymbol = BitcoinSymbol.of(bitcoinConfiguration.getBitcoinSymbol()); DecimalFormatSymbols dfs = configureDecimalFormatSymbols(bitcoinConfiguration, currentLocale); DecimalFormat localFormat = configureBitcoinDecimalFormat(dfs, bitcoinSymbol, showNegative); // Apply formatting to the symbolic amount String formattedAmount = localFormat.format(Coins.toSymbolicAmount(coin, bitcoinSymbol)); // The Satoshi symbol does not have decimals if (BitcoinSymbol.SATOSHI.equals(bitcoinSymbol)) { return new String[]{ formattedAmount, "" }; } // All other representations require a decimal int decimalIndex = formattedAmount.lastIndexOf(dfs.getDecimalSeparator()); if (decimalIndex == -1) { formattedAmount += dfs.getDecimalSeparator() + "00"; decimalIndex = formattedAmount.lastIndexOf(dfs.getDecimalSeparator()); } return new String[]{ formattedAmount.substring(0, decimalIndex + 3), // 12,345.67 (significant figures) formattedAmount.substring(decimalIndex + 3) // 89 (lesser figures truncated ) }; } /** * <p>Provide a single text representation for the Bitcoin balance display.</p> * <p>For example, 123456789 becomes "1,234,567.89 uBTC" or "uXBT 12,345.6789" </p> * <p>The amount will be adjusted by the symbolic multiplier from the current configuration</p> * * @param coin The amount in coins * @param languageConfiguration The language configuration to use as the basis for presentation * @param bitcoinConfiguration The Bitcoin configuration to use as the basis for the symbol * * @return The string suitable for presentation as a balance with symbol in a UTF-8 string */ public static String formatCoinAsSymbolicText( Coin coin, LanguageConfiguration languageConfiguration, BitcoinConfiguration bitcoinConfiguration ) { String[] formattedAmount = formatCoinAsSymbolic(coin, languageConfiguration, bitcoinConfiguration); String lineSymbol = BitcoinSymbol.of(bitcoinConfiguration.getBitcoinSymbol()).getTextSymbol(); // Convert to single text line with leading or trailing symbol if (bitcoinConfiguration.isCurrencySymbolLeading()) { return lineSymbol + "\u00a0" + formattedAmount[0] + formattedAmount[1]; } else { return formattedAmount[0] + formattedAmount[1] + "\u00a0" + lineSymbol; } } /** * <p>Provide a simple representation for a coin amount respecting decimal and grouping separators.</p> * <p>For example, 123456789 becomes "1,234,567.89" or "1.234.567,89" depending on configuration</p> * <p>The amount will be adjusted by the symbolic multiplier from the current configuration</p> * * @param coin The amount in coins * @param languageConfiguration The language configuration to use as the basis for presentation * @param bitcoinConfiguration The Bitcoin configuration to use as the basis for the symbol * * @return The string suitable for presentation as a balance without symbol in a UTF-8 string */ public static String formatCoinAmount(Coin coin, LanguageConfiguration languageConfiguration, BitcoinConfiguration bitcoinConfiguration) { String[] formattedAmount = formatCoinAsSymbolic(coin, languageConfiguration, bitcoinConfiguration); // Convert to single text line return formattedAmount[0] + formattedAmount[1]; } /** * <p>Provide a simple representation for a local currency amount.</p> * * @param amount The amount as a plain number (no multipliers) * @param locale The locale to use * @param bitcoinConfiguration The Bitcoin configuration to use as the basis for the symbol * @param showNegative True if the negative prefix is allowed * * @return The local currency representation with no symbolic decoration */ public static String formatLocalAmount(BigDecimal amount, Locale locale, BitcoinConfiguration bitcoinConfiguration, boolean showNegative) { if (amount == null) { return ""; } DecimalFormatSymbols dfs = configureDecimalFormatSymbols(bitcoinConfiguration, locale); DecimalFormat localFormat = configureLocalDecimalFormat(dfs, bitcoinConfiguration, showNegative); return localFormat.format(amount); } /** * <p>Convert the bitcoin exchange rate to use the unit of bitcoin being displayed</p> * <p>For example, 589.00 will become "0,589" if the unit of bitcoin is mB and the decimal separator is ","</p> * <p>The value passed into formatExchangeRate must be in "fiat currency per bitcoin" and NOT localised</p> * * @param exchangeRate The exchange rate in fiat per bitcoin * @param languageConfiguration The language configuration to use as the basis for presentation * @param bitcoinConfiguration The Bitcoin configuration to use as the basis for the symbol * * @return The localised string representing the bitcoin exchange rate in the display bitcoin unit */ public static String formatExchangeRate( Optional<String> exchangeRate, LanguageConfiguration languageConfiguration, BitcoinConfiguration bitcoinConfiguration ) { Preconditions.checkNotNull(exchangeRate, "'exchangeRate' must be non null"); Preconditions.checkState(exchangeRate.isPresent(), "'exchangeRate' must be present"); Preconditions.checkNotNull(languageConfiguration, "'languageConfiguration' must be present"); Preconditions.checkNotNull(bitcoinConfiguration, "'bitcoinConfiguration' must be present"); BigDecimal exchangeRateBigDecimal = new BigDecimal(exchangeRate.get()); // Correct for non unitary bitcoin display units e.g 567 USD per BTCis identical to 0.567 USD per mBTC BigDecimal correctedExchangeRateBigDecimal = exchangeRateBigDecimal.divide(BitcoinSymbol.current().multiplier()); Locale currentLocale = languageConfiguration.getLocale(); DecimalFormatSymbols dfs = configureDecimalFormatSymbols(bitcoinConfiguration, currentLocale); DecimalFormat localFormat = configureLocalDecimalFormat(dfs, bitcoinConfiguration, false); localFormat.setMinimumFractionDigits(Formats.EXCHANGE_RATE_DECIMAL_PLACES_OFFSET + (int)Math.log10(BitcoinSymbol.current().multiplier().doubleValue())); return localFormat.format(correctedExchangeRateBigDecimal); } /** * @param dfs The decimal format symbols * * @return A decimal format suitable for Bitcoin balance representation */ private static DecimalFormat configureBitcoinDecimalFormat(DecimalFormatSymbols dfs, BitcoinSymbol bitcoinSymbol, boolean showNegative) { DecimalFormat format = new DecimalFormat(); format.setDecimalFormatSymbols(dfs); format.setMaximumIntegerDigits(16); format.setMinimumIntegerDigits(1); format.setMaximumFractionDigits(bitcoinSymbol.decimalPlaces()); format.setMinimumFractionDigits(bitcoinSymbol.decimalPlaces()); format.setDecimalSeparatorAlwaysShown(false); if (showNegative) { format.setNegativePrefix("-"); } else { format.setNegativePrefix(""); } return format; } /** * @param bitcoinConfiguration The Bitcoin configuration * @param currentLocale The current locale * * @return The decimal format symbols to use based on the configuration and locale */ private static DecimalFormatSymbols configureDecimalFormatSymbols(BitcoinConfiguration bitcoinConfiguration, Locale currentLocale) { DecimalFormatSymbols dfs = new DecimalFormatSymbols(currentLocale); dfs.setDecimalSeparator(bitcoinConfiguration.getDecimalSeparator().charAt(0)); dfs.setGroupingSeparator(bitcoinConfiguration.getGroupingSeparator().charAt(0)); return dfs; } /** * @param dfs The decimal format symbols * @param bitcoinConfiguration The Bitcoin configuration to use * @param showNegative True if the negative prefix is allowed * * @return A decimal format suitable for local currency balance representation */ private static DecimalFormat configureLocalDecimalFormat( DecimalFormatSymbols dfs, BitcoinConfiguration bitcoinConfiguration, boolean showNegative ) { DecimalFormat format = new DecimalFormat(); format.setDecimalFormatSymbols(dfs); format.setMinimumIntegerDigits(1); format.setMaximumFractionDigits(bitcoinConfiguration.getLocalDecimalPlaces()); format.setMinimumFractionDigits(bitcoinConfiguration.getLocalDecimalPlaces()); format.setDecimalSeparatorAlwaysShown(true); if (showNegative) { format.setNegativePrefix("-"); } else { format.setNegativePrefix(""); } return format; } /** * @param event The "transaction seen" event * * @return A String suitably formatted for presentation as an alert message */ public static String formatAlertMessage(TransactionSeenEvent event) { // Decode the "transaction seen" event final Coin amount = event.getAmount(); final Coin modulusAmount; if (amount.compareTo(Coin.ZERO) >= 0) { modulusAmount = amount; } else { modulusAmount = amount.negate(); } // Create a suitable representation for inline text (no icon) final String messageAmount = Formats.formatCoinAsSymbolicText( modulusAmount, Configurations.currentConfiguration.getLanguage(), Configurations.currentConfiguration.getBitcoin() ); // Construct a suitable alert message if (amount.compareTo(Coin.ZERO) >= 0) { // Positive or zero amount, this is a receive return Languages.safeText(MessageKey.PAYMENT_RECEIVED_ALERT, messageAmount); } else { // Negative amount, this is a send (probably from a wallet clone elsewhere) return Languages.safeText(MessageKey.PAYMENT_SENT_ALERT, messageAmount); } } /** * @param bitcoinURI The Bitcoin URI * * @return A String suitably formatted for presentation as an alert message */ public static Optional<String> formatAlertMessage(BitcoinURI bitcoinURI) { Optional<String> alertMessage = Optional.absent(); // Decode the Bitcoin URI Optional<Address> address = Optional.fromNullable(bitcoinURI.getAddress()); Optional<Coin> amount = Optional.fromNullable(bitcoinURI.getAmount()); // Truncate the label field to avoid overrun on the display // (35+ overruns label + address + amount in mB + alert count at min width) // Send Bitcoin confirm wizard will fill in the complete details later Optional<String> label; if (Strings.isNullOrEmpty(bitcoinURI.getLabel())) { label = Optional.absent(); } else { label = Optional.of(Languages.truncatedList(Lists.newArrayList(bitcoinURI.getLabel()), 35)); } // Only proceed if we have an address if (address.isPresent()) { final String messageAmount; if (amount.isPresent()) { // Create a suitable representation for inline text (no icon) messageAmount = Formats.formatCoinAsSymbolicText( amount.get(), Configurations.currentConfiguration.getLanguage(), Configurations.currentConfiguration.getBitcoin() ); } else { messageAmount = Languages.safeText(MessageKey.NOT_AVAILABLE); } // Ensure we truncate the label if present String truncatedLabel = Languages.truncatedList(Lists.newArrayList(label.or(Languages.safeText(MessageKey.NOT_AVAILABLE))), 35); // Construct a suitable alert message alertMessage = Optional.of(Languages.safeText(MessageKey.BITCOIN_URI_ALERT, truncatedLabel, address.get().toString(), messageAmount)); } return alertMessage; } /** * @param paymentSessionSummary The payment session summary * * @return A String suitably formatted for presentation as an alert message */ public static Optional<String> formatAlertMessage(PaymentSessionSummary paymentSessionSummary) { if (!paymentSessionSummary.getPaymentSession().isPresent()) { // Construct a suitable alert message return Optional.of(Languages.safeText( paymentSessionSummary.getMessageKey(), paymentSessionSummary.getMessageData() )); } final boolean isTrusted; // Decode the payment session summary switch (paymentSessionSummary.getStatus()) { case TRUSTED: isTrusted = true; break; case UNTRUSTED: isTrusted = false; break; case DOWN: // Fall through to error case ERROR: // Construct a suitable alert message return Optional.of(Languages.safeText( MessageKey.PAYMENT_PROTOCOL_ERROR_ALERT, paymentSessionSummary.getMessageData() )); default: log.error("Unknown payment session status: {}", paymentSessionSummary.getStatus()); return Optional.absent(); } // Extract merchant information (payment session must be present) PaymentSession paymentSession = paymentSessionSummary.getPaymentSession().get(); Optional<Coin> amount = Optional.fromNullable(paymentSession.getValue()); // We do not truncate here since it is needed for the history // The UI will handle truncation String label = paymentSession.getMemo(); if (Strings.isNullOrEmpty(label)) { label = Languages.safeText(MessageKey.NOT_AVAILABLE); } Optional<String> alertMessage = Optional.absent(); // Only proceed if we have outputs if (!paymentSession.getOutputs().isEmpty()) { final String messageAmount; if (amount.isPresent()) { // Create a suitable representation for inline text (no icon) messageAmount = Formats.formatCoinAsSymbolicText( amount.get(), Configurations.currentConfiguration.getLanguage(), Configurations.currentConfiguration.getBitcoin() ); } else { messageAmount = Languages.safeText(MessageKey.NOT_AVAILABLE); } // Construct a suitable alert message MessageKey messageKey = isTrusted? MessageKey.PAYMENT_PROTOCOL_TRUSTED_ALERT : MessageKey.PAYMENT_PROTOCOL_UNTRUSTED_ALERT; alertMessage = Optional.of(Languages.safeText( messageKey, label, messageAmount )); } return alertMessage; } }
package com.github.dreamhead.moco; import com.google.common.eventbus.Subscribe; public interface MocoMonitor { @Subscribe void onMessageArrived(Request request); @Subscribe void onException(Throwable t); @Subscribe void onMessageLeave(Response response); @Subscribe void onUnexpectedMessage(Request request); }
package org.vrjuggler.vrjconfig.ui; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Point; import java.awt.event.*; import javax.swing.*; import javax.swing.event.EventListenerList; import org.vrjuggler.vrjconfig.ui.placer.*; /** * Allows the user to move displays about using Drag-and-Drop semantics. Such * a panel is useful for allowing the user to specify where simulator windows * should be placed and how they should be sized. * <p> * Displays placed within this panel are moveable using the mouse. */ public class Placer extends JPanel { /** * Whether displays may be resized. */ private boolean allowResize = true; /** * Whether displays may be move. */ private boolean allowMove = true; /** * The index of the currently selected object, -1 if nothing selected. */ private transient int selectedIndex = -1; /** * The position of the last mouse event. */ private transient Point lastMouse = null; /** * The data model for this placer. */ private PlacerModel model = null; /** * The renderer for this placer. */ private PlacerRenderer renderer = null; /** * The pane used to render placer renderer components. */ private CellRendererPane rendererPane = new CellRendererPane(); /** * The foreground color for selected items. */ private Color selectionForeground = Color.gray; /** * The background color for selected items. */ private Color selectionBackground = Color.blue; /** * All listeners interested in this placer. */ private EventListenerList listeners = new EventListenerList(); /** * Handler for when the model changes. */ private PlacerModelHandler modelHandler = new PlacerModelHandler(); /** * Creates a new placer with a default model. */ public Placer() { this(new AbstractPlacerModel() { public Object getElement(int idx) { return null; } public Object getElementAt(Point pt) { return null; } public int getIndexOfElementAt(Point pt) { return -1; } public Dimension getSizeOf(int idx) { return new Dimension(0,0); } public void setSizeOf(int idx, Dimension d) { } public Point getLocationOf(int idx) { return new Point(0,0); } public void setLocationOf(int idx, Point pt) { } public void moveToFront(int idx) { } public int getSize() { return 0; } }); } /** * Create a new Placer with the given data model. */ public Placer(PlacerModel model) { // init the model if (model == null) { throw new IllegalArgumentException("model can not be null"); } this.model = model; // init the renderer renderer = new DefaultPlacerRenderer(); try { jbInit(); } catch(Exception e) { e.printStackTrace(); } } /** * Sets the data model to use with this placer. */ public void setModel(PlacerModel model) { if (model == null) { throw new IllegalArgumentException("model can not be null"); } PlacerModel oldValue = this.model; oldValue.removePlacerModelListener(modelHandler); this.model = model; this.model.addPlacerModelListener(modelHandler); firePropertyChange("model", oldValue, model); } /** * Gets the data model used with this placer. */ public PlacerModel getModel() { return model; } /** * Sets the renderer to use with this placer. */ public void setRenderer(PlacerRenderer renderer) { if (renderer == null) { throw new IllegalArgumentException("renderer can not be null"); } PlacerRenderer oldValue = this.renderer; this.renderer = renderer; System.out.println("Set renderer to: "+this.renderer); firePropertyChange("renderer", oldValue, renderer); } /** * Gets the renderer used with this placer. */ public PlacerRenderer getRenderer() { return renderer; } /** * Sets whether displays may be resized. */ public void setAllowResize(boolean allowResize) { this.allowResize = allowResize; } /** * Gets whether displays may be resized. */ public boolean getAllowResize() { return allowResize; } /** * Sets whether displays may be moved. */ public void setAllowMove(boolean allowMove) { this.allowMove = allowMove; } /** * Gets whether displays may be moved. */ public boolean getAllowMove() { return allowMove; } /** * Gets the foreground color for selected cells. */ public Color getSelectionForeground() { return selectionForeground; } /** * Gets the background color for selected cells. */ public Color getSelectionBackground() { return selectionBackground; } /** * Sets the foreground color for selected cells. */ public void setSelectionForeground(Color color) { selectionForeground = color; } /** * Gets the background color for selected cells. */ public void setSelectionBackground(Color color) { selectionBackground = color; } /** * Gets the index of the selected item. * * @return the selected index; -1 if nothing is selected */ public int getSelectedIndex() { return selectedIndex; } /** * Gets the value of the selected item. * * @return the selected value; null if nothing is selected */ public Object getSelectedValue() { return ((selectedIndex == -1) ? null : model.getElement(selectedIndex)); } /** * Gets the top-most display that contains the given point. */ // public Display getDisplayAt(Point pt) // for (Iterator itr = displays.iterator(); itr.hasNext(); ) // Display d = (Display)itr.next(); // Point loc = d.getLocation(); // if (d.contains(pt.x - loc.x, pt.y - loc.y)) // return d; // return null; /** * Initializes UI components and sets up listeners. */ private void jbInit() throws Exception { this.setLayout(null); this.setOpaque(true); this.addMouseListener(new java.awt.event.MouseAdapter() { public void mousePressed(MouseEvent e) { this_mousePressed(e); } }); this.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseDragged(MouseEvent e) { this_mouseDragged(e); } }); this.add(rendererPane); } /** * Handles a mouse-press action. */ void this_mousePressed(MouseEvent e) { // Find the display that has been selected int idx = getModel().getIndexOfElementAt(e.getPoint()); if (idx == -1) { selectedIndex = -1; } else { // Move the selected element up to the front getModel().moveToFront(idx); selectedIndex = 0; } lastMouse = e.getPoint(); repaint(); fireItemSelected(selectedIndex); } /** * Handles dragging of the selected object around. */ void this_mouseDragged(MouseEvent e) { if (selectedIndex != -1) { // Figure out the distance moved Point mousePt = e.getPoint(); Point diff = new Point(mousePt.x - lastMouse.x, mousePt.y - lastMouse.y); // Move the selected display along Point newPos = new Point(getModel().getLocationOf(selectedIndex)); newPos.translate(diff.x, diff.y); // Make sure we don't allow the user to drag a display outside of the // viewable area. Dimension dim = getModel().getSizeOf(selectedIndex); Dimension visDim = this.getSize(); if (newPos.x + dim.width > visDim.width) { newPos.x = visDim.width - dim.width; } if (newPos.y + dim.height > visDim.height) { newPos.y = visDim.height - dim.height; } if (newPos.x < 0) { newPos.x = 0; } if (newPos.y < 0) { newPos.y = 0; } getModel().setLocationOf(selectedIndex, newPos); lastMouse = mousePt; repaint(); } } /** * Draws the objects in this placer's data model using the current * PlacerRenderer. */ public synchronized void paint(Graphics g) { // System.out.println("Painting the Placer!, selIdx = "+selectedIndex); super.paint(g); // Paint each object in the model using the current renderer for (int i=getModel().getSize()-1; i>=0; --i) { Component rendererComponent = renderer.getPlacerRendererComponent( this, getModel().getElement(i), (i == selectedIndex), false, i); Point pos = getModel().getLocationOf(i); Dimension dim = getModel().getSizeOf(i); rendererPane.paintComponent(g, rendererComponent, this, pos.x, pos.y, dim.width, dim.height); } } /** * Adds a listener that's notified each time the selection status of this * placer changes. */ public void addPlacerSelectionListener(PlacerSelectionListener listener) { listeners.add(PlacerSelectionListener.class, listener); } /** * Removes a listener that's notified each time the selection status of this * placer changes. */ public void removePlacerSelectionListener(PlacerSelectionListener listener) { listeners.remove(PlacerSelectionListener.class, listener); } /** * Notifies all listeners that the given index has been selected. * * @param idx the selected index or -1 if nothing is selected */ protected void fireItemSelected(int index) { // Get the value of the selected item Object value = ((index != -1) ? model.getElement(index) : null); // Notify all interested listeners PlacerSelectionEvent evt = null; Object[] listenerList = listeners.getListenerList(); for (int i=listenerList.length-2; i>=0; i-=2) { if (listenerList[i] == PlacerSelectionListener.class) { // lazily instantiate the list if (evt == null) { evt = new PlacerSelectionEvent(this, index, value); } ((PlacerSelectionListener)listenerList[i+1]).valueChanged(evt); } } } /** * Helper class that handles events from the data model and updates the * state of the parent placer accordingly. */ private class PlacerModelHandler implements PlacerModelListener { /** * Notifies this listener that the model it was listening to has changed * in some way. */ public void placerItemsChanged(PlacerModelEvent evt) { repaint(); } /** * Notifies this listener that items have been inserted into the placer. */ public void placerItemsInserted(PlacerModelEvent evt) { repaint(); } /** * Notifies this listener that items have been removed from the placer. */ public void placerItemsRemoved(PlacerModelEvent evt) { // Check if the placer is now empty so that we can make sure we clear // the selection index. if (model.getSize() == 0) { selectedIndex = -1; fireItemSelected(selectedIndex); } repaint(); } } } class DefaultPlacerRenderer extends JPanel implements PlacerRenderer { private Placer placer; private int idx; private boolean selected; public Component getPlacerRendererComponent(Placer placer, Object value, boolean selected, boolean hasFocus, int idx) { this.placer = placer; this.idx = idx; this.selected = selected; if (selected) { setForeground(placer.getSelectionForeground()); setBackground(placer.getSelectionBackground()); } else { setForeground(placer.getSelectionBackground()); setBackground(placer.getSelectionForeground()); } return this; } public void paintComponent(Graphics g) { if (placer != null && idx >= 0) { super.paintComponent(g); Point pos = placer.getModel().getLocationOf(idx); Dimension dim = placer.getModel().getSizeOf(idx); g.setColor(Color.white); g.drawRect(0, 0, dim.width-1, dim.height-1); g.fillRect(0, 0, dim.width, 3); } } }
package bisq.monitor.metric; import bisq.monitor.OnionParser; import bisq.monitor.Reporter; import bisq.core.dao.monitoring.model.StateHash; import bisq.core.dao.monitoring.network.messages.GetBlindVoteStateHashesRequest; import bisq.core.dao.monitoring.network.messages.GetDaoStateHashesRequest; import bisq.core.dao.monitoring.network.messages.GetProposalStateHashesRequest; import bisq.core.dao.monitoring.network.messages.GetStateHashesResponse; import bisq.network.p2p.NodeAddress; import bisq.network.p2p.network.Connection; import bisq.network.p2p.peers.getdata.messages.GetDataResponse; import bisq.network.p2p.peers.getdata.messages.PreliminaryGetDataRequest; import bisq.network.p2p.storage.payload.PersistableNetworkPayload; import bisq.network.p2p.storage.payload.ProtectedStorageEntry; import bisq.network.p2p.storage.payload.ProtectedStoragePayload; import bisq.common.proto.network.NetworkEnvelope; import java.net.MalformedURLException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Random; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import static com.google.common.base.Preconditions.checkNotNull; /** * Contacts a list of hosts and asks them for all the data excluding persisted messages. The * answers are then compiled into buckets of message types. Based on these * buckets, the Metric reports (for each host) the message types observed and * their number. * * Furthermore, since the DAO is a thing now, the consistency of the DAO state held by each host is assessed and reported. * * @author Florian Reimair * */ @Slf4j public class P2PSeedNodeSnapshot extends P2PSeedNodeSnapshotBase { Statistics statistics; final Map<NodeAddress, Statistics> bucketsPerHost = new ConcurrentHashMap<>(); protected final Set<byte[]> hashes = new TreeSet<>(Arrays::compare); private int daostateheight = 550000; private int proposalheight = daostateheight; private int blindvoteheight = daostateheight; /** * Efficient way to count message occurrences. */ private class Counter { private int value = 0; int value() { return value; } void increment() { value++; } } /** * Use a counter to do statistics. */ private class MyStatistics implements Statistics<Counter> { private final Map<String, Counter> buckets = new HashMap<>(); @Override public Statistics create() { return new MyStatistics(); } @Override public synchronized void log(Object message) { // For logging different data types String className = message.getClass().getSimpleName(); buckets.putIfAbsent(className, new Counter()); buckets.get(className).increment(); } @Override public Map<String, Counter> values() { return buckets; } @Override public synchronized void reset() { buckets.clear(); } } public P2PSeedNodeSnapshot(Reporter reporter) { super(reporter); // AppendOnlyDataStoreService appendOnlyDataStoreService, // ProtectedDataStoreService protectedDataStoreService, // ResourceDataStoreService resourceDataStoreService, // Storage<SequenceNumberMap> sequenceNumberMapStorage) { // Set<byte[]> excludedKeys = dataStorage.getAppendOnlyDataStoreMap().keySet().stream() // .map(e -> e.bytes) // .collect(Collectors.toSet()); // Set<byte[]> excludedKeysFromPersistedEntryMap = dataStorage.getProtectedDataStoreMap().keySet() // .stream() // .map(e -> e.bytes) // .collect(Collectors.toSet()); statistics = new MyStatistics(); } protected List<NetworkEnvelope> getRequests() { List<NetworkEnvelope> result = new ArrayList<>(); Random random = new Random(); result.add(new PreliminaryGetDataRequest(random.nextInt(), hashes)); result.add(new GetDaoStateHashesRequest(daostateheight, random.nextInt())); result.add(new GetProposalStateHashesRequest(proposalheight, random.nextInt())); result.add(new GetBlindVoteStateHashesRequest(blindvoteheight, random.nextInt())); return result; } /** * Report all the stuff. Uses the configured reporter directly. */ void report() { // report Map<String, String> report = new HashMap<>(); // - assemble histograms bucketsPerHost.forEach((host, statistics) -> statistics.values().forEach((type, counter) -> report .put(OnionParser.prettyPrint(host) + ".numberOfMessages." + type, String.valueOf(((Counter) counter).value())))); // - assemble diffs // - transfer values Map<String, Statistics> messagesPerHost = new HashMap<>(); bucketsPerHost.forEach((host, value) -> messagesPerHost.put(OnionParser.prettyPrint(host), value)); // - pick reference seed node and its values Optional<String> referenceHost = messagesPerHost.keySet().stream().sorted().findFirst(); Map<String, Counter> referenceValues = messagesPerHost.get(referenceHost.get()).values(); // - calculate diffs messagesPerHost.forEach( (host, statistics) -> { statistics.values().forEach((messageType, count) -> { try { report.put(OnionParser.prettyPrint(host) + ".relativeNumberOfMessages." + messageType, String.valueOf(((Counter) count).value() - referenceValues.get(messageType).value())); } catch (MalformedURLException | NullPointerException ignore) { log.error("we should never have gotten here", ignore); } }); try { report.put(OnionParser.prettyPrint(host) + ".referenceHost", referenceHost.get()); } catch (MalformedURLException ignore) { log.error("we should never got here"); } }); // cleanup for next run bucketsPerHost.forEach((host, statistics) -> statistics.reset()); // when our hash cache exceeds a hard limit, we clear the cache and start anew if (hashes.size() > 150000) hashes.clear(); // - report reporter.report(report, getName()); // - assemble dao report Map<String, String> daoreport = new HashMap<>(); // - transcode Map<String, Map<NodeAddress, Tuple>> perType = new HashMap<>(); daoData.forEach((nodeAddress, daostatistics) -> daostatistics.values().forEach((type, tuple) -> { perType.putIfAbsent((String) type, new HashMap<>()); perType.get(type).put(nodeAddress, (Tuple) tuple); })); // - process dao data perType.forEach((type, nodeAddressTupleMap) -> { // - find head int head = (int) nodeAddressTupleMap.values().stream().max(Comparator.comparingLong(Tuple::getHeight)).get().height; int oldest = (int) nodeAddressTupleMap.values().stream().min(Comparator.comparingLong(Tuple::getHeight)).get().height; // - update queried height if(type.contains("DaoState")) daostateheight = oldest - 20; else if(type.contains("Proposal")) proposalheight = oldest - 20; else blindvoteheight = oldest - 20; // - calculate diffs nodeAddressTupleMap.forEach((nodeAddress, tuple) -> daoreport.put(type + "." + OnionParser.prettyPrint(nodeAddress) + ".head", Long.toString(tuple.height - head))); // - memorize hashes Set<ByteBuffer> states = new HashSet<>(); nodeAddressTupleMap.forEach((nodeAddress, tuple) -> states.add(ByteBuffer.wrap(tuple.hash))); nodeAddressTupleMap.forEach((nodeAddress, tuple) -> daoreport.put(type + "." + OnionParser.prettyPrint(nodeAddress) + ".hash", Integer.toString(Arrays.asList(states.toArray()).indexOf(ByteBuffer.wrap(tuple.hash))))); // - report reference head daoreport.put(type + ".referenceHead", Integer.toString(head)); }); daoData.clear(); // - report reporter.report(daoreport, "DaoStateSnapshot"); } private class Tuple { @Getter private final long height; private final byte[] hash; Tuple(long height, byte[] hash) { this.height = height; this.hash = hash; } } private class DaoStatistics implements Statistics<Tuple> { Map<String, Tuple> buckets = new ConcurrentHashMap<>(); @Override public Statistics create() { return new DaoStatistics(); } @Override public void log(Object message) { // get last entry StateHash last = (StateHash) ((GetStateHashesResponse) message).getStateHashes().get(((GetStateHashesResponse) message).getStateHashes().size() - 1); // For logging different data types String className = last.getClass().getSimpleName(); buckets.putIfAbsent(className, new Tuple(last.getHeight(), last.getHash())); } @Override public Map<String, Tuple> values() { return buckets; } @Override public void reset() { buckets.clear(); } } private Map<NodeAddress, Statistics> daoData = new ConcurrentHashMap<>(); protected boolean treatMessage(NetworkEnvelope networkEnvelope, Connection connection) { checkNotNull(connection.getPeersNodeAddressProperty(), "although the property is nullable, we need it to not be null"); if (networkEnvelope instanceof GetDataResponse) { Statistics result = this.statistics.create(); GetDataResponse dataResponse = (GetDataResponse) networkEnvelope; final Set<ProtectedStorageEntry> dataSet = dataResponse.getDataSet(); dataSet.forEach(e -> { final ProtectedStoragePayload protectedStoragePayload = e.getProtectedStoragePayload(); if (protectedStoragePayload == null) { log.warn("StoragePayload was null: {}", networkEnvelope.toString()); return; } result.log(protectedStoragePayload); }); Set<PersistableNetworkPayload> persistableNetworkPayloadSet = dataResponse .getPersistableNetworkPayloadSet(); if (persistableNetworkPayloadSet != null) { persistableNetworkPayloadSet.forEach(persistableNetworkPayload -> { // memorize message hashes //Byte[] bytes = new Byte[persistableNetworkPayload.getHash().length]; //Arrays.setAll(bytes, n -> persistableNetworkPayload.getHash()[n]); //hashes.add(bytes); hashes.add(persistableNetworkPayload.getHash()); }); } bucketsPerHost.put(connection.getPeersNodeAddressProperty().getValue(), result); return true; } else if (networkEnvelope instanceof GetStateHashesResponse) { daoData.putIfAbsent(connection.getPeersNodeAddressProperty().getValue(), new DaoStatistics()); daoData.get(connection.getPeersNodeAddressProperty().getValue()).log(networkEnvelope); return true; } return false; } }
package org.whattf.checker; import org.xml.sax.Attributes; import org.xml.sax.SAXException; public class UncheckedSubtreeWarner extends Checker { private boolean alreadyWarnedAboutRdf; private boolean alreadyWarnedAboutOpenMath; private boolean alreadyWarnedAboutInkscape; private boolean alreadyWarnedAboutSvgVersion; public UncheckedSubtreeWarner() { alreadyWarnedAboutRdf = false; alreadyWarnedAboutOpenMath = false; alreadyWarnedAboutInkscape = false; alreadyWarnedAboutSvgVersion = false; } /** * @see org.whattf.checker.Checker#startDocument() */ @Override public void startDocument() throws SAXException { alreadyWarnedAboutRdf = false; alreadyWarnedAboutOpenMath = false; alreadyWarnedAboutInkscape = false; alreadyWarnedAboutSvgVersion = false; } /** * @see org.whattf.checker.Checker#startElement(java.lang.String, * java.lang.String, java.lang.String, org.xml.sax.Attributes) */ @Override public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { if (!alreadyWarnedAboutRdf && "http://www.w3.org/1999/02/22-rdf-syntax-ns#" == uri) { warn("This validator does not validate RDF. RDF subtrees go unchecked."); alreadyWarnedAboutRdf = true; } if (!alreadyWarnedAboutOpenMath && "http: warn("This validator does not validate OpenMath. OpenMath subtrees go unchecked."); alreadyWarnedAboutOpenMath = true; } if (!alreadyWarnedAboutInkscape && (("http: || "http: warn("This validator does not validate Inkscape extensions properly. Inkscape-specific errors may go unnoticed."); alreadyWarnedAboutInkscape = true; } if (!alreadyWarnedAboutSvgVersion && "http: warn("Unsupported SVG version specified. This validator only supports SVG 1.1. The recommended way to suppress this warning is to remove the \u201Cversion\u201D attribute altogether."); alreadyWarnedAboutSvgVersion = true; } } private boolean hasUnsupportedVersion(Attributes atts) { String version = atts.getValue("", "version"); return "1.0".equals(version) || "1.2".equals(version); } private boolean attrsContainInkscape(Attributes atts) { int length = atts.getLength(); for (int i = 0; i < length; i++) { String uri = atts.getURI(i); if ("http: || "http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" == uri) { return true; } } return false; } }
package obvious.ivtk.data; import infovis.Column; import infovis.column.ColumnFactory; import infovis.table.DefaultDynamicTable; import infovis.utils.TableIterator; import java.text.FieldPosition; import java.text.ParsePosition; import java.util.ArrayList; import java.util.Collection; import org.apache.log4j.BasicConfigurator; import obvious.ObviousException; import obvious.ObviousRuntimeException; import obvious.data.Schema; import obvious.data.Table; import obvious.data.Tuple; import obvious.data.event.TableListener; import obvious.data.util.IntIterator; import obviousx.text.TypedFormat; import obviousx.util.FormatFactory; import obviousx.util.FormatFactoryImpl; /** * Implementation of an Obvious Table based on infovis toolkit. * * @author Pierre-Luc Hemery * */ public class IvtkObviousTable implements Table { /** * Schema for the table. */ private Schema schema; /** * Wrapped ivtk table. */ private infovis.DynamicTable table; /** * Is the schema being edited. */ private boolean editing = false; /** * Are rows removable. */ private boolean canRemoveRow; /** * Are rows addable. */ private boolean canAddRow; /** * ArrayList of listeners. */ private ArrayList<TableListener> listener = new ArrayList<TableListener>(); /** * Format factory. */ private FormatFactory formatFactory; /** * Constructor for IvtkObvious table. * @param inSchema schema for the table */ public IvtkObviousTable(Schema inSchema) { this(inSchema, true, true); } /** * Constructor for IvtkObvious table. * @param inSchema schema for the table * @param add boolean indicating if row addition is allowed * @param rem boolean indicating if row addition is allowed */ public IvtkObviousTable(Schema inSchema, Boolean add, Boolean rem) { this.schema = inSchema; this.table = new DefaultDynamicTable(); this.canAddRow = add; this.canRemoveRow = rem; BasicConfigurator.configure(); ColumnFactory factory = ColumnFactory.getInstance(); formatFactory = new FormatFactoryImpl(); for (int i = 0; i < schema.getColumnCount(); i++) { Column col = factory.create( schema.getColumnType(i).getSimpleName(), schema.getColumnName(i)); table.addColumn(col); } } /** * Constructor for IvtkObvious table. * @param inTable an ivtk DefaultDynamicTable instance to wrap * @param add boolean indicating if row addition is allowed * @param rem boolean indicating if row addition is allowed */ public IvtkObviousTable(infovis.DynamicTable inTable, Boolean add, Boolean rem) { this.table = inTable; this.canAddRow = add; this.canRemoveRow = rem; formatFactory = new FormatFactoryImpl(); ArrayList<Column> cols = new ArrayList<Column>(); for (int i = 0; i < table.getColumnCount(); i++) { cols.add(table.getColumnAt(i)); } this.schema = new IvtkObviousSchema(cols); } /** * Constructor for IvtkObvious table. * @param inTable an ivtk DefaultDynamicTable instance to wrap */ public IvtkObviousTable(infovis.DynamicTable inTable) { this(inTable, true, true); } /** * Adds a row with default value. * @return number of rows */ public int addRow() { try { if (canAddRow()) { int rowId = table.addRow(); for (int i = 0; i < schema.getColumnCount(); i++) { TypedFormat format = formatFactory.getFormat( schema.getColumnType(i).getSimpleName()); StringBuffer val = format.format(schema.getColumnDefault(i), new StringBuffer(), new FieldPosition(0)); table.setValueAt(val.toString(), rowId, i); //table.getColumnAt(i).setValueAt(table.getColumnAt(i).size(), // val.toString()); } this.fireTableEvent(table.getLastRow(), table.getLastRow(), TableListener.ALL_COLUMN, TableListener.INSERT); } return this.getRowCount(); } catch (Exception e) { throw new ObviousRuntimeException(e); } } /** * Adds a row corresponding to the input tuple. * @param tuple tuple to insert in the table * @return number of rows */ public int addRow(Tuple tuple) { try { if (canAddRow()) { int rowId = table.addRow(); table.setSize(table.size() + 1); for (int i = 0; i < tuple.getSchema().getColumnCount(); i++) { TypedFormat format = formatFactory.getFormat( tuple.getSchema().getColumnType(i).getSimpleName()); if (format instanceof FormatFactoryImpl.TypedDecimalFormat) { table.setValueAt(tuple.get(i).toString(), rowId, i); } else { StringBuffer v = format.format(tuple.get(i), new StringBuffer(), new FieldPosition(0)); table.setValueAt(v.toString(), rowId, i); } } this.fireTableEvent(table.getLastRow(), table.getLastRow(), TableListener.ALL_COLUMN, TableListener.INSERT); } return this.getRowCount(); } catch (Exception e) { throw new ObviousRuntimeException(e); } } /** * Adds a table listener. * @param listnr an Obvious TableListener */ public void addTableListener(TableListener listnr) { listener.add(listnr); } /** * Indicates the beginning of a column edit. * @param col column index * @throws ObviousException if edition is not supported. */ public void beginEdit(int col) throws ObviousException { this.editing = true; for (TableListener listnr : this.getTableListeners()) { listnr.beginEdit(col); } } /** * Indicates if possible to add rows. * @return true if possible */ public boolean canAddRow() { return this.canAddRow; } /** * Indicates if possible to remove rows. * @return true if possible */ public boolean canRemoveRow() { return this.canRemoveRow; } /** * Indicates the end of a column edit. * @param col column index * @throws ObviousException if edition is not supported. */ public void endEdit(int col) throws ObviousException { this.editing = false; for (TableListener listnr : this.getTableListeners()) { listnr.endEdit(col); } } /** * Gets the number of rows in the table. * @return the number of rows */ public int getRowCount() { return table.getRowCount(); } /** * Returns this table's schema. * @return the schema of the table. */ public Schema getSchema() { return this.schema; } /** * Gets all table listener. * @return a collection of table listeners. */ public Collection<TableListener> getTableListeners() { return listener; } /** * Gets a specific value. * @param rowId row index * @param field column name * @return value for this couple */ public Object getValue(int rowId, String field) { return getValue(rowId, schema.getColumnIndex(field)); } /** * Gets a specific value. * @param rowId row index * @param col column index * @return value for this couple */ public Object getValue(int rowId, int col) { TypedFormat format = formatFactory.getFormat( schema.getColumnType(col).getSimpleName()); Object value = format.parseObject((String) table.getValueAt(rowId, col), new ParsePosition(0)); return value; } /** * Indicates if a column is being edited. * @param col column index * @return true if edited */ public boolean isEditing(int col) { return this.editing; } /** * Indicates if the given row number corresponds to a valid table row. * @param rowId row index * @return true if the row is valid, false if it is not */ public boolean isValidRow(int rowId) { return table.isRowValid(rowId); } /** * Indicates if a given value is correct. * @param rowId row index * @param col column index * @return true if the coordinates are valid */ public boolean isValueValid(int rowId, int col) { return isValidRow(rowId) && (col < schema.getColumnCount()); } /** * Removes all the rows. * * <p>After this method, the table is almost in the same state as if * it had been created afresh except it contains the same columns as before * but they are all cleared. * */ public void removeAllRows() { try { int lastRow = table.getLastRow(); TableIterator it = new TableIterator(0, table.getLastRow() + 1); while (it.hasNext()) { int rowId = it.nextRow(); table.removeRow(rowId); } this.fireTableEvent(0, lastRow, TableListener.ALL_COLUMN, TableListener.DELETE); } catch (Exception e) { throw new ObviousRuntimeException(e); } } /* Removes a row in the schema's table. * @param row row index * @return true if removes, else false. */ public boolean removeRow(int row) { try { if (!canRemoveRow()) { return false; } if (!isValidRow(row)) { return false; } table.removeRow(row); this.fireTableEvent(row, row, TableListener.ALL_COLUMN, TableListener.DELETE); return true; } catch (Exception e) { throw new ObviousRuntimeException(e); } } /** * Removes a table listener. * @param listnr an Obvious TableListener */ public void removeTableListener(TableListener listnr) { listener.remove(listnr); } /** * Gets an iterator over the row numbers of this table. * @return an iterator over the rows of this table */ public IntIterator rowIterator() { TableIterator it = new TableIterator(0, table.getLastRow() + 1); return new IvtkIntIterator(it); } /** * Sets a value. * @param rowId row index * @param field column name * @param val value to set */ public void set(int rowId, String field, Object val) { set(rowId, schema.getColumnIndex(field), val); } /** * Sets a value. * @param rowId row index * @param col column index * @param val value to set */ public void set(int rowId, int col, Object val) { try { if (val != null) { TypedFormat format = formatFactory.getFormat( val.getClass().getSimpleName()); if (format instanceof FormatFactoryImpl.TypedDecimalFormat) { table.setValueAt(val.toString(), rowId, col); } else { //StringBuffer v = format.format(val, // new StringBuffer(), new FieldPosition(0)); table.setValueAt(val.toString(), rowId, col); } } else { table.setValueAt(val, rowId, col); } this.fireTableEvent(rowId, rowId, col, TableListener.UPDATE); } catch (Exception e) { throw new ObviousRuntimeException(e); } } /** * Notifies changes to listener. * @param start the starting row index of the changed table region * @param end the ending row index of the changed table region * @param col the column that has changed * @param type the type of modification */ protected void fireTableEvent(int start, int end, int col, int type) { if (this.getTableListeners().isEmpty()) { return; } for (TableListener listnr : this.getTableListeners()) { listnr.tableChanged(this, start, end, col, type); } } /** * Wrapper around ivtk TableIterator class. * It makes this class compliant to obvious IntIterator. * @author Pierre-Luc Hemery * */ public class IvtkIntIterator implements IntIterator { /** * Wrapped TableIterator. */ private TableIterator it; /** * Constructor for IvktInterator. * @param iter an existing ivtk TableIteror */ public IvtkIntIterator(TableIterator iter) { this.it = iter; } /** * Returns the next element in the iteration as an int. * @return the next element in iteration (as int) */ public int nextInt() { return it.nextRow(); } /** * Returns true if the iteration has more elements. (In other words, returns * true if next would return an element rather than throwing an exception.) * @return true if the iterator has more elements. */ public boolean hasNext() { return it.hasNext(); } /** * Returns the next element in the iteration. * @return the next element in iteration (as Integer) */ public Integer next() { return it.nextRow(); } /** * Unsupported. */ public void remove() { it.remove(); } } /** * Return the underlying implementation. * @param type targeted class * @return null */ public Object getUnderlyingImpl(Class<?> type) { return null; } }
package org.folio.okapi.common; import io.vertx.core.Handler; import io.vertx.core.MultiMap; import io.vertx.core.Vertx; import io.vertx.core.buffer.Buffer; import io.vertx.core.http.HttpClient; import io.vertx.core.http.HttpClientRequest; import io.vertx.core.http.HttpMethod; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import io.vertx.ext.web.RoutingContext; import java.util.HashMap; import java.util.Map; import java.util.Random; import static org.folio.okapi.common.ErrorType.*; /** * Okapi client. Makes requests to other Okapi modules, or Okapi itself. Handles * all the things we need with the headers etc. Note that the client keeps a * list of necessary headers (which it can get from the RoutingContext, or * separately), so it is bound to one request, or at least one tenant. Your * module should not just keep one client around for everything it does. * * @author heikki */ public class OkapiClient { private final Logger logger = LoggerFactory.getLogger("okapi"); private String okapiUrl; private HttpClient httpClient; private Map<String, String> headers; private MultiMap respHeaders; private String reqId; private boolean logInfo; // t: log requests on INFO. f: on DEBUG private String responsebody; /** * Constructor from a vert.x ctx. That ctx contains all the headers we need. * * @param ctx */ public OkapiClient(RoutingContext ctx) { init(ctx.vertx()); this.okapiUrl = ctx.request().getHeader(XOkapiHeaders.URL); if (this.okapiUrl != null) { this.okapiUrl = okapiUrl.replaceAll("/+$", ""); // no trailing slash } for (String hdr : ctx.request().headers().names()) { if (hdr.startsWith(XOkapiHeaders.PREFIX) || hdr.startsWith("Accept")) { String hv = ctx.request().getHeader(hdr); headers.put(hdr, hv); if (hdr.equals(XOkapiHeaders.REQUEST_ID)) { reqId = hv; } } } } /** * Explicit constructor. * * @param okapiUrl * @param vertx * @param headers may be null */ public OkapiClient(String okapiUrl, Vertx vertx, Map<String, String> headers) { init(vertx); this.okapiUrl = okapiUrl.replaceAll("/+$", ""); // no trailing slash if (headers != null) { this.headers.putAll(headers); } if (this.headers.containsKey(XOkapiHeaders.REQUEST_ID)) { reqId = this.headers.get(XOkapiHeaders.REQUEST_ID); } respHeaders = null; } private void init(Vertx vertx) { this.httpClient = vertx.createHttpClient(); this.headers = new HashMap<>(); respHeaders = null; reqId = ""; logInfo = false; } /** * Enable logging of request on INFO level. Normally not the case, since Okapi * will log the incoming request anyway. Useful with Okapi's own requests to * modules, etc. */ public void enableInfoLog() { logInfo = true; } /** * Disable request logging on INFO. They will still be logged on DEBUG. */ public void disableInfoLog() { logInfo = false; } /** * Set up a new request-Id. Used internally, when Okapi itself makes a new * request to the modules, like the tenant interface. */ public void newReqId(String path) { Random r = new Random(); String newId = String.format("%06d", r.nextInt(1000000)) + "/" + path; if (reqId.isEmpty()) { reqId = newId; } else { reqId = reqId + ";" + newId; } headers.put(XOkapiHeaders.REQUEST_ID, reqId); } /** * Make a request to Okapi. * * @param method GET or POST or such * @param path like "/foomodule/something" * @param data for the request. Most likely a JSON string. * @param fut callback when done. Most likely a JSON string if all went well, * or a plain text string in case of errors. */ public void request(HttpMethod method, String path, String data, Handler<ExtendedAsyncResult<String>> fut) { if (this.okapiUrl == null) { fut.handle(new Failure<>(INTERNAL, "OkapiClient: No OkapiUrl specified")); return; } String url = this.okapiUrl + path; String tenant = "-"; if (headers.containsKey(XOkapiHeaders.TENANT)) { tenant = headers.get(XOkapiHeaders.TENANT); } respHeaders = null; String logReqMsg = reqId + " REQ " + "okapiClient " + tenant + " " + method.toString() + " " + url; if (logInfo) { logger.info(logReqMsg); } else { logger.debug(logReqMsg); } HttpClientRequest req = httpClient.requestAbs(method, url, reqres -> { String logResMsg = reqId + " RES " + reqres.statusCode() + " 0us " // TODO - get timing + "okapiClient " + url; if (logInfo) { logger.info(logResMsg); } else { logger.debug(logResMsg); } final Buffer buf = Buffer.buffer(); respHeaders = reqres.headers(); reqres.handler(b -> { logger.debug(reqId + " OkapiClient Buffering response " + b.toString()); buf.appendBuffer(b); }); reqres.endHandler(e -> { responsebody = buf.toString(); if (reqres.statusCode() >= 200 && reqres.statusCode() <= 299) { fut.handle(new Success<>(responsebody)); } else { if (reqres.statusCode() == 404) { fut.handle(new Failure<>(NOT_FOUND, "404 " + responsebody + ": " + url)); } else if (reqres.statusCode() == 403) { fut.handle(new Failure<>(FORBIDDEN, "403 " + responsebody + ": " + url)); } else if (reqres.statusCode() == 400) { fut.handle(new Failure<>(USER, responsebody)); } else { fut.handle(new Failure<>(INTERNAL, responsebody)); } } }); reqres.exceptionHandler(e -> fut.handle(new Failure<>(INTERNAL, e))); }); req.exceptionHandler(x -> { String msg = x.getMessage(); logger.warn(reqId + " OkapiClient exception: " + msg); fut.handle(new Failure<>(INTERNAL, msg)); }); for (Map.Entry<String, String> entry : headers.entrySet()) { logger.debug(reqId + " OkapiClient: adding header " + entry.getKey() + ": " + entry.getValue()); } req.headers().addAll(headers); req.end(data); } public void post(String path, String data, Handler<ExtendedAsyncResult<String>> fut) { request(HttpMethod.POST, path, data, fut); } public void get(String path, Handler<ExtendedAsyncResult<String>> fut) { request(HttpMethod.GET, path, "", fut); } public void delete(String path, Handler<ExtendedAsyncResult<String>> fut) { request(HttpMethod.DELETE, path, "", fut); } public String getOkapiUrl() { return okapiUrl; } /** * Get the response headers. May be null * * @return */ public MultiMap getRespHeaders() { return respHeaders; } /** * Get the response body. Same string as returned in the callback from * request(). * * @return */ public String getResponsebody() { return responsebody; } /** * Get the Okapi authentication token. From the X-Okapi-Token header. * * @return the token, or null if not defined. */ public String getOkapiToken() { return headers.get(XOkapiHeaders.TOKEN); } /** * Set the Okapi authentication token. Overrides the auth token. Should * normally not be needed, but can be used in some special cases. * * @param token */ public void setOkapiToken(String token) { headers.put(XOkapiHeaders.TOKEN, token); } public void close() { if (httpClient != null) { httpClient.close(); httpClient = null; } } }
package org.folio.okapi.common; import io.vertx.core.Handler; import io.vertx.core.MultiMap; import io.vertx.core.Vertx; import io.vertx.core.buffer.Buffer; import io.vertx.core.http.HttpClient; import io.vertx.core.http.HttpClientRequest; import io.vertx.core.http.HttpMethod; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import io.vertx.ext.web.RoutingContext; import java.util.HashMap; import java.util.Map; import java.util.Random; import static org.folio.okapi.common.ErrorType.*; /** * Okapi client. Makes requests to other Okapi modules, or Okapi itself. Handles * all the things we need with the headers etc. Note that the client keeps a * list of necessary headers (which it can get from the RoutingContext, or * separately), so it is bound to one request, or at least one tenant. Your * module should not just keep one client around for everything it does. * * @author heikki */ public class OkapiClient { private final Logger logger = LoggerFactory.getLogger("okapi"); private String okapiUrl; private HttpClient httpClient; private Map<String, String> headers; // TODO Response headers: do we need a trace or something? // Return type: Need a more complex container class with room for // response headers, the whole response, and so on. // Use this in the discovery-deployment communications private MultiMap respHeaders; private String reqId; private boolean logInfo; // t: log requests on INFO. f: on DEBUG private String responsebody; /** * Constructor from a vert.x ctx. That ctx contains all the headers we need. * * @param ctx */ public OkapiClient(RoutingContext ctx) { init(ctx.vertx()); this.okapiUrl = ctx.request().getHeader(XOkapiHeaders.URL); if (this.okapiUrl != null) { this.okapiUrl = okapiUrl.replaceAll("/+$", ""); // no trailing slash } for (String hdr : ctx.request().headers().names()) { if (hdr.startsWith(XOkapiHeaders.PREFIX) || hdr.startsWith("Accept")) { String hv = ctx.request().getHeader(hdr); headers.put(hdr, hv); if (hdr.equals(XOkapiHeaders.REQUEST_ID)) { reqId = hv; } } } } /** * Explicit constructor. * * @param okapiUrl * @param vertx * @param headers may be null */ public OkapiClient(String okapiUrl, Vertx vertx, Map<String, String> headers) { init(vertx); this.okapiUrl = okapiUrl.replaceAll("/+$", ""); // no trailing slash if (headers != null) { this.headers.putAll(headers); } if (this.headers.containsKey(XOkapiHeaders.REQUEST_ID)) { reqId = this.headers.get(XOkapiHeaders.REQUEST_ID); } respHeaders = null; } private void init(Vertx vertx) { this.httpClient = vertx.createHttpClient(); this.headers = new HashMap<>(); respHeaders = null; reqId = ""; logInfo = false; } /** * Enable logging of request on INFO level. Normally not the case, since Okapi * will log the incoming request anyway. Useful with Okapi's own requests to * modules, etc. */ public void enableInfoLog() { logInfo = true; } /** * Disable request logging on INFO. They will still be logged on DEBUG. */ public void disableInfoLog() { logInfo = false; } /** * Set up a new request-Id. Used internally, when Okapi itself makes a new * request to the modules, like the tenant interface. */ public void newReqId(String path) { Random r = new Random(); String newId = String.format("%06d", r.nextInt(1000000)) + "/" + path; if (reqId.isEmpty()) { reqId = newId; } else { reqId = reqId + ";" + newId; } headers.put(XOkapiHeaders.REQUEST_ID, reqId); } /** * Make a request to Okapi. * * @param method GET or POST or such * @param path like "/foomodule/something" * @param data for the request. Most likely a JSON string. * @param fut callback when done. Most likely a JSON string if all went well, * or a plain text string in case of errors. */ public void request(HttpMethod method, String path, String data, Handler<ExtendedAsyncResult<String>> fut) { if (this.okapiUrl == null) { fut.handle(new Failure<>(INTERNAL, "OkapiClient: No OkapiUrl specified")); return; } String url = this.okapiUrl + path; String tenant = "-"; if (headers.containsKey(XOkapiHeaders.TENANT)) { tenant = headers.get(XOkapiHeaders.TENANT); } respHeaders = null; String logReqMsg = reqId + " REQ " + "okapiClient " + tenant + " " + method.toString() + " " + url; if (logInfo) { logger.info(logReqMsg); } else { logger.debug(logReqMsg); } HttpClientRequest req = httpClient.requestAbs(method, url, postres -> { String logResMsg = reqId + " RES " + postres.statusCode() + " 0us " // TODO - get timing + "okapiClient " + url; if (logInfo) { logger.info(logResMsg); } else { logger.debug(logResMsg); } final Buffer buf = Buffer.buffer(); respHeaders = postres.headers(); postres.handler(b -> { logger.debug(reqId + " OkapiClient Buffering response " + b.toString()); buf.appendBuffer(b); }); postres.endHandler(e -> { responsebody = buf.toString(); if (postres.statusCode() >= 200 && postres.statusCode() <= 299) { fut.handle(new Success<>(responsebody)); } else { if (postres.statusCode() == 404) { fut.handle(new Failure<>(NOT_FOUND, "404 " + responsebody + ": " + url)); } else if (postres.statusCode() == 403) { fut.handle(new Failure<>(FORBIDDEN, "403 " + responsebody + ": " + url)); } else if (postres.statusCode() == 400) { fut.handle(new Failure<>(USER, responsebody)); } else { fut.handle(new Failure<>(INTERNAL, responsebody)); } } }); postres.exceptionHandler(e -> fut.handle(new Failure<>(INTERNAL, e))); }); req.exceptionHandler(x -> { String msg = x.getMessage(); logger.warn(reqId + " OkapiClient exception: " + msg); fut.handle(new Failure<>(INTERNAL, msg)); }); for (Map.Entry<String, String> entry : headers.entrySet()) { logger.debug(reqId + " OkapiClient: adding header " + entry.getKey() + ": " + entry.getValue()); } req.headers().addAll(headers); req.end(data); } public void post(String path, String data, Handler<ExtendedAsyncResult<String>> fut) { request(HttpMethod.POST, path, data, fut); } public void get(String path, Handler<ExtendedAsyncResult<String>> fut) { request(HttpMethod.GET, path, "", fut); } public void delete(String path, Handler<ExtendedAsyncResult<String>> fut) { request(HttpMethod.DELETE, path, "", fut); } public String getOkapiUrl() { return okapiUrl; } /** * Get the response headers. May be null * * @return */ public MultiMap getRespHeaders() { return respHeaders; } /** * Get the response body. Same string as returned in the callback from * request(). * * @return */ public String getResponsebody() { return responsebody; } /** * Get the Okapi authentication token. From the X-Okapi-Token header. * * @return the token, or null if not defined. */ public String getOkapiToken() { return headers.get(XOkapiHeaders.TOKEN); } /** * Set the Okapi authentication token. Overrides the auth token. Should * normally not be needed, but can be used in some special cases. * * @param token */ public void setOkapiToken(String token) { headers.put(XOkapiHeaders.TOKEN, token); } }
package org.openlca.core.model; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name = "tbl_impact_categories") public class ImpactCategory extends RootEntity { @OneToMany(cascade = { CascadeType.ALL }, orphanRemoval = true) @JoinColumn(name = "f_impact_category") public final List<ImpactFactor> impactFactors = new ArrayList<>(); @Column(name = "reference_unit") public String referenceUnit; @Override public ImpactCategory clone() { ImpactCategory clone = new ImpactCategory(); Util.cloneRootFields(this, clone); clone.referenceUnit = referenceUnit; for (ImpactFactor f : impactFactors) clone.impactFactors.add(f.clone()); return clone; } public ImpactFactor getFactor(Flow flow) { if (flow == null) return null; for (ImpactFactor factor : impactFactors) if (flow.equals(factor.flow)) return factor; return null; } public ImpactFactor getFactor(String refId) { if (refId == null) return null; for (ImpactFactor factor : impactFactors) if (factor.flow != null && refId.equals(factor.flow.refId)) return factor; return null; } }
package org.lamport.tla.toolbox; import org.eclipse.core.resources.IResourceChangeEvent; import org.eclipse.core.resources.IResourceChangeListener; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.lamport.tla.toolbox.spec.Spec; import org.lamport.tla.toolbox.spec.manager.ISpecManager; import org.lamport.tla.toolbox.spec.manager.WorkspaceSpecManager; import org.lamport.tla.toolbox.spec.parser.ParserDependencyStorage; import org.lamport.tla.toolbox.ui.contribution.ParseStatusContributionItem; import org.lamport.tla.toolbox.ui.perspective.ProblemsPerspective; import org.lamport.tla.toolbox.util.TLAMarkerHelper; import org.lamport.tla.toolbox.util.UIHelper; import org.lamport.tla.toolbox.util.pref.IPreferenceConstants; import org.lamport.tla.toolbox.util.pref.PreferenceStoreHelper; import org.osgi.framework.BundleContext; /** * The activator class controls the plug-in life cycle */ public class Activator extends AbstractUIPlugin { // The plug-in ID public static final String PLUGIN_ID = "org.lamport.tla.toolbox"; // The shared instance private static Activator plugin; private static ISpecManager specManager; private static ParserDependencyStorage parserDependencyStorage; private ParseStatusContributionItem parseStatusWidget = null; /** * The constructor */ public Activator() { } public void start(BundleContext context) throws Exception { super.start(context); plugin = this; // register the listeners IWorkspace workspace = ResourcesPlugin.getWorkspace(); // install the parse status widget UIHelper.runUIAsync(new Runnable() { public void run() { parseStatusWidget = UIHelper.getStatusBarContributionItem(); parseStatusWidget.updateStatus(); } }); // update widget on resource modifications workspace.addResourceChangeListener(new IResourceChangeListener() { public void resourceChanged(IResourceChangeEvent event) { UIHelper.runUIAsync(new Runnable() { public void run() { parseStatusWidget = UIHelper.getStatusBarContributionItem(); parseStatusWidget.updateStatus(); } }); } }, IResourceChangeEvent.POST_BUILD); // react with window pop-up, if set up in the preferences workspace.addResourceChangeListener(new IResourceChangeListener() { /* (non-Javadoc) * @see org.eclipse.core.resources.IResourceChangeListener#resourceChanged(org.eclipse.core.resources.IResourceChangeEvent) */ public void resourceChanged(final IResourceChangeEvent event) { UIHelper.runUIAsync(new Runnable() { public void run() { // look up the preference for raising windows on errors boolean showErrors = PreferenceStoreHelper.getInstancePreferenceStore().getBoolean( IPreferenceConstants.P_PARSER_POPUP_ERRORS); if (showErrors) { Spec spec = Activator.getSpecManager().getSpecLoaded(); UIHelper.closeWindow(ProblemsPerspective.ID); // there were problems -> open the problem view // Instead of explicit status check, look on the problem markers // if (AdapterFactory.isProblemStatus(spec.getStatus())) if (TLAMarkerHelper.getProblemMarkers(spec.getProject(), null).length > 0) { UIHelper.openPerspectiveInWindowRight(ProblemsPerspective.ID, null, ProblemsPerspective.WIDTH); } } } }); } }, IResourceChangeEvent.POST_BUILD); } public void stop(BundleContext context) throws Exception { // unregister the listeners specManager.terminate(); specManager = null; plugin = null; super.stop(context); } /** * Returns the shared instance * * @return the shared instance */ public static Activator getDefault() { return plugin; } /** * Retrieves a working spec manager instance */ public static synchronized ISpecManager getSpecManager() { if (specManager == null) { specManager = new WorkspaceSpecManager(); } return specManager; } /** * Retrieves a working instance of parser dependency storage */ public static synchronized ParserDependencyStorage getModuleDependencyStorage() { if (parserDependencyStorage == null) { parserDependencyStorage = new ParserDependencyStorage(); } return parserDependencyStorage; } }
package org.lamport.tla.toolbox.spec; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.List; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IAdapterManager; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Platform; import org.eclipse.jface.text.ITextSelection; import org.lamport.tla.toolbox.Activator; import org.lamport.tla.toolbox.spec.parser.IParseConstants; import org.lamport.tla.toolbox.tool.SpecLifecycleParticipant; import org.lamport.tla.toolbox.util.AdapterFactory; import org.lamport.tla.toolbox.util.ResourceHelper; import org.lamport.tla.toolbox.util.compare.ResourceNameComparator; import org.lamport.tla.toolbox.util.pref.PreferenceStoreHelper; import tla2sany.modanalyzer.SpecObj; /** * Represents a specification handle in the toolbox * * In June 2010, LL added some fields by which handlers of different commands * could communicate with one another. I'm sure there's a more elegant way to * do this that involves another few levels of indirection, but I have the old-fashioned * belief that doing things the easy way and commenting what you do is better than * doing things the correct way that makes it impossible to figure out what * the hell is going on without learning yet another almost but not quite completely * undocumented Eclipse feature. * * * @version $Id$ * @author Simon Zambrovski */ public class Spec implements IAdaptable { /** * The following fields are used for remembering the jumping-off * point for a Goto Declaration or ShowDefinitions command, so we can return to it * with a Return from Goto Declaration command. They should probably * be changed to arrays so we can call return from a Sequence of such commands. */ private String openDeclModuleName; private ITextSelection openDeclSelection; /** * The following fields are used to remember the result of a Show Uses command so * the Goto Next Use and Goto Previous Use commands know where to go. * * The name of the module whose instances are being shown. If there * are more than one, this is set by user selection from a pop-up * dialog. */ private String moduleToShow = null; /** * The markers to be shown, sorted by the locations in which they * originally appeared. I don't think that order can change, * but what do I know? */ private IMarker[] markersToShow = null; /** * The index of the marker in markersToShow that is currently being * shown. */ private int currentSelection = 0; /* project handle */ private IProject project; /* root module handle */ private IFile rootFile; /* status of the specification */ private int status; /* the semantic tree produced by the parser */ private SpecObj specObj; /** * Creates a Spec handle for existing project. Use the factory method * {@link Spec#createNewSpec(String, String, Date)} if the project reference is not available * * @param project * project handle */ public Spec(IProject project) { this.project = project; initProjectProperties(); } /** * Factory method Creates a new specification, the underlying IProject link the root file * * @param name the name of the specification * @param rootFilename the path to the root file name * @param importExisting */ public static Spec createNewSpec(String name, String rootFilename, boolean importExisting) { IProject project = ResourceHelper.getProject(name, rootFilename, true, importExisting); PreferenceStoreHelper.storeRootFilename(project, rootFilename); Spec spec = new Spec(project); spec.setLastModified(); return spec; } /** * initializes the root module from the project properties */ public void initProjectProperties() { this.rootFile = PreferenceStoreHelper.readProjectRootFile(project); this.specObj = null; this.status = IParseConstants.UNPARSED; // Initialize the spec's ToolboxDirSize property. // Added by LL and Dan on 21 May 2010 ResourceHelper.setToolboxDirSize(this.project); // Assert.isNotNull(this.rootFile); // This assertion was preventing the Toolbox from starting, so LL // comented it out on 19 Mar 2011 and added the log message // on 3 Apr 2011. // To report this problem to the user, one can do the following: // - Add a failed field to the Spec object, initialized to false // - Set this field to true when the error occurs. // After the statement // spec = new Spec(projects[i]); // in the constructor of WorkspaceSpecManager, test this field and, // if true, take the appropriate action--probably popping up a warning // (if that's possible) or else putting the name of the spec in the // log, and also probably not executing the addSpec command that follows // this statement. if (this.rootFile == null) { Activator.logError("A spec did not load correctly, probably because it was modified outside the Toolbox." + "\n Error occurred in toolbox/spec/Spec.initProjectProperties()", null); } } /** * @return the lastModified */ public Date getLastModified() { if (IResource.NULL_STAMP == project.getModificationStamp()) { return null; } return new Date(project.getModificationStamp()); } /** * Touches the underlying resource */ public void setLastModified() { try { project.touch(new NullProgressMonitor()); } catch (CoreException e) { Activator.logError("Error changing the timestamp of the spec", e); } } /** * Retrieves the underlying project file * * @return the project */ public IProject getProject() { return project; } /** * @return the name */ public String getName() { return project.getName(); } /** * Retrieves the path to the file containing the root module * This is a convenience method for {@link getRootFile()#getLocation()#toOSString()} * @return the OS representation of the root file */ public String getRootFilename() { IPath location = rootFile.getLocation(); return location.toOSString(); } /** * Retrieves the handle to the root file * * @return IFile of the root */ public IFile getRootFile() { return this.rootFile; } /** * Retrieves parsing status * * See {@link IParseConstants} for possible values of status. * * @return the status */ public int getStatus() { return status; } /** * Sets parsing status. As a side effect the {@link SpecLifecycleParticipant}s get informed * * @param status the status to set */ public void setStatus(int status) { this.status = status; // informs Activator.getSpecManager().specParsed(this); } /** * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class) */ public Object getAdapter(Class adapter) { // lookup the IAdapterManager service IAdapterManager manager = Platform.getAdapterManager(); // forward the request to IAdapterManager service return manager.getAdapter(this, adapter); } /** * Retrieves the list of modules in the spec, or an empty list if no modules * <br> * The list is sorted on the resource name * * @return */ public IResource[] getModuleResources() { // TODO relate this list to the list of modules, which result after parse IResource[] modules = null; try { modules = getProject().members(IResource.NONE); // sort the markers List moduleList = new ArrayList(Arrays.asList(modules)); Collections.sort(moduleList, new ResourceNameComparator()); return (IResource[]) moduleList.toArray(new IResource[moduleList.size()]); } catch (CoreException e) { Activator.logError("Error retrieving the the spec modules", e); modules = new IResource[0]; } return modules; } /** * Returns the SpecObj */ public SpecObj getRootModule() { return this.specObj; } /** * Returns the SpecObj only on valid status */ public SpecObj getValidRootModule() { if (AdapterFactory.isProblemStatus(this.status)) { return null; } return getRootModule(); } /** * Sets the new spec object * @param specObj */ public void setSpecObj(SpecObj specObj) { this.specObj = specObj; } /** * @param openDeclModuleName the openDeclModuleName to set */ public void setOpenDeclModuleName(String openDeclModuleName) { this.openDeclModuleName = openDeclModuleName; } /** * @return the openDeclModuleName */ public String getOpenDeclModuleName() { return openDeclModuleName; } /** * @param openDeclSelection the openDeclSelection to set */ public void setOpenDeclSelection(ITextSelection openDeclSelection) { this.openDeclSelection = openDeclSelection; } /** * @return the openDeclSelection */ public ITextSelection getOpenDeclSelection() { return openDeclSelection; } /** * @param moduleToShow the moduleToShow to set */ public void setModuleToShow(String moduleToShow) { this.moduleToShow = moduleToShow; } /** * @return the moduleToShow */ public String getModuleToShow() { return moduleToShow; } /** * @param markersToShow the markersToShow to set */ public void setMarkersToShow(IMarker[] markersToShow) { this.markersToShow = markersToShow; } /** * @return the markersToShow */ public IMarker[] getMarkersToShow() { return markersToShow; } /** * @param currentSelection the currentSelection to set */ public void setCurrentSelection(int currentSelection) { this.currentSelection = currentSelection; } /** * @return the currentSelection */ public int getCurrentSelection() { return currentSelection; } }
package aQute.bnd.osgi; import static java.util.Objects.requireNonNull; import java.lang.annotation.ElementType; import java.lang.annotation.RetentionPolicy; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.stream.Stream; import aQute.bnd.osgi.Descriptors.TypeRef; import aQute.lib.converter.Converter; /* * This class is referenced in aQute.bnd.annotation.metatype.Configurable in constant * BND_ANNOTATION_CLASS_NAME */ public class Annotation { private static final Converter CONVERTER; static { CONVERTER = new Converter(); CONVERTER.hook(null, (t, o) -> { if (o instanceof Annotation && t instanceof Class<?> && ((Class<?>) t).isAnnotation()) { Annotation a = (Annotation) o; @SuppressWarnings("unchecked") Class<java.lang.annotation.Annotation> c = (Class<java.lang.annotation.Annotation>) t; return a.getAnnotation(c); } return null; }); } private final TypeRef name; private Map<String, Object> elements; private final ElementType member; private final RetentionPolicy policy; public Annotation(TypeRef name, Map<String, Object> elements, ElementType member, RetentionPolicy policy) { this.name = requireNonNull(name); this.elements = elements; this.member = requireNonNull(member); this.policy = requireNonNull(policy); } public TypeRef getName() { return name; } public ElementType getElementType() { return member; } public RetentionPolicy getRetentionPolicy() { return policy; } @Override public String toString() { return name + ":" + member + ":" + policy + ":" + (elements == null ? "{}" : elements); } @SuppressWarnings("unchecked") public <T> T get(String string) { if (elements == null) { return null; } return (T) elements.get(string); } public <T> Stream<T> stream(String key, Class<? extends T> type) { Object v = get(key); if (v == null) { return Stream.empty(); } if (v.getClass() .isArray()) { return Arrays.stream((Object[]) v) .map(type::cast); } return Stream.of(v) .map(type::cast); } public void put(String string, Object v) { if (elements == null) { elements = new LinkedHashMap<>(); } elements.put(string, v); } public boolean containsKey(String key) { if (elements == null) { return false; } return elements.containsKey(key); } public Set<String> keySet() { if (elements == null) { return Collections.emptySet(); } return elements.keySet(); } public Set<Entry<String, Object>> entrySet() { if (elements == null) { return Collections.emptySet(); } return elements.entrySet(); } public <T extends java.lang.annotation.Annotation> T getAnnotation() throws Exception { return getAnnotation(getClass().getClassLoader()); } public <T extends java.lang.annotation.Annotation> T getAnnotation(ClassLoader cl) throws Exception { String cname = name.getFQN(); try { @SuppressWarnings("unchecked") Class<T> c = (Class<T>) cl.loadClass(cname); return getAnnotation(c); } catch (ClassNotFoundException | NoClassDefFoundError e) { return null; } } public <T extends java.lang.annotation.Annotation> T getAnnotation(Class<T> c) throws Exception { if (elements == null) { elements = new LinkedHashMap<>(); } return CONVERTER.convert(c, elements); } public void merge(Annotation annotation) { merge(annotation.elements); } public void addDefaults(Clazz c) throws Exception { merge(c.getDefaults()); } private void merge(Map<String, Object> map) { if (map == null || map.isEmpty()) { return; } if (elements == null) { elements = new LinkedHashMap<>(map); } else { map.forEach((k, v) -> elements.putIfAbsent(k, v)); } } }
package Models; import Helpers.Json; import java.util.LinkedList; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import Helpers.JsonObject; import Models.Tile.TileType; public class BoardModel implements Serializable<BoardModel> { private JavaCell[][] map; private LinkedList<JavaCell> path; private ArrayList<JavaCell> connectedPalaces = new ArrayList<JavaCell>(); private JavaCell[] outerCells; public int cellId; public BoardModel() { this.map = new JavaCell[14][14]; this.path = new LinkedList<JavaCell>(); cellId = 0; outerCells = new JavaCell[50]; int i = 0; for (int x = 0; x < map.length; x++) { for (int y = 0; y < map[0].length; y++) { map[x][y] = new JavaCell(x, y, 0); if ((x == 0 || x == 13) && (y != 0 && y != 13)) { outerCells[i] = map[x][y]; i++; } else if ((y == 0 || y == 13) && (x != 0 && x != 13)) { outerCells[i] = map[x][y]; i++; } } } } public boolean placeTile(int xC, int yC, Tile tile, JavaPlayer player) { JavaCell[][] miniMap = createTestMap(xC, yC); TileType[][] tileCells = tile.getTileCells(); if (checkValidTilePlacement(xC, yC, tile, player, miniMap)) { /* * are we going to be creating the tile here? if we are then we need * to increase cellId here. */ cellId++; for (int i = 0; i < tileCells.length; i++) for (int j = 0; j < tileCells[i].length; j++) if (tileCells[i][j] != null) { map[miniMap[i][j].getX()][miniMap[i][j].getY()] .setCellType(tileCells[i][j]); map[miniMap[i][j].getX()][miniMap[i][j].getY()] .setCellId(cellId); map[miniMap[i][j].getX()][miniMap[i][j].getY()] .setElevation(map[miniMap[i][j].getX()][miniMap[i][j] .getY()].getElevation() + 1); } if(placedLandTile(xC, yC)) player.placedLandTile(); System.out.println(toString()); return true; } return false; } public boolean placedLandTile(int xC, int yC){ if(map[xC][yC].getCellType() == "village" || map[xC][yC].getCellType() == "rice") return true; return false; } public boolean checkValidTilePlacement(int xC, int yC, Tile tile, JavaPlayer player, JavaCell[][] miniMap) { // creating a small map with the cells we need to compare // JavaCell[][] miniMap = createTestMap(xC, yC); int neededActionPoints = checkNeededActionPoints(miniMap, tile); //boolean needed to check the amount of available AP points boolean isLandTile = "villagerice".contains(tile.getTileCells()[1][1].toString()); System.out.println("palace placement: " + checkPalacePlacement(miniMap, tile)); System.out.println("palace tilesBelow: " + checkTilesBelow(miniMap, tile)); System.out.println("palace elevation: " + checkElevation(miniMap, tile, xC, yC)); System.out.println("palace I: " + checkIrrigationPlacement(miniMap, tile)); System.out.println("palace DevOnCell: " + checkDeveloperOnCell(miniMap, tile)); System.out.println("palace CityConn: " + checkCityConnection(miniMap, tile)); System.out.println("palace edge: " + checkEdgePlacement(miniMap, tile)); System.out.println("palace action: " + player.decrementNActionPoints(neededActionPoints, isLandTile)); if (checkPalacePlacement(miniMap, tile) && checkTilesBelow(miniMap, tile) && checkElevation(miniMap, tile, xC, yC) && checkIrrigationPlacement(miniMap, tile) && checkDeveloperOnCell(miniMap, tile) && checkCityConnection(miniMap, tile) && checkEdgePlacement(miniMap, tile) && player.decrementNActionPoints(neededActionPoints, isLandTile)) { return true; } return false; } private JavaCell[][] createTestMap(int xC, int yC) { JavaCell[][] testingMap = new JavaCell[3][3]; for (int i = 0, x = xC - 1; i < 3; i++, x++) { for (int j = 0, y = yC - 1; j < 3; j++, y++) { if ((x >= 0 && x <= map.length) && (y >= 0) && (y <= map[0].length)) { testingMap[i][j] = map[x][y]; } } } return testingMap; } private int checkNeededActionPoints(JavaCell[][] miniMap, Tile tile) { int outsideCount = 1; int mapRowLength = map.length; int mapColumnSize = map[0].length; TileType[][] tileCells = tile.getTileCells(); for (int i = 0; i < tileCells.length; i++) { for (int j = 0; j < tileCells[i].length; j++) { if (tileCells[i][j] != null) { if (miniMap[i][j] != null && ((i == mapRowLength) || (i == mapColumnSize) || ((i != 0) && (i != mapColumnSize - 1) && (j == 0)) || ((i != 0) && (i != mapColumnSize) && (j == mapRowLength)))) { outsideCount++; } } } } return outsideCount; } private boolean checkPalacePlacement(JavaCell[][] miniMap, Tile tile) { TileType[][] tileCells = tile.getTileCells(); for (int i = 0; i < tileCells.length; i++) { for (int j = 0; j < tileCells[i].length; j++) { if (tileCells[i][j] != null) { if (miniMap[i][j] != null && miniMap[i][j].getCellType() != null && miniMap[i][j].getCellType() == "palace") { return false; } } } } return true; } private boolean checkTilesBelow(JavaCell[][] miniMap, Tile tile) { TileType[][] tileCells = tile.getTileCells(); int numberOfTilesBelow = 0; int testId = miniMap[1][1].getCellId(); int testing = 0; for (int i = 0; i < tileCells.length; i++) { for (int j = 0; j < tileCells[i].length; j++) { if (tileCells[i][j] != null && miniMap[i][j].getElevation() >= 0) { System.out.println("in the 1st if statement"); if (testId == 0) { testId = miniMap[i][j].getCellId(); System.out.println("The id is: " + testId); } else { if (testId != miniMap[i][j].getCellId()) return true; else numberOfTilesBelow++; } } if( miniMap[i][j] != null && miniMap[i][j].getElevation() >= 0 && miniMap[1][1].getCellId() == miniMap[i][j].getCellId()){ testing++; } } } System.out.println("The # of tiles below: " + numberOfTilesBelow + "testing: " + testing); int number; if (tile.getType() == "two") { number = 2; } else if (tile.getType() == "three") { number = 3; } else if (tile.getType() == "one") { number = 1; } else { number = 0; } if (number != numberOfTilesBelow || testing > numberOfTilesBelow) return true; else return false; } private boolean checkElevation(JavaCell[][] miniMap, Tile tile, int xC, int yC) { TileType[][] tileCells = tile.getTileCells(); int elevation = map[xC][yC].getElevation(); for (int i = 0; i < tileCells.length; i++) { for (int j = 0; j < tileCells[i].length; j++) { if (tileCells[i][j] != null && miniMap[i][j].getElevation() != elevation) { return false; } } } return true; } private boolean checkIrrigationPlacement(JavaCell[][] miniMap, Tile tile) { TileType[][] tileCells = tile.getTileCells(); for (int i = 0; i < tileCells.length; i++) { for (int j = 0; j < tileCells[i].length; j++) { if (tileCells[i][j] != null) { if (miniMap[i][j] != null && miniMap[i][j].getCellType() != null && miniMap[i][j].getCellType() == "irrigation") { return false; } } } } return true; } private boolean checkDeveloperOnCell(JavaCell[][] miniMap, Tile tile) { TileType[][] tileCells = tile.getTileCells(); for (int i = 0; i < tileCells.length; i++) { for (int j = 0; j < tileCells[i].length; j++) { if (tileCells[i][j] != null) { if (miniMap[i][j] != null && miniMap[i][j].hasDeveloper()) { return false; } } } } return true; } // cannot place a village next to 2 palaces private boolean checkCityConnection(JavaCell[][] miniMap, Tile tile) { JavaCell[][] mapCopy = new JavaCell[map.length][map[0].length]; for (int i = 0; i < map.length; i++) { for (int j = 0; j < map[i].length; j++) { mapCopy[i][j] = map[i][j]; } } TileType[][] tileCells = tile.getTileCells(); for (int i = 0; i < tileCells.length; i++) { for (int j = 0; j < tileCells[0].length; j++) { if (tileCells[i][j] != null && tileCells[i][j] == TileType.village && miniMap[i][j] != null) { findPalaceSpaces(miniMap[i][j].getX(), miniMap[i][j].getY(), mapCopy); } } } for (int i = 0; i < connectedPalaces.size(); i++) { for (int j = i + 1; j < connectedPalaces.size(); j++) { if (connectedPalaces.get(i) != null && connectedPalaces.get(j) != null) { if (connectedPalaces.get(i) != connectedPalaces.get(j)) { return false; } } } } return true; } private void findPalaceSpaces(int x, int y, JavaCell[][] map) { boolean canUp = (x - 1 >= 0); boolean canDown = (x + 1 < map.length); boolean canRight = (y + 1 < map[0].length); boolean canLeft = (y - 1 >= 0); if (map[x][y] != null && map[x][y].getCellType() != null && map[x][y].getCellType() == "palace") { connectedPalaces.add(map[x][y]); } map[x][y] = null; // fixed the bug here if (canUp && (map[x - 1][y] != null && (map[x - 1][y].getCellType() == "village" || map[x - 1][y] .getCellType() == "palace"))) { findPalaceSpaces(x - 1, y, map); } if (canDown && (map[x + 1][y] != null && (map[x + 1][y].getCellType() == "village" || map[x + 1][y] .getCellType() == "palace"))) { findPalaceSpaces(x + 1, y, map); } if (canLeft && (map[x][y - 1] != null && (map[x][y - 1].getCellType() == "village" || map[x][y - 1] .getCellType() == "palace"))) { findPalaceSpaces(x, y - 1, map); } if (canRight && (map[x][y + 1] != null && (map[x][y + 1].getCellType() == "village" || map[x][y + 1] .getCellType() == "palace"))) { findPalaceSpaces(x, y + 1, map); } return; } public boolean canPlacePalace(int x, int y, JavaCell palace) { return true; } public boolean canUpgradePalace(int x, int y, JavaCell palace) { return false; } //This method is so swag money $$$ private static int findNumberConnected(int x, int y, JavaCell[][] map) { JavaCell[][] copy = new JavaCell[14][14]; for (int i = 0; i < 14; i++) for (int j = 0; j < 14; j++) { { copy[i][j] = map[i][j]; } } boolean canUp = (x - 1 >= 0); boolean canDown = (x + 1 < map.length); boolean canRight = (y + 1 < map[0].length); boolean canLeft = (y - 1 >= 0); int up = 0; int down = 0; int right = 0; int left = 0; // fixed the bug here if (canUp && (map[x - 1][y] != null && (map[x - 1][y].getCellType() == "village" ))) { up = findNumberConnected(x - 1, y, map); } if (canDown && (map[x + 1][y] != null && (map[x + 1][y].getCellType() == "village" ))) { up = findNumberConnected(x + 1, y, map); } if (canLeft && (map[x][y - 1] != null && (map[x][y - 1].getCellType() == "village" ))) { up = findNumberConnected(x, y - 1, map); } if (canRight && map[x][y + 1] != null && (map[x][y + 1].getCellType() == "village" )) { up = findNumberConnected(x, y + 1, map); } return up + left + right + down + 1; } // Returns the number of village Spaces surrounding the given Cell. Called // by checkIfICanUpgradePalace to make sure number of surrounding villages // is greater than or equal to the palace number. /*private int checkForNumberOfVillages(Cell cell) { setConnectedCells(cell); return cell.getConnectedCells().size(); }*/ private boolean checkEdgePlacement(JavaCell[][] miniMap, Tile tile) { TileType[][] tileCells = tile.getTileCells(); JavaCell[] cells = new JavaCell[4]; int count = 0; int x = 0; for (int i = 0; i < miniMap.length; i++) for (int j = 0; j < miniMap[i].length; j++) if (tileCells[i][j] != null){ cells[x] = miniMap[i][j]; x++; } int number; if (tile.getType() == "two") { number = 2; } else if (tile.getType() == "three") { number = 3; } else if (tile.getType() == "one") { number = 1; } else { number = 0; } System.out.println("in checkedge the outer cell length is: " + outerCells.length); for (int i = 0; i < outerCells.length; i++) { if (cells[0] != null && outerCells[i] != null && cells[0].getX() == outerCells[i].getX() && cells[0].getY() == outerCells[i].getY()) count++; if (cells[1] != null && outerCells[i] != null && cells[1].getX() == outerCells[i].getX() && cells[1].getY() == outerCells[i].getY()) count++; if (cells[2] != null && outerCells[i] != null && cells[2].getX() == outerCells[i].getX() && cells[2].getY() == outerCells[i].getY()) count++; if (cells[3] != null && outerCells[i] != null && cells[3].getX() == outerCells[i].getX() && cells[3].getY() == outerCells[i].getY()) count++; } System.out.println("count: " + count + "number" + number); if (count == number) { return false; } return true; } public JavaCell getCellAtXY(int x, int y){ return map[x][y]; } public boolean placeDeveloper(JavaCell jc, JavaPlayer player) { // Check with validity method first if (!canPlaceDeveloper(jc, player)) return false; // Set developer on board player.placeDevOnBoard(jc); return true; // TODO Specific index?? cc: Cameron } public boolean canPlaceDeveloper(JavaCell locationCell, JavaPlayer player) { // Can only place on village or rice space if (!(isTileOrLand(locationCell.getX(), locationCell.getY()))) return false; // Can only place if no developer is already occupying space if (locationCell.hasDeveloper()) return false; // Space must be on or inside border into central java if (locationCell.isBorder()) { // If it's on the border, must see that there is a land space tile // there // But we already checked that above, so by this point we are good } // If it's not on the border, have to check that at least on adjacent // space is open in outer java else if (!hasAdjacentEmptyTile(locationCell)) return false; // Check that player has available AP for this // First determine type of move/cost if (!player.decrementNActionPoints(locationCell.getActionPointsFromDeveloperMove(), false) || !player.canPlaceDeveloperOnBoard()) // TODO: Check lowlands or // mountains return false; return true; } public boolean removeDatDeveloperOffDaBoard(JavaCell jailCell, JavaPlayer theHomie) { // Check if its an border cell if (!jailCell.isBorder()) { // If its not on the border, needs to be next to it if(!jailCell.isNextToBorder()) return false; // Can't do it, homie goes back to Jail // If it's next to the border, needs an adjacent empty tile in border if(!hasAdjacentEmptyTile(jailCell)) return false; // Can't do it, homie goes back to Jail } // Else, he is on the border, we can proceed with bail procedures if(!theHomie.decrementNActionPoints(jailCell.getActionPointsFromDeveloperMove(), false)) return false; // Can't do it, homie goes back to Jail // By this point, we've made it through all the bail procedures and homie has paid his dues (action points) // He is now free to go theHomie.removeDeveloperFromArray(); return true; // The homie is free ~ ~ ~ } public boolean hasAdjacentEmptyTile(JavaCell cell) { int x = cell.getX(); int y = cell.getY(); // Check if the cell is adjacent to any empty border cells if (x + 1 == 13) { if (map[13][y].getCellType().equals("blank")) return true; } if (x - 1 == 0) { if (map[0][y].getCellType().equals("blank")) return true; } if (y + 1 == 13) { if (map[x][13].getCellType().equals("blank")) return true; } if (y - 1 == 0) { if (map[x][0].getCellType().equals("blank")) return true; } return false; } public boolean isTileOrLand(int x, int y) { if (!(map[x][y].getCellType().equals("village") || map[x][y] .getCellType().equals("rice"))) return false; return true; } // Method to determine cost of moving dev onto board: 2 from lowlands, 1 // from mountains public int getCost(JavaCell cell) { int x = cell.getX(); if (x <= 6) return 2; else return 1; } public void removeDeveloper(JavaCell javaCell, JavaPlayer player) { // Turn off hasDeveloper javaCell.removeDeveloper(); // Remove currently selected developer from dev array player.removeDeveloperFromArray(); // Must check that this works later // on TODO // Decrement actions points player.decrementNActionPoints(1, false); } public boolean moveDeveloper(JavaPlayer player) { int pathSize = path.size(); int actionPoints = 0; JavaCell currentCell = path.removeLast(); JavaCell nextCell = path.removeLast(); for (int i = 0; i < pathSize - 2; i++) { if (fromVillageToRice(currentCell, nextCell)) { actionPoints++; } currentCell = nextCell; nextCell = path.removeLast(); } if (fromVillageToRice(currentCell, nextCell)) { actionPoints++; } if (player.decrementNActionPoints(actionPoints, false)) { player.associateDeveloperWithCell(nextCell); return true; } return false; } public boolean addJavaCellToPath(JavaCell javaCell) { int pathSize = path.size(); LinkedList<JavaCell> temp = new LinkedList<JavaCell>(); for (int i = 0; i < pathSize; i++) { temp.push(path.pop()); } JavaCell currentCell = temp.pop(); int count = 0; while ((currentCell != javaCell) && count < pathSize - 1) { path.push(currentCell); currentCell = temp.pop(); count++; } path.push(currentCell); return true; } public boolean hasAdjacentLandSpaceTile(JavaCell cell) { int x = cell.getX(); int y = cell.getY(); // Check if the cell is adjacent to any border cells if (x + 1 == 13) { if (isTileOrLand(x + 1, y)) { return true; } } if (x - 1 == 0) { if (isTileOrLand(x - 1, y)) return true; } if (y + 1 == 13) { if (isTileOrLand(x, y + 1)) { return true; } } if (y - 1 == 0) { if (isTileOrLand(x, y - 1)) { return true; } } return false; } public JavaCell[][] getMap() { return map; } // Given a root cell, finds and adds to a list all adjacent cells with the // same type // This can be used to retrieve the cells that make up a city. public ArrayList<JavaCell> getCityFromRootCell(JavaCell root) { ArrayList<JavaCell> connected = new ArrayList<JavaCell>(); int x = root.getX(); int y = root.getY(); connected.add(root); int i = 0; while (i < connected.size()) { // Cell temp = connected.get(i); HashSet<JavaCell> adjacent = new HashSet<JavaCell>(); if (y < 14 && map[y + 1][x].getCellType().equals("village") || map[y + 1][x].getCellType().equals("palace")) adjacent.add(map[y + 1][x]); if (y > 0 && map[y - 1][x].getCellType().equals("village") || map[y - 1][x].getCellType().equals("palace")) adjacent.add(map[y - 1][x]); if (x < 14 && map[y][x + 1].getCellType().equals("village") || map[y][x + 1].getCellType().equals("palace")) adjacent.add(map[y][x + 1]); if (x > 0 && map[y][x - 1].getCellType().equals("village") || map[y][x - 1].getCellType().equals("palace")) adjacent.add(map[y][x - 1]); Iterator<JavaCell> it = adjacent.iterator(); while (it.hasNext()) { JavaCell next = (JavaCell) it.next(); if (!connected.contains(next)) connected.add(next); } i++; } return connected; } public boolean nextToIrrigation(int xC, int yC, Tile tile) { JavaCell[][] mapCopy = new JavaCell[map.length][map[0].length]; for (int i = 0; i < map.length; i++) { for (int j = 0; j < map[i].length; j++) { mapCopy[i][j] = map[i][j]; } } if (yC < 14 && map[xC][yC + 1].getCellType().equals("irrigation")) { return isIrrigationSurrounded(mapCopy, xC, yC + 1); } if (yC > 0 && map[xC][yC + 1].getCellType().equals("irrigation")) { return isIrrigationSurrounded(mapCopy, xC, yC - 1); } if (xC < 14 && map[xC + 1][yC].getCellType().equals("irrigation")) { return isIrrigationSurrounded(mapCopy, xC + 1, yC); } if (xC > 0 && map[xC + 1][yC].getCellType().equals("irrigation")) { return isIrrigationSurrounded(mapCopy, xC - 1, yC); } return false; } public boolean isIrrigationSurrounded(JavaCell[][] mapCopy, int xC, int yC) { boolean right = false; boolean left = false; boolean up = false; boolean down = false; if (xC < 13 && xC > 0) { if (map[xC + 1][yC].getCellType().equals("blank")) { return false; } else if (map[xC + 1][yC].getCellType().equals("irrigation")) { return isIrrigationSurrounded(mapCopy, xC + 1, yC); } else down = true; } if (xC < 14 && xC > 1) { if (map[xC - 1][yC].getCellType().equals("blank")) { return false; } else if (map[xC - 1][yC].getCellType().equals("irrigation")) { return isIrrigationSurrounded(mapCopy, xC - 1, yC); } else left = true; } if (yC < 13 && yC > 0) { if (map[xC][yC + 1].getCellType().equals("blank")) { return false; } else if (map[xC][yC + 1].getCellType().equals("irrigation")) { return isIrrigationSurrounded(mapCopy, xC, yC + 1); } else up = true; } if (yC < 14 && yC > 1) { if (map[xC][yC - 1].getCellType().equals("blank")) { return false; } else if (map[xC][yC - 1].getCellType().equals("irrigation")) { return isIrrigationSurrounded(mapCopy, xC, yC - 1); } else down = true; } if (up && down && right && left) { return true; } return false; } public boolean fromVillageToRice(JavaCell jc1, JavaCell jc2) { if (jc1.getCellType().equals("village") && jc2.getCellType().equals("rice") || jc1.getCellType().equals("rice") && jc2.getCellType().equals("village")) { return true; } return false; } public String toString() { String s = ""; for (int i = 0; i < map.length; i++) { for (int j = 0; j < map[i].length; j++) { s += map[i][j].getElevation() + " "; } s += "\n"; } return s; } @Override public String serialize() { return Json.jsonObject(Json.jsonMembers( Json.jsonPair("map", Json.serializeArray(map)), Json.jsonPair("path", Json.serializeArray(path)), Json.jsonPair("connectedPalaces", Json.serializeArray(connectedPalaces)))); } @Override public BoardModel loadObject(JsonObject json) { map = new JavaCell[json.getJsonObjectArray("map").length][(((JsonObject[][]) json .getObject("map"))[0]).length]; for (int x = 0; x < json.getJsonObjectArray("map").length; ++x) for (int y = 0; y < ((JsonObject[]) (Object) json .getJsonObjectArray("map")[0]).length; ++y) map[x][y] = (new JavaCell(-1, -1, -1)) .loadObject(((JsonObject[][]) json.getObject("map"))[x][y]); path = new LinkedList<JavaCell>(); for (JsonObject cell : json.getJsonObjectArray("path")) path.push(map[(new JavaCell(-1, -1, -1)).loadObject(cell).xVal][(new JavaCell( -1, -1, -1)).loadObject(cell).yVal]); connectedPalaces = new ArrayList<JavaCell>(); for (JsonObject cell : json.getJsonObjectArray("connectedPalaces")) connectedPalaces.add(map[(new JavaCell(-1, -1, -1)) .loadObject(cell).xVal][(new JavaCell(-1, -1, -1)) .loadObject(cell).yVal]); return this; } public int getNextCellId() { return ++cellId; } }
package Models; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import CellsAndComponents.Inhabitant; import CellsAndComponents.Sugar; import CellsAndComponents.Agent; import javafx.geometry.Point2D; import javafx.scene.paint.Color; import CellsAndComponents.Cell; import CellsAndComponents.AdvancedCell; import Graphs.BaseGraph; /** * This class implements the SugarScape model and extends BaseModel. * * @author Megan Gutter and Sierra Smith * */ public class Sugarscape extends BaseModel { private static final int SUGAR_GROW_BACK_RATE = 1; private static final int SUGAR_GROW_BACK_INTERVAL = 1; private static final int WITH_AGENT = -1; private static final Color WITH_AGENT_COLOR = Color.RED; private static final double MIN_NUM_AGENTS = 0; private static final double MAX_NUM_AGENTS = 100; private int sugarGrowCounter; public Sugarscape(Map<String, Double> parameters) { super(parameters, 2); List<String> myStates = new ArrayList<String>(Arrays.asList("agent")); List<Color> myColors = new ArrayList<>(Arrays.asList(WITH_AGENT_COLOR)); List<Integer> myInts = new ArrayList<>(Arrays.asList(WITH_AGENT)); initializeMaps(myStates, myInts, myColors); sugarGrowCounter = 0; try { getParameterValuesMap().put("numAgents", parameters.get("numAgents")); } catch (NullPointerException e) { getParameterValuesMap().put("numAgents", (MIN_NUM_AGENTS + MAX_NUM_AGENTS) / 2); } } @Override public Cell updateFutureState(Cell cellToUpdate, Collection<Cell> neighbors) { return null; } public Collection<Cell> updateFutureStates(Iterable<Cell> cellsToUpdate, BaseGraph graph) { ArrayList<Cell> shuffledCells = new ArrayList<Cell>( (ArrayList<Cell>) cellsToUpdate); Collections.shuffle(shuffledCells); for (Cell c : shuffledCells) { AdvancedCell curCell = (AdvancedCell) c; if (curCell.getNumInhabitants() > 0) { ArrayList<AdvancedCell> possibleCells = (ArrayList<AdvancedCell>) getVacantPatchesInSight( curCell, graph); ArrayList<AdvancedCell> possibleMaxSugar = (ArrayList<AdvancedCell>) findMaxSugarCells(possibleCells); AdvancedCell toMoveTo = getClosest(possibleMaxSugar, curCell, graph); moveAgent(toMoveTo, curCell); ((Agent) toMoveTo.getInhabitants().get(0)) .addSugar(((Sugar) toMoveTo.getPatch()) .getSugarAmount()); ((Sugar) toMoveTo.getPatch()).takeAllSugar(); if (((Agent) toMoveTo.getInhabitants().get(0)).checkDead()) { toMoveTo.getInhabitants().remove(0); } else { changeFutureState(toMoveTo, WITH_AGENT, WITH_AGENT_COLOR); } } } sugarGrowCounter += 1; for (Cell c : shuffledCells) { AdvancedCell curCell = (AdvancedCell) c; if (sugarGrowCounter >= SUGAR_GROW_BACK_INTERVAL) { ((Sugar) curCell.getPatch()) .sugarGrowBack(SUGAR_GROW_BACK_RATE); } if (curCell.getNumInhabitants() == 0) { // change Orange later to be based off of amount changeFutureState(curCell, ((Sugar) curCell.getPatch()).getSugarAmount(), Color.ORANGE); } } return shuffledCells; } public void assignAdditionalCellInfo(BaseGraph graph) { ArrayList<Cell> shuffledCells = new ArrayList<Cell>( (ArrayList<Cell>) graph.getAllCells()); Collections.shuffle(shuffledCells); for (int i = 0; i < getParameterValuesMap().get("numAgents"); i++) { AdvancedCell toAddto = (AdvancedCell) shuffledCells.get(i); toAddto.addInhabitant(new Agent(WITH_AGENT)); } } private Collection<AdvancedCell> getVacantPatchesInSight( AdvancedCell curCell, BaseGraph graph) { int vision = ((Agent) curCell.getInhabitants().get(0)).getVision(); List<AdvancedCell> possibleCells = new ArrayList<AdvancedCell>(); for (int i = 1; i <= vision; i++) { if (checkIfVacant(curCell, graph, i, 0) != null) { possibleCells.add(checkIfVacant(curCell, graph, i, 0)); } if (checkIfVacant(curCell, graph, -i, 0) != null) { possibleCells.add(checkIfVacant(curCell, graph, -i, 0)); } if (checkIfVacant(curCell, graph, 0, i) != null) { possibleCells.add(checkIfVacant(curCell, graph, 0, i)); } if (checkIfVacant(curCell, graph, 0, -i) != null) { possibleCells.add(checkIfVacant(curCell, graph, 0, -i)); } } return possibleCells; } private AdvancedCell checkIfVacant(AdvancedCell curCell, BaseGraph graph, int x, int y) { Point2D change = new Point2D(x, y); AdvancedCell possible = (AdvancedCell) graph.getTranslatedCell(curCell, change); if (possible != null && possible.getNumInhabitants() == 0) { return possible; } return null; } private Collection<AdvancedCell> findMaxSugarCells( ArrayList<AdvancedCell> possibleCells) { int maxSugar = 0; for (AdvancedCell curCell : possibleCells) { if (((Sugar) curCell.getPatch()).getSugarAmount() > maxSugar) { maxSugar = ((Sugar) curCell.getPatch()).getSugarAmount(); } } ArrayList<AdvancedCell> possibleMaxSugar = new ArrayList<AdvancedCell>(); for (AdvancedCell curCell : possibleCells) { if (((Sugar) curCell.getPatch()).getSugarAmount() == maxSugar) { possibleMaxSugar.add(curCell); } } return possibleMaxSugar; } private AdvancedCell getClosest(List<AdvancedCell> possibleCells, AdvancedCell curCell, BaseGraph graph) { Point2D curPoint = graph.getPointFromCell(curCell); double maxDistance = Double.MAX_VALUE; AdvancedCell toReturn = null; for (AdvancedCell c : possibleCells) { double cellDistance = curPoint.distance(graph.getPointFromCell(c)); if (cellDistance < maxDistance) { toReturn = c; maxDistance = cellDistance; } } return toReturn; } private void moveAgent(AdvancedCell newCell, AdvancedCell oldCell) { Inhabitant toMove = oldCell.getInhabitants().get(0); newCell.addInhabitant(toMove); oldCell.getInhabitants().remove(0); } @Override public Color getDefaultColor() { return null; } @Override public int getDefaultState() { return 0; } @Override //error check? public int getIntForState(String state) { if (state.equals("agent")) { return getStateToIntMap().get(state); } return Integer.parseInt(state); } }
package ly.count.android.sdk; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.net.Uri; import android.util.Log; import java.io.PrintWriter; import java.io.StringWriter; import java.net.MalformedURLException; import java.net.URL; import java.util.Calendar; import java.util.List; import java.util.Map; import java.util.HashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class Countly { /** * Current version of the Count.ly Android SDK as a displayable string. */ public static final String COUNTLY_SDK_VERSION_STRING = "16.02.02"; /** * Default string used in the begin session metrics if the * app version cannot be found. */ public static final String DEFAULT_APP_VERSION = "1.0"; /** * Tag used in all logging in the Count.ly SDK. */ public static final String TAG = "Countly"; /** * Determines how many custom events can be queued locally before * an attempt is made to submit them to a Count.ly server. */ private static final int EVENT_QUEUE_SIZE_THRESHOLD = 10; /** * How often onTimer() is called. */ private static final long TIMER_DELAY_IN_SECONDS = 60; protected static List<String> publicKeyPinCertificates; /** * Enum used in Countly.initMessaging() method which controls what kind of * app installation it is. Later (in Countly Dashboard or when calling Countly API method), * you'll be able to choose whether you want to send a message to test devices, * or to production ones. */ public static enum CountlyMessagingMode { TEST, PRODUCTION, } private static class SingletonHolder { static final Countly instance = new Countly(); } private ConnectionQueue connectionQueue_; @SuppressWarnings("FieldCanBeLocal") private ScheduledExecutorService timerService_; private EventQueue eventQueue_; private long prevSessionDurationStartTime_; private int activityCount_; private boolean disableUpdateSessionRequests_; private boolean enableLogging_; private Countly.CountlyMessagingMode messagingMode_; private Context context_; //user data access public static UserData userData; //track views private String lastView = null; private int lastViewStart = 0; private boolean firstView = true; private boolean autoViewTracker = false; /** * Returns the Countly singleton. */ public static Countly sharedInstance() { return SingletonHolder.instance; } /** * Constructs a Countly object. * Creates a new ConnectionQueue and initializes the session timer. */ Countly() { connectionQueue_ = new ConnectionQueue(); Countly.userData = new UserData(connectionQueue_); timerService_ = Executors.newSingleThreadScheduledExecutor(); timerService_.scheduleWithFixedDelay(new Runnable() { @Override public void run() { onTimer(); } }, TIMER_DELAY_IN_SECONDS, TIMER_DELAY_IN_SECONDS, TimeUnit.SECONDS); } public Countly init(final Context context, final String serverURL, final String appKey) { return init(context, serverURL, appKey, null, OpenUDIDAdapter.isOpenUDIDAvailable() ? DeviceId.Type.OPEN_UDID : DeviceId.Type.ADVERTISING_ID); } public Countly init(final Context context, final String serverURL, final String appKey, final String deviceID) { return init(context, serverURL, appKey, deviceID, null); } public synchronized Countly init(final Context context, final String serverURL, final String appKey, final String deviceID, DeviceId.Type idMode) { if (context == null) { throw new IllegalArgumentException("valid context is required"); } if (!isValidURL(serverURL)) { throw new IllegalArgumentException("valid serverURL is required"); } if (appKey == null || appKey.length() == 0) { throw new IllegalArgumentException("valid appKey is required"); } if (deviceID != null && deviceID.length() == 0) { throw new IllegalArgumentException("valid deviceID is required"); } if (deviceID == null && idMode == null) { if (OpenUDIDAdapter.isOpenUDIDAvailable()) idMode = DeviceId.Type.OPEN_UDID; else if (AdvertisingIdAdapter.isAdvertisingIdAvailable()) idMode = DeviceId.Type.ADVERTISING_ID; } if (deviceID == null && idMode == DeviceId.Type.OPEN_UDID && !OpenUDIDAdapter.isOpenUDIDAvailable()) { throw new IllegalArgumentException("valid deviceID is required because OpenUDID is not available"); } if (deviceID == null && idMode == DeviceId.Type.ADVERTISING_ID && !AdvertisingIdAdapter.isAdvertisingIdAvailable()) { throw new IllegalArgumentException("valid deviceID is required because Advertising ID is not available (you need to include Google Play services 4.0+ into your project)"); } if (eventQueue_ != null && (!connectionQueue_.getServerURL().equals(serverURL) || !connectionQueue_.getAppKey().equals(appKey) || !DeviceId.deviceIDEqualsNullSafe(deviceID, idMode, connectionQueue_.getDeviceId()) )) { throw new IllegalStateException("Countly cannot be reinitialized with different values"); } // In some cases CountlyMessaging does some background processing, so it needs a way // to start Countly on itself if (MessagingAdapter.isMessagingAvailable()) { MessagingAdapter.storeConfiguration(context, serverURL, appKey, deviceID, idMode); } // if we get here and eventQueue_ != null, init is being called again with the same values, // so there is nothing to do, because we are already initialized with those values if (eventQueue_ == null) { DeviceId deviceIdInstance; if (deviceID != null) { deviceIdInstance = new DeviceId(deviceID); } else { deviceIdInstance = new DeviceId(idMode); } final CountlyStore countlyStore = new CountlyStore(context); deviceIdInstance.init(context, countlyStore, true); connectionQueue_.setServerURL(serverURL); connectionQueue_.setAppKey(appKey); connectionQueue_.setCountlyStore(countlyStore); connectionQueue_.setDeviceId(deviceIdInstance); eventQueue_ = new EventQueue(countlyStore); } context_ = context; // context is allowed to be changed on the second init call connectionQueue_.setContext(context); return this; } /** * Checks whether Countly.init has been already called. * @return true if Countly is ready to use */ public synchronized boolean isInitialized() { return eventQueue_ != null; } public Countly initMessaging(Activity activity, Class<? extends Activity> activityClass, String projectID, Countly.CountlyMessagingMode mode) { return initMessaging(activity, activityClass, projectID, null, mode); } public synchronized Countly initMessaging(Activity activity, Class<? extends Activity> activityClass, String projectID, String[] buttonNames, Countly.CountlyMessagingMode mode) { if (mode != null && !MessagingAdapter.isMessagingAvailable()) { throw new IllegalStateException("you need to include countly-messaging-sdk-android library instead of countly-sdk-android if you want to use Countly Messaging"); } else { messagingMode_ = mode; if (!MessagingAdapter.init(activity, activityClass, projectID, buttonNames)) { throw new IllegalStateException("couldn't initialize Countly Messaging"); } } if (MessagingAdapter.isMessagingAvailable()) { MessagingAdapter.storeConfiguration(connectionQueue_.getContext(), connectionQueue_.getServerURL(), connectionQueue_.getAppKey(), connectionQueue_.getDeviceId().getId(), connectionQueue_.getDeviceId().getType()); } return this; } public synchronized void halt() { eventQueue_ = null; final CountlyStore countlyStore = connectionQueue_.getCountlyStore(); if (countlyStore != null) { countlyStore.clear(); } connectionQueue_.setContext(null); connectionQueue_.setServerURL(null); connectionQueue_.setAppKey(null); connectionQueue_.setCountlyStore(null); prevSessionDurationStartTime_ = 0; activityCount_ = 0; } public synchronized void onStart(Activity activity) { appLaunchDeepLink = false; if (eventQueue_ == null) { throw new IllegalStateException("init must be called before onStart"); } ++activityCount_; if (activityCount_ == 1) { onStartHelper(); } //check if there is an install referrer data String referrer = ReferrerReceiver.getReferrer(context_); if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Checking referrer: " + referrer); } if(referrer != null){ connectionQueue_.sendReferrerData(referrer); ReferrerReceiver.deleteReferrer(context_); } CrashDetails.inForeground(); if(autoViewTracker){ recordView(activity.getClass().getName()); } } /** * Called when the first Activity is started. Sends a begin session event to the server * and initializes application session tracking. */ void onStartHelper() { prevSessionDurationStartTime_ = System.nanoTime(); connectionQueue_.beginSession(); } public synchronized void onStop() { if (eventQueue_ == null) { throw new IllegalStateException("init must be called before onStop"); } if (activityCount_ == 0) { throw new IllegalStateException("must call onStart before onStop"); } --activityCount_; if (activityCount_ == 0) { onStopHelper(); } CrashDetails.inBackground(); //report current view duration reportViewDuration(); } /** * Called when final Activity is stopped. Sends an end session event to the server, * also sends any unsent custom events. */ void onStopHelper() { connectionQueue_.endSession(roundedSecondsSinceLastSessionDurationUpdate()); prevSessionDurationStartTime_ = 0; if (eventQueue_.size() > 0) { connectionQueue_.recordEvents(eventQueue_.events()); } } /** * Called when GCM Registration ID is received. Sends a token session event to the server. */ public void onRegistrationId(String registrationId) { connectionQueue_.tokenSession(registrationId, messagingMode_); } public void recordEvent(final String key) { recordEvent(key, null, 1, 0); } public void recordEvent(final String key, final int count) { recordEvent(key, null, count, 0); } public void recordEvent(final String key, final int count, final double sum) { recordEvent(key, null, count, sum); } public void recordEvent(final String key, final Map<String, String> segmentation, final int count) { recordEvent(key, segmentation, count, 0); } public synchronized void recordEvent(final String key, final Map<String, String> segmentation, final int count, final double sum) { if (!isInitialized()) { throw new IllegalStateException("Countly.sharedInstance().init must be called before recordEvent"); } if (key == null || key.length() == 0) { throw new IllegalArgumentException("Valid Countly event key is required"); } if (count < 1) { throw new IllegalArgumentException("Countly event count should be greater than zero"); } if (segmentation != null) { for (String k : segmentation.keySet()) { if (k == null || k.length() == 0) { throw new IllegalArgumentException("Countly event segmentation key cannot be null or empty"); } if (segmentation.get(k) == null || segmentation.get(k).length() == 0) { throw new IllegalArgumentException("Countly event segmentation value cannot be null or empty"); } } } eventQueue_.recordEvent(key, segmentation, count, sum); sendEventsIfNeeded(); } /** * Enable or disable automatic view tracking * @param enable boolean for the state of automatic view tracking */ public synchronized Countly setViewTracking(boolean enable){ autoViewTracker = enable; return this; } /** * Check state of automatic view tracking * @return boolean - true if enabled, false if disabled */ public synchronized boolean isViewTrackingEnabled(){ return autoViewTracker; } /** * Record a view manualy, without automatic tracking * or track view that is not automatically tracked * like fragment, Message box or transparent Activity * @param viewName String - name of the view */ public synchronized Countly recordView(String viewName){ reportViewDuration(); lastView = viewName; lastViewStart = Countly.currentTimestamp(); HashMap<String, String> segments = new HashMap<String, String>(); segments.put("name", viewName); segments.put("visit", "1"); segments.put("segment", "Android"); if(firstView) { firstView = false; segments.put("start", "1"); } recordEvent("[CLY]_view", segments, 1); return this; } /** * Sets information about user. Possible keys are: * <ul> * <li> * name - (String) providing user's full name * </li> * <li> * username - (String) providing user's nickname * </li> * <li> * email - (String) providing user's email address * </li> * <li> * organization - (String) providing user's organization's name where user works * </li> * <li> * phone - (String) providing user's phone number * </li> * <li> * picture - (String) providing WWW URL to user's avatar or profile picture * </li> * <li> * picturePath - (String) providing local path to user's avatar or profile picture * </li> * <li> * gender - (String) providing user's gender as M for male and F for female * </li> * <li> * byear - (int) providing user's year of birth as integer * </li> * </ul> * @param data Map&lt;String, String&gt; with user data * @deprecated use {@link #Countly().sharedInstance().userData.setUserData(Map<String, String>)} to set data and {@link #Countly().sharedInstance().userData.save()} to send it to server. */ public synchronized Countly setUserData(Map<String, String> data) { return setUserData(data, null); } /** * Sets information about user with custom properties. * In custom properties you can provide any string key values to be stored with user * Possible keys are: * <ul> * <li> * name - (String) providing user's full name * </li> * <li> * username - (String) providing user's nickname * </li> * <li> * email - (String) providing user's email address * </li> * <li> * organization - (String) providing user's organization's name where user works * </li> * <li> * phone - (String) providing user's phone number * </li> * <li> * picture - (String) providing WWW URL to user's avatar or profile picture * </li> * <li> * picturePath - (String) providing local path to user's avatar or profile picture * </li> * <li> * gender - (String) providing user's gender as M for male and F for female * </li> * <li> * byear - (int) providing user's year of birth as integer * </li> * </ul> * @param data Map&lt;String, String&gt; with user data * @param customdata Map&lt;String, String&gt; with custom key values for this user * @deprecated use {@link #Countly().sharedInstance().userData.setUserData(Map<String, String>, Map<String, String>)} to set data and {@link #Countly().sharedInstance().userData.save()} to send it to server. */ public synchronized Countly setUserData(Map<String, String> data, Map<String, String> customdata) { UserData.setData(data); if(customdata != null) UserData.setCustomData(customdata); connectionQueue_.sendUserData(); UserData.clear(); return this; } /** * Sets custom properties. * In custom properties you can provide any string key values to be stored with user * @param customdata Map&lt;String, String&gt; with custom key values for this user * @deprecated use {@link #Countly().sharedInstance().userData.setCustomUserData(Map<String, String>)} to set data and {@link #Countly().sharedInstance().userData.save()} to send it to server. */ public synchronized Countly setCustomUserData(Map<String, String> customdata) { if(customdata != null) UserData.setCustomData(customdata); connectionQueue_.sendUserData(); UserData.clear(); return this; } /** * Set user location. * * Countly detects user location based on IP address. But for geolocation-enabled apps, * it's better to supply exact location of user. * Allows sending messages to a custom segment of users located in a particular area. * * @param lat Latitude * @param lon Longitude */ public synchronized Countly setLocation(double lat, double lon) { connectionQueue_.getCountlyStore().setLocation(lat, lon); if (disableUpdateSessionRequests_) { connectionQueue_.updateSession(roundedSecondsSinceLastSessionDurationUpdate()); } return this; } /** * Sets custom segments to be reported with crash reports * In custom segments you can provide any string key values to segments crashes by * @param segments Map&lt;String, String&gt; key segments and their values */ public synchronized Countly setCustomCrashSegments(Map<String, String> segments) { if(segments != null) CrashDetails.setCustomSegments(segments); return this; } /** * Add crash breadcrumb like log record to the log that will be send together with crash report * @param record String a bread crumb for the crash report */ public synchronized Countly addCrashLog(String record) { CrashDetails.addLog(record); return this; } /** * Log handled exception to report it to server as non fatal crash * @param exception Exception to log */ public synchronized Countly logException(Exception exception) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); exception.printStackTrace(pw); connectionQueue_.sendCrashReport(sw.toString(), true); return this; } /** * Enable crash reporting to send unhandled crash reports to server */ public synchronized Countly enableCrashReporting() { //get default handler final Thread.UncaughtExceptionHandler oldHandler = Thread.getDefaultUncaughtExceptionHandler(); Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); Countly.sharedInstance().connectionQueue_.sendCrashReport(sw.toString(), false); //if there was another handler before if(oldHandler != null){ //notify it also oldHandler.uncaughtException(t,e); } } }; Thread.setDefaultUncaughtExceptionHandler(handler); return this; } /** * Disable periodic session time updates. * By default, Countly will send a request to the server each 30 seconds with a small update * containing session duration time. This method allows you to disable such behavior. * Note that event updates will still be sent every 10 events or 30 seconds after event recording. * @param disable whether or not to disable session time updates * @return Countly instance for easy method chaining */ public synchronized Countly setDisableUpdateSessionRequests(final boolean disable) { disableUpdateSessionRequests_ = disable; return this; } /** * Sets whether debug logging is turned on or off. Logging is disabled by default. * @param enableLogging true to enable logging, false to disable logging * @return Countly instance for easy method chaining */ public synchronized Countly setLoggingEnabled(final boolean enableLogging) { enableLogging_ = enableLogging; return this; } public synchronized boolean isLoggingEnabled() { return enableLogging_; } private boolean appLaunchDeepLink = true; public static void onCreate(Activity activity) { Intent launchIntent = activity.getPackageManager().getLaunchIntentForPackage(activity.getPackageName()); if (sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Activity created: " + activity.getClass().getName() + " ( main is " + launchIntent.getComponent().getClassName() + ")"); } Intent intent = activity.getIntent(); if (intent != null) { Uri data = intent.getData(); if (data != null) { if (sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Data in activity created intent: " + data + " (appLaunchDeepLink " + sharedInstance().appLaunchDeepLink + ") " ); } if (sharedInstance().appLaunchDeepLink) { DeviceInfo.deepLink = data.toString(); } } } } /** * Reports duration of last view */ void reportViewDuration(){ if(lastView != null){ HashMap<String, String> segments = new HashMap<String, String>(); segments.put("name", lastView); segments.put("dur", String.valueOf(Countly.currentTimestamp()-lastViewStart)); segments.put("segment", "Android"); recordEvent("[CLY]_view",segments,1); lastView = null; lastViewStart = 0; } } /** * Submits all of the locally queued events to the server if there are more than 10 of them. */ void sendEventsIfNeeded() { if (eventQueue_.size() >= EVENT_QUEUE_SIZE_THRESHOLD) { connectionQueue_.recordEvents(eventQueue_.events()); } } /** * Called every 60 seconds to send a session heartbeat to the server. Does nothing if there * is not an active application session. */ synchronized void onTimer() { final boolean hasActiveSession = activityCount_ > 0; if (hasActiveSession) { if (!disableUpdateSessionRequests_) { connectionQueue_.updateSession(roundedSecondsSinceLastSessionDurationUpdate()); } if (eventQueue_.size() > 0) { connectionQueue_.recordEvents(eventQueue_.events()); } } } /** * Calculates the unsent session duration in seconds, rounded to the nearest int. */ int roundedSecondsSinceLastSessionDurationUpdate() { final long currentTimestampInNanoseconds = System.nanoTime(); final long unsentSessionLengthInNanoseconds = currentTimestampInNanoseconds - prevSessionDurationStartTime_; prevSessionDurationStartTime_ = currentTimestampInNanoseconds; return (int) Math.round(unsentSessionLengthInNanoseconds / 1000000000.0d); } /** * Utility method to return a current timestamp that can be used in the Count.ly API. */ static int currentTimestamp() { return ((int)(System.currentTimeMillis() / 1000l)); } /** * Utility method to return a current hour of the day that can be used in the Count.ly API. */ static int currentHour(){return Calendar.getInstance().get(Calendar.HOUR_OF_DAY); } /** * Utility method to return a current day of the week that can be used in the Count.ly API. */ static int currentDayOfWeek(){ int day = Calendar.getInstance().get(Calendar.DAY_OF_WEEK); switch (day) { case Calendar.MONDAY: return 1; case Calendar.TUESDAY: return 2; case Calendar.WEDNESDAY: return 3; case Calendar.THURSDAY: return 4; case Calendar.FRIDAY: return 5; case Calendar.SATURDAY: return 6; } return 0; } /** * Utility method for testing validity of a URL. */ static boolean isValidURL(final String urlStr) { boolean validURL = false; if (urlStr != null && urlStr.length() > 0) { try { new URL(urlStr); validURL = true; } catch (MalformedURLException e) { validURL = false; } } return validURL; } public static Countly enablePublicKeyPinning(List<String> certificates) { publicKeyPinCertificates = certificates; return Countly.sharedInstance(); } // for unit testing ConnectionQueue getConnectionQueue() { return connectionQueue_; } void setConnectionQueue(final ConnectionQueue connectionQueue) { connectionQueue_ = connectionQueue; } ExecutorService getTimerService() { return timerService_; } EventQueue getEventQueue() { return eventQueue_; } void setEventQueue(final EventQueue eventQueue) { eventQueue_ = eventQueue; } long getPrevSessionDurationStartTime() { return prevSessionDurationStartTime_; } void setPrevSessionDurationStartTime(final long prevSessionDurationStartTime) { prevSessionDurationStartTime_ = prevSessionDurationStartTime; } int getActivityCount() { return activityCount_; } synchronized boolean getDisableUpdateSessionRequests() { return disableUpdateSessionRequests_; } public void stackOverflow() { this.stackOverflow(); } public synchronized Countly crashTest(int crashNumber) { if (crashNumber == 1){ if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Running crashTest 1"); } stackOverflow(); }else if (crashNumber == 2){ if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Running crashTest 2"); } int test = 10/0; }else if (crashNumber == 3){ if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Running crashTest 3"); } Object[] o = null; while (true) { o = new Object[] { o }; } }else if (crashNumber == 4){ if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Running crashTest 4"); } throw new RuntimeException("This is a crash"); } else{ if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Running crashTest 5"); } String test = null; test.charAt(1); } return Countly.sharedInstance(); } }
package ly.count.android.sdk; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.util.Base64; import android.util.Log; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.HashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import static ly.count.android.sdk.CountlyStarRating.STAR_RATING_EVENT_KEY; @SuppressWarnings("JavadocReference") public class Countly { /** * Current version of the Count.ly Android SDK as a displayable string. */ public static final String COUNTLY_SDK_VERSION_STRING = "19.08"; /** * Used as request meta data on every request */ protected static final String COUNTLY_SDK_NAME = "java-native-android"; /** * Default string used in the begin session metrics if the * app version cannot be found. */ protected static final String DEFAULT_APP_VERSION = "1.0"; /** * Tag used in all logging in the Count.ly SDK. */ public static final String TAG = "Countly"; /** * Broadcast sent when consent set is changed */ public static final String CONSENT_BROADCAST = "ly.count.android.sdk.Countly.CONSENT_BROADCAST"; /** * Determines how many custom events can be queued locally before * an attempt is made to submit them to a Count.ly server. */ private static int EVENT_QUEUE_SIZE_THRESHOLD = 10; /** * How often onTimer() is called. */ private static final long TIMER_DELAY_IN_SECONDS = 60; protected static List<String> publicKeyPinCertificates; protected static List<String> certificatePinCertificates; protected static final Map<String, Event> timedEvents = new HashMap<>(); /** * Enum used in Countly.initMessaging() method which controls what kind of * app installation it is. Later (in Countly Dashboard or when calling Countly API method), * you'll be able to choose whether you want to send a message to test devices, * or to production ones. */ public enum CountlyMessagingMode { TEST, PRODUCTION, } private static class SingletonHolder { @SuppressLint("StaticFieldLeak") static final Countly instance = new Countly(); } private ConnectionQueue connectionQueue_; @SuppressWarnings("FieldCanBeLocal") private final ScheduledExecutorService timerService_; private EventQueue eventQueue_; private long prevSessionDurationStartTime_; private int activityCount_; private boolean disableUpdateSessionRequests_; private boolean enableLogging_; private Countly.CountlyMessagingMode messagingMode_; private Context context_; //user data access public static UserData userData; //track views private String lastView = null; private int lastViewStart = 0; private boolean firstView = true; private boolean autoViewTracker = false; private final static String VIEW_EVENT_KEY = "[CLY]_view"; //overrides private boolean isHttpPostForced = false;//when true, all data sent to the server will be sent using HTTP POST //app crawlers private boolean shouldIgnoreCrawlers = true;//ignore app crawlers by default private boolean deviceIsAppCrawler = false;//by default assume that device is not a app crawler @SuppressWarnings("ArraysAsListWithZeroOrOneArgument") private final List<String> appCrawlerNames = new ArrayList<>(Arrays.asList("Calypso AppCrawler"));//List against which device name is checked to determine if device is app crawler //star rating @SuppressWarnings("FieldCanBeLocal") private CountlyStarRating.RatingCallback starRatingCallback_;// saved callback that is used for automatic star rating //push related private boolean addMetadataToPushIntents = false;// a flag that indicates if metadata should be added to push notification intents //internal flags private boolean calledAtLeastOnceOnStart = false;//flag for if the onStart function has been called at least once //activity tracking boolean automaticTrackingShouldUseShortName = false;//flag for using short names //attribution protected boolean isAttributionEnabled = true; protected boolean isBeginSessionSent = false; //remote config_ //if set to true, it will automatically download remote configs on module startup boolean remoteConfigAutomaticUpdateEnabled = false; RemoteConfig.RemoteConfigCallback remoteConfigInitCallback = null; //custom request header fields Map<String, String> requestHeaderCustomValues; //native crash static final String countlyFolderName = "Countly"; static final String countlyNativeCrashFolderName = "CrashDumps"; //GDPR protected boolean requiresConsent = false; private final Map<String, Boolean> featureConsentValues = new HashMap<>(); private final Map<String, String[]> groupedFeatures = new HashMap<>(); private final List<String> collectedConsentChanges = new ArrayList<>(); Boolean delayedPushConsent = null;//if this is set, consent for push has to be set before finishing init and sending push changes boolean delayedLocationErasure = false;//if location needs to be cleared at the end of init CountlyConfig config_ = null; public static class CountlyFeatureNames { public static final String sessions = "sessions"; public static final String events = "events"; public static final String views = "views"; //public static final String scrolls = "scrolls"; //public static final String clicks = "clicks"; //public static final String forms = "forms"; public static final String location = "location"; public static final String crashes = "crashes"; public static final String attribution = "attribution"; public static final String users = "users"; public static final String push = "push"; public static final String starRating = "star-rating"; //public static final String accessoryDevices = "accessory-devices"; } //a list of valid feature names that are used for checking private final String[] validFeatureNames = new String[]{ CountlyFeatureNames.sessions, CountlyFeatureNames.events, CountlyFeatureNames.views, CountlyFeatureNames.location, CountlyFeatureNames.crashes, CountlyFeatureNames.attribution, CountlyFeatureNames.users, CountlyFeatureNames.push, CountlyFeatureNames.starRating}; /** * Returns the Countly singleton. */ public static Countly sharedInstance() { return SingletonHolder.instance; } /** * Constructs a Countly object. * Creates a new ConnectionQueue and initializes the session timer. */ Countly() { connectionQueue_ = new ConnectionQueue(); Countly.userData = new UserData(connectionQueue_); timerService_ = Executors.newSingleThreadScheduledExecutor(); timerService_.scheduleWithFixedDelay(new Runnable() { @Override public void run() { onTimer(); } }, TIMER_DELAY_IN_SECONDS, TIMER_DELAY_IN_SECONDS, TimeUnit.SECONDS); initConsent(); } public Countly init(final Context context, final String serverURL, final String appKey) { return init(context, serverURL, appKey, null, OpenUDIDAdapter.isOpenUDIDAvailable() ? DeviceId.Type.OPEN_UDID : DeviceId.Type.ADVERTISING_ID); } public Countly init(final Context context, final String serverURL, final String appKey, final String deviceID) { return init(context, serverURL, appKey, deviceID, null); } public synchronized Countly init(final Context context, final String serverURL, final String appKey, final String deviceID, DeviceId.Type idMode) { return init(context, serverURL, appKey, deviceID, idMode, -1, null, null, null, null); } public synchronized Countly init(final Context context, String serverURL, final String appKey, final String deviceID, DeviceId.Type idMode, int starRatingLimit, CountlyStarRating.RatingCallback starRatingCallback, String starRatingTextTitle, String starRatingTextMessage, String starRatingTextDismiss) { CountlyConfig config = new CountlyConfig(); config.setContext(context).setServerURL(serverURL).setAppKey(appKey).setDeviceId(deviceID) .setIdMode(idMode).setStarRatingLimit(starRatingLimit).setStarRatingCallback(starRatingCallback) .setStarRatingTextTitle(starRatingTextTitle).setStarRatingTextMessage(starRatingTextMessage) .setStarRatingTextDismiss(starRatingTextDismiss); return init(config); } /** * Initializes the Countly SDK. Call from your main Activity's onCreate() method. * Must be called before other SDK methods can be used. * @param config contains all needed information to init SDK */ public synchronized Countly init(CountlyConfig config){ //enable logging if(config.loggingEnabled){ //enable logging before any potential logging calls setLoggingEnabled(true); } if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "[Init] Initializing Countly SDk version " + COUNTLY_SDK_VERSION_STRING); } if (config.context == null) { throw new IllegalArgumentException("valid context is required in Countly init, but was provided 'null'"); } if (!isValidURL(config.serverURL)) { throw new IllegalArgumentException("valid serverURL is required"); } //enable unhandled crash reporting if(config.enableUnhandledCrashReporting){ enableCrashReporting(); } //react to given consent if(config.shouldRequireConsent){ setRequiresConsent(true); setConsent(config.enabledFeatureNames, true); } if (config.serverURL.charAt(config.serverURL.length() - 1) == '/') { if (Countly.sharedInstance().isLoggingEnabled()) { Log.i(Countly.TAG, "[Init] Removing trailing '/' from provided server url"); } config.serverURL = config.serverURL.substring(0, config.serverURL.length() - 1);//removing trailing '/' from server url } if (config.appKey == null || config.appKey.length() == 0) { throw new IllegalArgumentException("valid appKey is required, but was provided either 'null' or empty String"); } if (config.deviceID != null && config.deviceID.length() == 0) { //device ID is provided but it's a empty string throw new IllegalArgumentException("valid deviceID is required, but was provided as empty String"); } if (config.deviceID == null && config.idMode == null) { //device ID was not provided and no preferred mode specified. Choosing defaults if (OpenUDIDAdapter.isOpenUDIDAvailable()) config.idMode = DeviceId.Type.OPEN_UDID; else if (AdvertisingIdAdapter.isAdvertisingIdAvailable()) config.idMode = DeviceId.Type.ADVERTISING_ID; } if (config.deviceID == null && config.idMode == DeviceId.Type.OPEN_UDID && !OpenUDIDAdapter.isOpenUDIDAvailable()) { //choosing OPEN_UDID as ID type, but it's not available on this device throw new IllegalArgumentException("valid deviceID is required because OpenUDID is not available"); } if (config.deviceID == null && config.idMode == DeviceId.Type.ADVERTISING_ID && !AdvertisingIdAdapter.isAdvertisingIdAvailable()) { //choosing advertising ID as type, but it's available on this device throw new IllegalArgumentException("valid deviceID is required because Advertising ID is not available (you need to include Google Play services 4.0+ into your project)"); } if (eventQueue_ != null && (!connectionQueue_.getServerURL().equals(config.serverURL) || !connectionQueue_.getAppKey().equals(config.appKey) || !DeviceId.deviceIDEqualsNullSafe(config.deviceID, config.idMode, connectionQueue_.getDeviceId()) )) { //not sure if this needed throw new IllegalStateException("Countly cannot be reinitialized with different values"); } if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "[Init] Checking init parameters"); Log.d(Countly.TAG, "[Init] Is consent required? [" + requiresConsent + "]"); // Context class hierarchy // Context //|- ContextWrapper //|- - Application //|- - ContextThemeWrapper //|- - - - Activity //|- - Service //|- - - IntentService Class contextClass = config.context.getClass(); Class contextSuperClass = contextClass.getSuperclass(); String contextText = "[Init] Provided Context [" + config.context.getClass().getSimpleName() + "]"; if(contextSuperClass != null){ contextText += ", it's superclass: [" + contextSuperClass.getSimpleName() + "]"; } Log.d(Countly.TAG, contextText); } //init view related things if(config.enableViewTracking){ setViewTracking(true); } if(config.autoTrackingUseShortName){ setAutoTrackingUseShortName(true); } //init other things if(config.customNetworkRequestHeaders != null){ addCustomNetworkRequestHeaders(config.customNetworkRequestHeaders); } if(config.pushIntentAddMetadata){ setPushIntentAddMetadata(true); } if(config.enableRemoteConfigAutomaticDownload){ setRemoteConfigAutomaticDownload(config.enableRemoteConfigAutomaticDownload, config.remoteConfigCallback); } if(config.httpPostForced){ setHttpPostForced(true); } //set the star rating values starRatingCallback_ = config.starRatingCallback; CountlyStarRating.setStarRatingInitConfig(config.context, config.starRatingLimit, config.starRatingTextTitle, config.starRatingTextMessage, config.starRatingTextDismiss); //app crawler check checkIfDeviceIsAppCrawler(); //set internal context, it's allowed to be changed on the second init call context_ = config.context.getApplicationContext(); // if we get here and eventQueue_ != null, init is being called again with the same values, // so there is nothing to do, because we are already initialized with those values if (eventQueue_ == null) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "[Init] About to init internal systems"); } config_ = config; final CountlyStore countlyStore = new CountlyStore(config.context); boolean doingTemporaryIdMode = false; boolean customIDWasProvided = (config.deviceID != null); if(config.temporaryDeviceIdEnabled && !customIDWasProvided){ //if we want to use temporary ID mode and no developer custom ID is provided //then we override that custom ID to set the temporary mode config.deviceID = DeviceId.temporaryCountlyDeviceId; doingTemporaryIdMode = true; } DeviceId deviceIdInstance; if (config.deviceID != null) { //if the developer provided a ID deviceIdInstance = new DeviceId(countlyStore, config.deviceID); } else { //the dev provided only a type, generate a appropriate ID deviceIdInstance = new DeviceId(countlyStore, config.idMode); } if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "[Init] Currently cached advertising ID [" + countlyStore.getCachedAdvertisingId() + "]"); } AdvertisingIdAdapter.cacheAdvertisingID(config.context, countlyStore); deviceIdInstance.init(config.context, countlyStore, true); boolean temporaryDeviceIdWasEnabled = deviceIdInstance.temporaryIdModeEnabled(); if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "[Init] [TemporaryDeviceId] Previously was enabled: [" + temporaryDeviceIdWasEnabled + "]"); } if(temporaryDeviceIdWasEnabled){ //if we previously we're in temporary ID mode if(!config.temporaryDeviceIdEnabled || customIDWasProvided){ //if we don't set temporary device ID mode or //a custom device ID is explicitly provided //that means we have to exit temporary ID mode if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "[Init] [TemporaryDeviceId] Decided we have to exit temporary device ID mode, mode enabled: [" + config.temporaryDeviceIdEnabled + "], custom Device ID Set: [" + customIDWasProvided + "]"); } } else { //we continue to stay in temporary ID mode //no changes need to happen if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "[Init] [TemporaryDeviceId] Decided to stay in temporary ID mode"); } } } else { if(config.temporaryDeviceIdEnabled && config.deviceID == null){ //temporary device ID mode is enabled and //no custom device ID is provided //we can safely enter temporary device ID mode if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "[Init] [TemporaryDeviceId] Decided to enter temporary ID mode"); } } } //initialize networking queues connectionQueue_.setServerURL(config.serverURL); connectionQueue_.setAppKey(config.appKey); connectionQueue_.setCountlyStore(countlyStore); connectionQueue_.setDeviceId(deviceIdInstance); connectionQueue_.setRequestHeaderCustomValues(requestHeaderCustomValues); connectionQueue_.setContext(context_); eventQueue_ = new EventQueue(countlyStore); if(doingTemporaryIdMode) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "[Init] Trying to enter temporary ID mode"); } //if we are doing temporary ID, make sure it is applied //if it's not, change ID to it if(!deviceIdInstance.temporaryIdModeEnabled()){ if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "[Init] Temporary ID mode was not enabled, entering it"); } //temporary ID is not set changeDeviceId(DeviceId.temporaryCountlyDeviceId); } else { if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "[Init] Temporary ID mode was enabled previously, nothing to enter"); } } } //do star rating related things if(getConsent(CountlyFeatureNames.starRating)) { CountlyStarRating.registerAppSession(config.context, starRatingCallback_); } } else { //if this is not the first time we are calling init // context is allowed to be changed on the second init call connectionQueue_.setContext(context_); } if(requiresConsent) { //do delayed push consent action, if needed if(delayedPushConsent != null){ doPushConsentSpecialAction(delayedPushConsent); } //do delayed location erasure, if needed if(delayedLocationErasure){ doLocationConsentSpecialErasure(); } //send collected consent changes that were made before initialization if (collectedConsentChanges.size() != 0) { for (String changeItem : collectedConsentChanges) { connectionQueue_.sendConsentChanges(changeItem); } collectedConsentChanges.clear(); } context_.sendBroadcast(new Intent(CONSENT_BROADCAST)); if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "[Init] Countly is initialized with the current consent state:"); checkAllConsent(); } //update remote config_ values if automatic update is enabled if(remoteConfigAutomaticUpdateEnabled && anyConsentGiven()){ RemoteConfig.updateRemoteConfigValues(context_, null, null, connectionQueue_, false, remoteConfigInitCallback); } } //check for previous native crash dumps checkForNativeCrashDumps(config.context); return this; } /** * Checks whether Countly.init has been already called. * @return true if Countly is ready to use */ @SuppressWarnings("BooleanMethodIsAlwaysInverted") public synchronized boolean isInitialized() { return eventQueue_ != null; } public synchronized void halt() { if (Countly.sharedInstance().isLoggingEnabled()) { Log.i(Countly.TAG, "Halting Countly!"); } eventQueue_ = null; final CountlyStore countlyStore = connectionQueue_.getCountlyStore(); if (countlyStore != null) { countlyStore.clear(); } connectionQueue_.setContext(null); connectionQueue_.setServerURL(null); connectionQueue_.setAppKey(null); connectionQueue_.setCountlyStore(null); prevSessionDurationStartTime_ = 0; activityCount_ = 0; } public synchronized void onStart(Activity activity) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Countly onStart called, [" + activityCount_ + "] -> [" + (activityCount_ + 1) + "] activities now open"); } appLaunchDeepLink = false; if (eventQueue_ == null) { throw new IllegalStateException("init must be called before onStart"); } ++activityCount_; if (activityCount_ == 1) { onStartHelper(); } //check if there is an install referrer data String referrer = ReferrerReceiver.getReferrer(context_); if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Checking referrer: " + referrer); } if(referrer != null){ connectionQueue_.sendReferrerData(referrer); ReferrerReceiver.deleteReferrer(context_); } CrashDetails.inForeground(); if(autoViewTracker){ String usedActivityName; if(automaticTrackingShouldUseShortName){ usedActivityName = activity.getClass().getSimpleName(); } else { usedActivityName = activity.getClass().getName(); } recordView(usedActivityName); } calledAtLeastOnceOnStart = true; } /** * Called when the first Activity is started. Sends a begin session event to the server * and initializes application session tracking. */ private void onStartHelper() { prevSessionDurationStartTime_ = System.nanoTime(); connectionQueue_.beginSession(); } public synchronized void onStop() { if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Countly onStop called, [" + activityCount_ + "] -> [" + (activityCount_ - 1) + "] activities now open"); } if (eventQueue_ == null) { throw new IllegalStateException("init must be called before onStop"); } if (activityCount_ == 0) { throw new IllegalStateException("must call onStart before onStop"); } --activityCount_; if (activityCount_ == 0) { onStopHelper(); } CrashDetails.inBackground(); //report current view duration reportViewDuration(); } /** * Called when final Activity is stopped. Sends an end session event to the server, * also sends any unsent custom events. */ private void onStopHelper() { connectionQueue_.endSession(roundedSecondsSinceLastSessionDurationUpdate()); prevSessionDurationStartTime_ = 0; if (eventQueue_.size() > 0) { connectionQueue_.recordEvents(eventQueue_.events()); } } /** * Called when GCM Registration ID is received. Sends a token session event to the server. */ public void onRegistrationId(String registrationId) { onRegistrationId(registrationId, messagingMode_); } /** * DON'T USE THIS!!!! */ public void onRegistrationId(String registrationId, CountlyMessagingMode mode) { if(!getConsent(CountlyFeatureNames.push)) { return; } connectionQueue_.tokenSession(registrationId, mode); } /** * Changes current device id type to the one specified in parameter. Closes current session and * reopens new one with new id. Doesn't merge user profiles on the server * @param type Device ID type to change to * @param deviceId Optional device ID for a case when type = DEVELOPER_SPECIFIED */ public void changeDeviceId(DeviceId.Type type, String deviceId) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Calling [changeDeviceId] with type and ID"); } if (eventQueue_ == null) { throw new IllegalStateException("init must be called before changeDeviceId"); } //if (activityCount_ == 0) { if (type == null) { throw new IllegalStateException("type cannot be null"); } if(!anyConsentGiven()){ if (Countly.sharedInstance().isLoggingEnabled()) { Log.w(Countly.TAG, "Can't change Device ID if no consent is given"); } return; } DeviceId currentDeviceId = connectionQueue_.getDeviceId(); if(currentDeviceId.temporaryIdModeEnabled() && deviceId.equals(DeviceId.temporaryCountlyDeviceId)){ // we already are in temporary mode and we want to set temporary mode // in this case we just ignore the request since nothing has to be done return; } if(currentDeviceId.temporaryIdModeEnabled()){ // we are about to exit temporary ID mode // because of the previous check, we know that the new type is a different one // we just call our method for exiting it // we don't end the session, we just update the device ID and connection queue exitTemporaryIdMode(type, deviceId); } // we are either making a simple ID change or entering temporary mode // in both cases we act the same as the temporary ID requests will be updated with the final ID later //force flush events so that they are associated correctly sendEventsForced(); connectionQueue_.endSession(roundedSecondsSinceLastSessionDurationUpdate(), currentDeviceId.getId()); currentDeviceId.changeToId(context_, connectionQueue_.getCountlyStore(), type, deviceId); connectionQueue_.beginSession(); //update remote config_ values if automatic update is enabled remoteConfigClearValues(); if (remoteConfigAutomaticUpdateEnabled && anyConsentGiven()) { RemoteConfig.updateRemoteConfigValues(context_, null, null, connectionQueue_, false, null); } } /** * Changes current device id to the one specified in parameter. Merges user profile with new id * (if any) with old profile. * @param deviceId new device id */ public void changeDeviceId(String deviceId) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Calling [changeDeviceId] only with ID"); } if (!isInitialized()) { throw new IllegalStateException("init must be called before changeDeviceId"); } //if (activityCount_ == 0) { if (deviceId == null || "".equals(deviceId)) { throw new IllegalStateException("deviceId cannot be null or empty"); } if(!anyConsentGiven()){ if (Countly.sharedInstance().isLoggingEnabled()) { Log.w(Countly.TAG, "Can't change Device ID if no consent is given"); } return; } if(connectionQueue_.getDeviceId().temporaryIdModeEnabled()){ //if we are in temporary ID mode if(deviceId.equals(DeviceId.temporaryCountlyDeviceId)){ //if we want to enter temporary ID mode //just exit, nothing to do if (Countly.sharedInstance().isLoggingEnabled()) { Log.w(Countly.TAG, "[changeDeviceId] About to enter temporary ID mode when already in it"); } return; } // if a developer supplied ID is provided //we just exit this mode and set the id to the provided one exitTemporaryIdMode(DeviceId.Type.DEVELOPER_SUPPLIED, deviceId); } else { //we are not in temporary mode, nothing special happens connectionQueue_.changeDeviceId(deviceId, roundedSecondsSinceLastSessionDurationUpdate()); //update remote config_ values if automatic update is enabled remoteConfigClearValues(); if (remoteConfigAutomaticUpdateEnabled && anyConsentGiven()) { //request should be delayed, because of the delayed server merge RemoteConfig.updateRemoteConfigValues(context_, null, null, connectionQueue_, true, null); } } } private void exitTemporaryIdMode(DeviceId.Type type, String deviceId){ if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Calling exitTemporaryIdMode"); } if (!isInitialized()) { throw new IllegalStateException("init must be called before exitTemporaryIdMode"); } //start by changing stored ID connectionQueue_.getDeviceId().changeToId(context_, connectionQueue_.getCountlyStore(), type, deviceId); //update stored request for ID change to use this new ID //update remote config_ values if automatic update is enabled remoteConfigClearValues(); if (remoteConfigAutomaticUpdateEnabled && anyConsentGiven()) { RemoteConfig.updateRemoteConfigValues(context_, null, null, connectionQueue_, false, null); } doStoredRequests(); } public void recordEvent(final String key) { recordEvent(key, null, 1, 0); } public void recordEvent(final String key, final int count) { recordEvent(key, null, count, 0); } public void recordEvent(final String key, final int count, final double sum) { recordEvent(key, null, count, sum); } public void recordEvent(final String key, final Map<String, String> segmentation, final int count) { recordEvent(key, segmentation, count, 0); } public synchronized void recordEvent(final String key, final Map<String, String> segmentation, final int count, final double sum) { recordEvent(key, segmentation, count, sum, 0); } public synchronized void recordEvent(final String key, final Map<String, String> segmentation, final int count, final double sum, final double dur){ recordEvent(key, segmentation, null, null, count, sum, dur); } public synchronized void recordEvent(final String key, final Map<String, String> segmentation, final Map<String, Integer> segmentationInt, final Map<String, Double> segmentationDouble, final int count, final double sum, final double dur) { if (!isInitialized()) { throw new IllegalStateException("Countly.sharedInstance().init must be called before recordEvent"); } if (key == null || key.length() == 0) { throw new IllegalArgumentException("Valid Countly event key is required"); } if (count < 1) { throw new IllegalArgumentException("Countly event count should be greater than zero"); } if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Recording event with key: [" + key + "]"); } if (segmentation != null) { for (String k : segmentation.keySet()) { if (k == null || k.length() == 0) { throw new IllegalArgumentException("Countly event segmentation key cannot be null or empty"); } if (segmentation.get(k) == null || segmentation.get(k).length() == 0) { throw new IllegalArgumentException("Countly event segmentation value cannot be null or empty"); } } } if (segmentationInt != null) { for (String k : segmentationInt.keySet()) { if (k == null || k.length() == 0) { throw new IllegalArgumentException("Countly event segmentation key cannot be null or empty"); } if (segmentationInt.get(k) == null) { throw new IllegalArgumentException("Countly event segmentation value cannot be null"); } } } if (segmentationDouble != null) { for (String k : segmentationDouble.keySet()) { if (k == null || k.length() == 0) { throw new IllegalArgumentException("Countly event segmentation key cannot be null or empty"); } if (segmentationDouble.get(k) == null) { throw new IllegalArgumentException("Countly event segmentation value cannot be null"); } } } switch (key) { case STAR_RATING_EVENT_KEY: if (Countly.sharedInstance().getConsent(CountlyFeatureNames.starRating)) { eventQueue_.recordEvent(key, segmentation, segmentationInt, segmentationDouble, count, sum, dur); sendEventsForced(); } break; case VIEW_EVENT_KEY: if (Countly.sharedInstance().getConsent(CountlyFeatureNames.views)) { eventQueue_.recordEvent(key, segmentation, segmentationInt, segmentationDouble, count, sum, dur); sendEventsForced(); } break; default: if (Countly.sharedInstance().getConsent(CountlyFeatureNames.events)) { eventQueue_.recordEvent(key, segmentation, segmentationInt, segmentationDouble, count, sum, dur); sendEventsIfNeeded(); } break; } } /** * Enable or disable automatic view tracking * @param enable boolean for the state of automatic view tracking * @deprecated use CountlyConfig during init to set this * @return Returns link to Countly for call chaining */ public synchronized Countly setViewTracking(boolean enable){ if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Enabling automatic view tracking"); } autoViewTracker = enable; return this; } /** * Check state of automatic view tracking * @return boolean - true if enabled, false if disabled */ public synchronized boolean isViewTrackingEnabled(){ return autoViewTracker; } /** * Record a view manually, without automatic tracking * or track view that is not automatically tracked * like fragment, Message box or transparent Activity * @param viewName String - name of the view * @return Returns link to Countly for call chaining */ public synchronized Countly recordView(String viewName){ if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Recording view with name: [" + viewName + "]"); } reportViewDuration(); lastView = viewName; lastViewStart = Countly.currentTimestamp(); HashMap<String, String> segments = new HashMap<>(); segments.put("name", viewName); segments.put("visit", "1"); segments.put("segment", "Android"); if(firstView) { firstView = false; segments.put("start", "1"); } recordEvent(VIEW_EVENT_KEY, segments, 1); return this; } /** * Sets information about user. Possible keys are: * <ul> * <li> * name - (String) providing user's full name * </li> * <li> * username - (String) providing user's nickname * </li> * <li> * email - (String) providing user's email address * </li> * <li> * organization - (String) providing user's organization's name where user works * </li> * <li> * phone - (String) providing user's phone number * </li> * <li> * picture - (String) providing WWW URL to user's avatar or profile picture * </li> * <li> * picturePath - (String) providing local path to user's avatar or profile picture * </li> * <li> * gender - (String) providing user's gender as M for male and F for female * </li> * <li> * byear - (int) providing user's year of birth as integer * </li> * </ul> * @param data Map&lt;String, String&gt; with user data * @deprecated use {@link UserData#setUserData(Map)} to set data and {@link UserData#save()} to send it to server. */ public synchronized Countly setUserData(Map<String, String> data) { return setUserData(data, null); } /** * Sets information about user with custom properties. * In custom properties you can provide any string key values to be stored with user * Possible keys are: * <ul> * <li> * name - (String) providing user's full name * </li> * <li> * username - (String) providing user's nickname * </li> * <li> * email - (String) providing user's email address * </li> * <li> * organization - (String) providing user's organization's name where user works * </li> * <li> * phone - (String) providing user's phone number * </li> * <li> * picture - (String) providing WWW URL to user's avatar or profile picture * </li> * <li> * picturePath - (String) providing local path to user's avatar or profile picture * </li> * <li> * gender - (String) providing user's gender as M for male and F for female * </li> * <li> * byear - (int) providing user's year of birth as integer * </li> * </ul> * @param data Map&lt;String, String&gt; with user data * @param customdata Map&lt;String, String&gt; with custom key values for this user * @deprecated use {@link UserData#setUserData(Map, Map)} to set data and {@link UserData#save()} to send it to server. */ public synchronized Countly setUserData(Map<String, String> data, Map<String, String> customdata) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Setting user data"); } UserData.setData(data); if(customdata != null) UserData.setCustomData(customdata); connectionQueue_.sendUserData(); UserData.clear(); return this; } /** * Sets custom properties. * In custom properties you can provide any string key values to be stored with user * @param customdata Map&lt;String, String&gt; with custom key values for this user * @deprecated use {@link UserData#setCustomUserData(Map)} to set data and {@link UserData#save()} to send it to server. */ public synchronized Countly setCustomUserData(Map<String, String> customdata) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Setting custom user data"); } if(customdata != null) UserData.setCustomData(customdata); connectionQueue_.sendUserData(); UserData.clear(); return this; } /** * Disable sending of location data * @return Returns link to Countly for call chaining */ public synchronized Countly disableLocation() { if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Disabling location"); } if(!getConsent(CountlyFeatureNames.location)){ //can't send disable location request if no consent given return this; } resetLocationValues(); connectionQueue_.getCountlyStore().setLocationDisabled(true); connectionQueue_.sendLocation(); return this; } private synchronized void resetLocationValues(){ connectionQueue_.getCountlyStore().setLocationCountryCode(""); connectionQueue_.getCountlyStore().setLocationCity(""); connectionQueue_.getCountlyStore().setLocation(""); connectionQueue_.getCountlyStore().setLocationIpAddress(""); } /** * Set location parameters. If they are set before begin_session, they will be sent as part of it. * If they are set after, then they will be sent as a separate request. * If this is called after disabling location, it will enable it. * @param country_code ISO Country code for the user's country * @param city Name of the user's city * @param location comma separate lat and lng values. For example, "56.42345,123.45325" * @return Returns link to Countly for call chaining */ public synchronized Countly setLocation(String country_code, String city, String location, String ipAddress){ if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Setting location parameters"); } if(!getConsent(CountlyFeatureNames.location)){ return this; } if(country_code != null){ connectionQueue_.getCountlyStore().setLocationCountryCode(country_code); } if(city != null){ connectionQueue_.getCountlyStore().setLocationCity(city); } if(location != null){ connectionQueue_.getCountlyStore().setLocation(location); } if(ipAddress != null){ connectionQueue_.getCountlyStore().setLocationIpAddress(ipAddress); } if((country_code == null && city != null) || (city == null && country_code != null)) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.w(Countly.TAG, "In \"setLocation\" both city and country code need to be set at the same time to be sent"); } } if(country_code != null || city != null || location != null || ipAddress != null){ connectionQueue_.getCountlyStore().setLocationDisabled(false); } if(isBeginSessionSent || !Countly.sharedInstance().getConsent(Countly.CountlyFeatureNames.sessions)){ //send as a seperate request if either begin session was already send and we missed our first opportunity //or if consent for sessions is not given and our only option to send this is as a separate request connectionQueue_.sendLocation(); } else { //will be sent a part of begin session } return this; } /** * Sets custom segments to be reported with crash reports * In custom segments you can provide any string key values to segments crashes by * @param segments Map&lt;String, String&gt; key segments and their values * @return Returns link to Countly for call chaining */ public synchronized Countly setCustomCrashSegments(Map<String, String> segments) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Setting custom crash segments"); } if(!getConsent(CountlyFeatureNames.crashes)){ return this; } if(segments != null) { CrashDetails.setCustomSegments(segments); } return this; } /** * Add crash breadcrumb like log record to the log that will be send together with crash report * @param record String a bread crumb for the crash report * @return Returns link to Countly for call chaining * @deprecated use `addCrashBreadcrumb` */ public synchronized Countly addCrashLog(String record) { return addCrashBreadcrumb(record); } /** * Add crash breadcrumb like log record to the log that will be send together with crash report * @param record String a bread crumb for the crash report * @return Returns link to Countly for call chaining */ public synchronized Countly addCrashBreadcrumb(String record) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Adding crash breadcrumb"); } if(!getConsent(CountlyFeatureNames.crashes)){ return this; } if(record == null || record.isEmpty()) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Can't add a null or empty crash breadcrumb"); } return this; } CrashDetails.addLog(record); return this; } /** * Called during init to check if there are any crash dumps saved * @param context android context */ protected synchronized void checkForNativeCrashDumps(Context context){ Log.d(TAG, "Checking for native crash dumps"); String basePath = context.getCacheDir().getAbsolutePath(); String finalPath = basePath + File.separator + countlyFolderName + File.separator + countlyNativeCrashFolderName; File folder = new File(finalPath); if (folder.exists()) { Log.d(TAG, "Native crash folder exists, checking for dumps"); File[] dumpFiles = folder.listFiles(); Log.d(TAG,"Crash dump folder contains [" + dumpFiles.length + "] files"); for (int i = 0; i < dumpFiles.length; i++) { //record crash recordNativeException(dumpFiles[i]); //delete dump file dumpFiles[i].delete(); } } else { Log.d(TAG, "Native crash folder does not exist"); } } protected synchronized void recordNativeException(File dumpFile){ Log.d(TAG, "Recording native crash dump: [" + dumpFile.getName() + "]"); //check for consent if(!getConsent(CountlyFeatureNames.crashes)){ return; } //read bytes int size = (int)dumpFile.length(); byte[] bytes = new byte[size]; try { BufferedInputStream buf = new BufferedInputStream(new FileInputStream(dumpFile)); buf.read(bytes, 0, bytes.length); buf.close(); } catch (Exception e) { Log.e(TAG, "Failed to read dump file bytes"); e.printStackTrace(); return; } //convert to base64 String dumpString = Base64.encodeToString(bytes, Base64.NO_WRAP); //record crash connectionQueue_.sendCrashReport(dumpString, false, true); } /** * Log handled exception to report it to server as non fatal crash * @param exception Exception to log * @deprecated Use recordHandledException * @return Returns link to Countly for call chaining */ public synchronized Countly logException(Exception exception) { return recordException(exception, true); } /** * Log handled exception to report it to server as non fatal crash * @param exception Exception to log * @return Returns link to Countly for call chaining */ public synchronized Countly recordHandledException(Exception exception) { return recordException(exception, true); } /** * Log handled exception to report it to server as non fatal crash * @param exception Throwable to log * @return Returns link to Countly for call chaining */ public synchronized Countly recordHandledException(Throwable exception) { return recordException(exception, true); } /** * Log unhandled exception to report it to server as fatal crash * @param exception Exception to log * @return Returns link to Countly for call chaining */ public synchronized Countly recordUnhandledException(Exception exception) { return recordException(exception, false); } /** * Log unhandled exception to report it to server as fatal crash * @param exception Throwable to log * @return Returns link to Countly for call chaining */ public synchronized Countly recordUnhandledException(Throwable exception) { return recordException(exception, false); } /** * Common call for handling exceptions * @param exception Exception to log * @param itIsHandled If the exception is handled or not (fatal) * @return Returns link to Countly for call chaining */ private synchronized Countly recordException(Throwable exception, boolean itIsHandled) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Logging exception, handled:[" + itIsHandled + "]"); } if(!getConsent(CountlyFeatureNames.crashes)){ return this; } StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); exception.printStackTrace(pw); connectionQueue_.sendCrashReport(sw.toString(), itIsHandled, false); return this; } /** * Enable crash reporting to send unhandled crash reports to server * @deprecated use CountlyConfig during init to set this * @return Returns link to Countly for call chaining */ public synchronized Countly enableCrashReporting() { if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Enabling unhandled crash reporting"); } //get default handler final Thread.UncaughtExceptionHandler oldHandler = Thread.getDefaultUncaughtExceptionHandler(); Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { if(getConsent(CountlyFeatureNames.crashes)){ StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); Countly.sharedInstance().connectionQueue_.sendCrashReport(sw.toString(), false, false); } //if there was another handler before if(oldHandler != null){ //notify it also oldHandler.uncaughtException(t,e); } } }; Thread.setDefaultUncaughtExceptionHandler(handler); return this; } /** * Start timed event with a specified key * @param key name of the custom event, required, must not be the empty string or null * @return true if no event with this key existed before and event is started, false otherwise */ public synchronized boolean startEvent(final String key) { if (!isInitialized()) { throw new IllegalStateException("Countly.sharedInstance().init must be called before recordEvent"); } if (key == null || key.length() == 0) { throw new IllegalArgumentException("Valid Countly event key is required"); } if (timedEvents.containsKey(key)) { return false; } if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Starting event: [" + key + "]"); } timedEvents.put(key, new Event(key)); return true; } /** * End timed event with a specified key * @param key name of the custom event, required, must not be the empty string or null * @return true if event with this key has been previously started, false otherwise */ public synchronized boolean endEvent(final String key) { return endEvent(key, null, 1, 0); } public synchronized boolean endEvent(final String key, final Map<String, String> segmentation, final int count, final double sum) { return endEvent(key, segmentation, null, null, count, sum); } public synchronized boolean endEvent(final String key, final Map<String, String> segmentation, final Map<String, Integer> segmentationInt, final Map<String, Double> segmentationDouble, final int count, final double sum) { Event event = timedEvents.remove(key); if (event != null) { if(!getConsent(CountlyFeatureNames.events)) { return true; } if (!isInitialized()) { throw new IllegalStateException("Countly.sharedInstance().init must be called before recordEvent"); } if (key == null || key.length() == 0) { throw new IllegalArgumentException("Valid Countly event key is required"); } if (count < 1) { throw new IllegalArgumentException("Countly event count should be greater than zero"); } if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Ending event: [" + key + "]"); } if (segmentation != null) { for (String k : segmentation.keySet()) { if (k == null || k.length() == 0) { throw new IllegalArgumentException("Countly event segmentation key cannot be null or empty"); } if (segmentation.get(k) == null || segmentation.get(k).length() == 0) { throw new IllegalArgumentException("Countly event segmentation value cannot be null or empty"); } } } if (segmentationInt != null) { for (String k : segmentationInt.keySet()) { if (k == null || k.length() == 0) { throw new IllegalArgumentException("Countly event segmentation key cannot be null or empty"); } if (segmentationInt.get(k) == null) { throw new IllegalArgumentException("Countly event segmentation value cannot be null"); } } } if (segmentationDouble != null) { for (String k : segmentationDouble.keySet()) { if (k == null || k.length() == 0) { throw new IllegalArgumentException("Countly event segmentation key cannot be null or empty"); } if (segmentationDouble.get(k) == null) { throw new IllegalArgumentException("Countly event segmentation value cannot be null"); } } } long currentTimestamp = Countly.currentTimestampMs(); event.segmentation = segmentation; event.segmentationDouble = segmentationDouble; event.segmentationInt = segmentationInt; event.dur = (currentTimestamp - event.timestamp) / 1000.0; event.count = count; event.sum = sum; eventQueue_.recordEvent(event); sendEventsIfNeeded(); return true; } else { return false; } } /** * Disable periodic session time updates. * By default, Countly will send a request to the server each 30 seconds with a small update * containing session duration time. This method allows you to disable such behavior. * Note that event updates will still be sent every 10 events or 30 seconds after event recording. * @param disable whether or not to disable session time updates * @return Countly instance for easy method chaining */ public synchronized Countly setDisableUpdateSessionRequests(final boolean disable) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Disabling periodic session time updates"); } disableUpdateSessionRequests_ = disable; return this; } /** * Sets whether debug logging is turned on or off. Logging is disabled by default. * @param enableLogging true to enable logging, false to disable logging * @deprecated use CountlyConfig during init to set this * @return Countly instance for easy method chaining */ public synchronized Countly setLoggingEnabled(final boolean enableLogging) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Enabling logging"); } enableLogging_ = enableLogging; return this; } public synchronized boolean isLoggingEnabled() { return enableLogging_; } public synchronized Countly enableParameterTamperingProtection(String salt) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Enabling tamper protection"); } ConnectionProcessor.salt = salt; return this; } /** * Returns if the countly sdk onStart function has been called at least once * @return true - yes, it has, false - no it has not */ public synchronized boolean hasBeenCalledOnStart() { return calledAtLeastOnceOnStart; } public synchronized Countly setEventQueueSizeToSend(int size) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Setting event queue size: [" + size + "]"); } EVENT_QUEUE_SIZE_THRESHOLD = size; return this; } private boolean appLaunchDeepLink = true; public static void onCreate(Activity activity) { Intent launchIntent = activity.getPackageManager().getLaunchIntentForPackage(activity.getPackageName()); if (sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Activity created: " + activity.getClass().getName() + " ( main is " + launchIntent.getComponent().getClassName() + ")"); } Intent intent = activity.getIntent(); if (intent != null) { Uri data = intent.getData(); if (data != null) { if (sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Data in activity created intent: " + data + " (appLaunchDeepLink " + sharedInstance().appLaunchDeepLink + ") " ); } if (sharedInstance().appLaunchDeepLink) { DeviceInfo.deepLink = data.toString(); } } } } /** * Reports duration of last view */ private void reportViewDuration(){ if (sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "View [" + lastView + "] is getting closed, reporting duration: [" + (Countly.currentTimestamp() - lastViewStart) + "], current timestamp: [" + Countly.currentTimestamp() + "], last views start: [" + lastViewStart + "]"); } if(lastView != null && lastViewStart <= 0) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.e(Countly.TAG, "Last view start value is not normal: [" + lastViewStart + "]"); } } if(!getConsent(CountlyFeatureNames.views)) { return; } //only record view if the view name is not null and if it has a reasonable duration //if the lastViewStart is equal to 0, the duration would be set to the current timestamp //and therefore will be ignored if(lastView != null && lastViewStart > 0){ HashMap<String, String> segments = new HashMap<>(); segments.put("name", lastView); segments.put("dur", String.valueOf(Countly.currentTimestamp()-lastViewStart)); segments.put("segment", "Android"); recordEvent(VIEW_EVENT_KEY,segments,1); lastView = null; lastViewStart = 0; } } /** * Submits all of the locally queued events to the server if there are more than 10 of them. */ protected void sendEventsIfNeeded() { if (eventQueue_.size() >= EVENT_QUEUE_SIZE_THRESHOLD) { connectionQueue_.recordEvents(eventQueue_.events()); } } /** * Immediately sends all stored events */ protected void sendEventsForced() { connectionQueue_.recordEvents(eventQueue_.events()); } /** * Called every 60 seconds to send a session heartbeat to the server. Does nothing if there * is not an active application session. */ synchronized void onTimer() { final boolean hasActiveSession = activityCount_ > 0; if (hasActiveSession) { if (!disableUpdateSessionRequests_) { connectionQueue_.updateSession(roundedSecondsSinceLastSessionDurationUpdate()); } if (eventQueue_.size() > 0) { connectionQueue_.recordEvents(eventQueue_.events()); } } if(isInitialized()){ connectionQueue_.tick(); } } /** * Calculates the unsent session duration in seconds, rounded to the nearest int. */ int roundedSecondsSinceLastSessionDurationUpdate() { final long currentTimestampInNanoseconds = System.nanoTime(); final long unsentSessionLengthInNanoseconds = currentTimestampInNanoseconds - prevSessionDurationStartTime_; prevSessionDurationStartTime_ = currentTimestampInNanoseconds; return (int) Math.round(unsentSessionLengthInNanoseconds / 1000000000.0d); } /** * Utility method to return a current timestamp that can be used in the Count.ly API. */ static int currentTimestamp() { return ((int)(System.currentTimeMillis() / 1000L)); } static class TimeUniquesEnsurer { final List<Long> lastTsMs = new ArrayList<>(10); final long addition = 0; long currentTimeMillis() { return System.currentTimeMillis() + addition; } synchronized long uniqueTimestamp() { long ms = currentTimeMillis(); // change time back case if (lastTsMs.size() > 2) { long min = Collections.min(lastTsMs); if (ms < min) { lastTsMs.clear(); lastTsMs.add(ms); return ms; } } // usual case while (lastTsMs.contains(ms)) { ms += 1; } while (lastTsMs.size() >= 10) { lastTsMs.remove(0); } lastTsMs.add(ms); return ms; } } private static final TimeUniquesEnsurer timeGenerator = new TimeUniquesEnsurer(); static synchronized long currentTimestampMs() { return timeGenerator.uniqueTimestamp(); } /** * Utility method to return a current hour of the day that can be used in the Count.ly API. */ static int currentHour(){return Calendar.getInstance().get(Calendar.HOUR_OF_DAY); } /** * Utility method to return a current day of the week that can be used in the Count.ly API. */ @SuppressLint("SwitchIntDef") static int currentDayOfWeek(){ int day = Calendar.getInstance().get(Calendar.DAY_OF_WEEK); switch (day) { case Calendar.MONDAY: return 1; case Calendar.TUESDAY: return 2; case Calendar.WEDNESDAY: return 3; case Calendar.THURSDAY: return 4; case Calendar.FRIDAY: return 5; case Calendar.SATURDAY: return 6; } return 0; } /** * Utility method for testing validity of a URL. */ @SuppressWarnings("ConstantConditions") static boolean isValidURL(final String urlStr) { boolean validURL = false; if (urlStr != null && urlStr.length() > 0) { try { new URL(urlStr); validURL = true; } catch (MalformedURLException e) { validURL = false; } } return validURL; } public static Countly enablePublicKeyPinning(List<String> certificates) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.i(Countly.TAG, "Enabling public key pinning"); } publicKeyPinCertificates = certificates; return Countly.sharedInstance(); } public static Countly enableCertificatePinning(List<String> certificates) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.i(Countly.TAG, "Enabling certificate pinning"); } certificatePinCertificates = certificates; return Countly.sharedInstance(); } /** * Shows the star rating dialog * @param activity the activity that will own the dialog * @param callback callback for the star rating dialog "rate" and "dismiss" events */ public void showStarRating(Activity activity, CountlyStarRating.RatingCallback callback){ if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Showing star rating"); } if(!getConsent(CountlyFeatureNames.starRating)) { return; } CountlyStarRating.showStarRating(activity, callback); } /** * Set's the text's for the different fields in the star rating dialog. Set value null if for some field you want to keep the old value * @param starRatingTextTitle dialog's title text * @param starRatingTextMessage dialog's message text * @param starRatingTextDismiss dialog's dismiss buttons text */ public synchronized Countly setStarRatingDialogTexts(String starRatingTextTitle, String starRatingTextMessage, String starRatingTextDismiss) { if(context_ == null) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.e(Countly.TAG, "Can't call this function before init has been called"); return this; } } if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Setting star rating texts"); } CountlyStarRating.setStarRatingInitConfig(context_, -1, starRatingTextTitle, starRatingTextMessage, starRatingTextDismiss); return this; } /** * Set if the star rating should be shown automatically * @param IsShownAutomatically set it true if you want to show the app star rating dialog automatically for each new version after the specified session amount */ public synchronized Countly setIfStarRatingShownAutomatically(boolean IsShownAutomatically) { if(context_ == null) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.e(Countly.TAG, "Can't call this function before init has been called"); return this; } } if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Setting to show star rating automaticaly: [" + IsShownAutomatically + "]"); } CountlyStarRating.setShowDialogAutomatically(context_, IsShownAutomatically); return this; } /** * Set if the star rating is shown only once per app lifetime * @param disableAsking set true if you want to disable asking the app rating for each new app version (show it only once per apps lifetime) */ public synchronized Countly setStarRatingDisableAskingForEachAppVersion(boolean disableAsking) { if(context_ == null) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.e(Countly.TAG, "Can't call this function before init has been called"); return this; } } if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Setting to disable showing of star rating for each app version:[" + disableAsking + "]"); } CountlyStarRating.setStarRatingDisableAskingForEachAppVersion(context_, disableAsking); return this; } /** * Set after how many sessions the automatic star rating will be shown for each app version * @param limit app session amount for the limit * @return Returns link to Countly for call chaining */ public synchronized Countly setAutomaticStarRatingSessionLimit(int limit) { if(context_ == null) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.e(Countly.TAG, "Can't call this function before init has been called"); return this; } } if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Setting automatic star rating session limit: [" + limit + "]"); } CountlyStarRating.setStarRatingInitConfig(context_, limit, null, null, null); return this; } /** * Returns the session limit set for automatic star rating */ public int getAutomaticStarRatingSessionLimit(){ if(context_ == null) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.e(Countly.TAG, "Can't call this function before init has been called"); return -1; } } int sessionLimit = CountlyStarRating.getAutomaticStarRatingSessionLimit(context_); if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Getting automatic star rating session limit: [" + sessionLimit + "]"); } return sessionLimit; } /** * Returns how many sessions has star rating counted internally for the current apps version */ public int getStarRatingsCurrentVersionsSessionCount(){ if(context_ == null) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.e(Countly.TAG, "Can't call this function before init has been called"); return -1; } } int sessionCount = CountlyStarRating.getCurrentVersionsSessionCount(context_); if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Getting star rating current version session count: [" + sessionCount + "]"); } return sessionCount; } /** * Set the automatic star rating session count back to 0 */ public void clearAutomaticStarRatingSessionCount(){ if(context_ == null) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.e(Countly.TAG, "Can't call this function before init has been called"); return; } } if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Clearing star rating session count"); } CountlyStarRating.clearAutomaticStarRatingSessionCount(context_); } /** * Set if the star rating dialog is cancellable * @param isCancellable set this true if it should be cancellable */ public synchronized Countly setIfStarRatingDialogIsCancellable(boolean isCancellable){ if(context_ == null) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.e(Countly.TAG, "Can't call this function before init has been called"); return this; } } if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Setting if star rating is cancellable: [" + isCancellable + "]"); } CountlyStarRating.setIfRatingDialogIsCancellable(context_, isCancellable); return this; } /** * Set the override for forcing to use HTTP POST for all connections to the server * @param isItForced the flag for the new status, set "true" if you want it to be forced * @deprecated use CountlyConfig during init to set this */ public synchronized Countly setHttpPostForced(boolean isItForced) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Setting if HTTP POST is forced: [" + isItForced + "]"); } isHttpPostForced = isItForced; return this; } /** * Get the status of the override for HTTP POST * @return return "true" if HTTP POST ir forced */ public boolean isHttpPostForced() { return isHttpPostForced; } private void checkIfDeviceIsAppCrawler(){ String deviceName = DeviceInfo.getDevice(); for(int a = 0 ; a < appCrawlerNames.size() ; a++) { if(deviceName.equals(appCrawlerNames.get(a))){ deviceIsAppCrawler = true; return; } } } /** * Set if Countly SDK should ignore app crawlers * @param shouldIgnore if crawlers should be ignored */ public synchronized Countly setShouldIgnoreCrawlers(boolean shouldIgnore){ if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Setting if should ignore app crawlers: [" + shouldIgnore + "]"); } shouldIgnoreCrawlers = shouldIgnore; return this; } /** * Add app crawler device name to the list of names that should be ignored * @param crawlerName the name to be ignored */ public void addAppCrawlerName(String crawlerName) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Adding app crawler name: [" + crawlerName + "]"); } if(crawlerName != null && !crawlerName.isEmpty()) { appCrawlerNames.add(crawlerName); } } /** * Return if current device is detected as a app crawler * @return returns if devices is detected as a app crawler */ public boolean isDeviceAppCrawler() { return deviceIsAppCrawler; } /** * Return if the countly sdk should ignore app crawlers */ public boolean ifShouldIgnoreCrawlers(){ return shouldIgnoreCrawlers; } /** * Returns the device id used by countly for this device * @return device ID */ public synchronized String getDeviceID() { if(!isInitialized()) { throw new IllegalStateException("init must be called before getDeviceID"); } return connectionQueue_.getDeviceId().getId(); } /** * Returns the type of the device ID used by countly for this device. * @return device ID type */ public synchronized DeviceId.Type getDeviceIDType(){ if(!isInitialized()) { throw new IllegalStateException("init must be called before getDeviceID"); } return connectionQueue_.getDeviceId().getType(); } /** * @deprecated use CountlyConfig during init to set this * @param shouldAddMetadata * @return */ public synchronized Countly setPushIntentAddMetadata(boolean shouldAddMetadata) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Setting if adding metadata to push intents: [" + shouldAddMetadata + "]"); } addMetadataToPushIntents = shouldAddMetadata; return this; } /** * Set if automatic activity tracking should use short names * @deprecated use CountlyConfig during init to set this * @param shouldUseShortName set true if you want short names */ public synchronized Countly setAutoTrackingUseShortName(boolean shouldUseShortName) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Setting if automatic view tracking should use short names: [" + shouldUseShortName + "]"); } automaticTrackingShouldUseShortName = shouldUseShortName; return this; } /** * Set if attribution should be enabled * @param shouldEnableAttribution set true if you want to enable it, set false if you want to disable it */ public synchronized Countly setEnableAttribution(boolean shouldEnableAttribution) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Setting if attribution should be enabled"); } isAttributionEnabled = shouldEnableAttribution; return this; } /** * @deprecated use CountlyConfig during init to set this * @param shouldRequireConsent * @return */ public synchronized Countly setRequiresConsent(boolean shouldRequireConsent){ if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Setting if consent should be required, [" + shouldRequireConsent + "]"); } requiresConsent = shouldRequireConsent; return this; } /** * Initiate all things related to consent */ private void initConsent(){ //groupedFeatures.put("activity", new String[]{CountlyFeatureNames.sessions, CountlyFeatureNames.events, CountlyFeatureNames.views}); //groupedFeatures.put("interaction", new String[]{CountlyFeatureNames.sessions, CountlyFeatureNames.events, CountlyFeatureNames.views}); } /** * Special things needed to be done during setting push consent * @param consentValue The value of push consent */ private void doPushConsentSpecialAction(boolean consentValue){ if(isLoggingEnabled()) { Log.d(TAG, "Doing push consent special action: [" + consentValue + "]"); } connectionQueue_.getCountlyStore().setConsentPush(consentValue); } /** * Actions needed to be done for the consent related location erasure */ private void doLocationConsentSpecialErasure(){ resetLocationValues(); connectionQueue_.sendLocation(); } /** * Check if the given name is a valid feature name * @param name the name of the feature to be tested if it is valid * @return returns true if value is contained in feature name array */ private boolean isValidFeatureName(String name){ for(String fName:validFeatureNames){ if(fName.equals(name)){ return true; } } return false; } /** * Prepare features into json format * @param features the names of features that are about to be changed * @param consentValue the value for the new consent * @return provided consent changes in json format */ private String formatConsentChanges(String [] features, boolean consentValue){ StringBuilder preparedConsent = new StringBuilder(); preparedConsent.append("{"); for(int a = 0 ; a < features.length ; a++){ if(a != 0){ preparedConsent.append(","); } preparedConsent.append('"'); preparedConsent.append(features[a]); preparedConsent.append('"'); preparedConsent.append(':'); preparedConsent.append(consentValue); } preparedConsent.append("}"); return preparedConsent.toString(); } /** * Group multiple features into a feature group * @param groupName name of the consent group * @param features array of feature to be added to the consent group * @return Returns link to Countly for call chaining */ public synchronized Countly createFeatureGroup(String groupName, String[] features){ if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Creating a feature group with the name: [" + groupName + "]"); } groupedFeatures.put(groupName, features); return this; } /** * Set the consent of a feature group * @param groupName name of the consent group * @param isConsentGiven the value that should be set for this consent group * @return Returns link to Countly for call chaining */ public synchronized Countly setConsentFeatureGroup(String groupName, boolean isConsentGiven){ if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Setting consent for feature group named: [" + groupName + "] with value: [" + isConsentGiven + "]"); } if(!groupedFeatures.containsKey(groupName)){ if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Trying to set consent for a unknown feature group: [" + groupName + "]"); } return this; } setConsent(groupedFeatures.get(groupName), isConsentGiven); return this; } /** * Set the consent of a feature * @param featureNames feature names for which consent should be changed * @param isConsentGiven the consent value that should be set * @return Returns link to Countly for call chaining */ public synchronized Countly setConsent(String[] featureNames, boolean isConsentGiven){ final boolean isInit = isInitialized();//is the SDK initialized if(!requiresConsent){ //if consent is not required, ignore all calls to it return this; } boolean previousSessionsConsent = false; if(featureConsentValues.containsKey(CountlyFeatureNames.sessions)){ previousSessionsConsent = featureConsentValues.get(CountlyFeatureNames.sessions); } boolean previousLocationConsent = false; if(featureConsentValues.containsKey(CountlyFeatureNames.location)){ previousLocationConsent = featureConsentValues.get(CountlyFeatureNames.location); } boolean currentSessionConsent = previousSessionsConsent; for(String featureName:featureNames) { if (Countly.sharedInstance() != null && Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Setting consent for feature named: [" + featureName + "] with value: [" + isConsentGiven + "]"); } if (!isValidFeatureName(featureName)) { Log.d(Countly.TAG, "Given feature: [" + featureName + "] is not a valid name, ignoring it"); continue; } featureConsentValues.put(featureName, isConsentGiven); //special actions for each feature switch (featureName){ case CountlyFeatureNames.push: if(isInit) { //if the SDK is already initialized, do the special action now doPushConsentSpecialAction(isConsentGiven); } else { //do the special action later delayedPushConsent = isConsentGiven; } break; case CountlyFeatureNames.sessions: currentSessionConsent = isConsentGiven; break; case CountlyFeatureNames.location: if(previousLocationConsent && !isConsentGiven){ //if consent is about to be removed if(isInit){ doLocationConsentSpecialErasure(); } else { delayedLocationErasure = true; } } break; } } String formattedChanges = formatConsentChanges(featureNames, isConsentGiven); if(isInit && (collectedConsentChanges.size() == 0)){ //if countly is initialized and collected changes are already sent, send consent now connectionQueue_.sendConsentChanges(formattedChanges); context_.sendBroadcast(new Intent(CONSENT_BROADCAST)); //if consent has changed and it was set to true if((previousSessionsConsent != currentSessionConsent) && currentSessionConsent){ //if consent was given, we need to begin the session if(isBeginSessionSent){ //if the first timing for a beginSession call was missed, send it again onStartHelper(); } } } else { // if countly is not initialized, collect and send it after it is collectedConsentChanges.add(formattedChanges); } return this; } /** * Give the consent to a feature * @param featureNames the names of features for which consent should be given * @return Returns link to Countly for call chaining */ public synchronized Countly giveConsent(String[] featureNames){ if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Giving consent for features named: [" + Arrays.toString(featureNames) + "]"); } setConsent(featureNames, true); return this; } /** * Remove the consent of a feature * @param featureNames the names of features for which consent should be removed * @return Returns link to Countly for call chaining */ public synchronized Countly removeConsent(String[] featureNames){ if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Removing consent for features named: [" + Arrays.toString(featureNames) + "]"); } setConsent(featureNames, false); return this; } /** * Get the current consent state of a feature * @param featureName the name of a feature for which consent should be checked * @return the consent value */ public synchronized boolean getConsent(String featureName){ if(!requiresConsent){ //return true silently return true; } Boolean returnValue = featureConsentValues.get(featureName); if(returnValue == null) { if(featureName.equals(CountlyFeatureNames.push)){ //if the feature is 'push", set it with the value from preferences boolean storedConsent = connectionQueue_.getCountlyStore().getConsentPush(); if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Push consent has not been set this session. Setting the value found stored in preferences:[" + storedConsent + "]"); } featureConsentValues.put(featureName, storedConsent); returnValue = storedConsent; } else { returnValue = false; } } if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Returning consent for feature named: [" + featureName + "] [" + returnValue + "]"); } return returnValue; } /** * Print the consent values of all features * @return Returns link to Countly for call chaining */ public synchronized Countly checkAllConsent(){ if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Checking and printing consent for All features"); } if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Is consent required? [" + requiresConsent + "]"); } //make sure push consent has been added to the feature map getConsent(CountlyFeatureNames.push); StringBuilder sb = new StringBuilder(); for(String key:featureConsentValues.keySet()) { sb.append("Feature named [").append(key).append("], consent value: [").append(featureConsentValues.get(key)).append("]\n"); } if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, sb.toString()); } return this; } /** * Returns true if any consent has been given * @return true - any consent has been given, false - no consent has been given */ protected boolean anyConsentGiven(){ if (!requiresConsent){ //no consent required - all consent given return true; } for(String key:featureConsentValues.keySet()) { if(featureConsentValues.get(key)){ return true; } } return false; } /** * Show the rating dialog to the user * @param widgetId ID that identifies this dialog * @return */ public synchronized Countly showFeedbackPopup(final String widgetId, final String closeButtonText, final Activity activity, final CountlyStarRating.FeedbackRatingCallback callback){ if (!isInitialized()) { throw new IllegalStateException("Countly.sharedInstance().init must be called before showFeedbackPopup"); } CountlyStarRating.showFeedbackPopup(widgetId, closeButtonText, activity, this, connectionQueue_, callback); return this; } /** * If enable, will automatically download newest remote config_ values on init. * @deprecated use CountlyConfig during init to set this * @param enabled set true for enabling it * @param callback callback called after the update was done * @return */ public synchronized Countly setRemoteConfigAutomaticDownload(boolean enabled, RemoteConfig.RemoteConfigCallback callback){ if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Setting if remote config_ Automatic download will be enabled, " + enabled); } remoteConfigAutomaticUpdateEnabled = enabled; remoteConfigInitCallback = callback; return this; } /** * Manually update remote config_ values * @param callback */ public void remoteConfigUpdate(RemoteConfig.RemoteConfigCallback callback){ if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Manually calling to updateRemoteConfig"); } if (!isInitialized()) { throw new IllegalStateException("Countly.sharedInstance().init must be called before remoteConfigUpdate"); } if(!anyConsentGiven()){ return; } RemoteConfig.updateRemoteConfigValues(context_, null, null, connectionQueue_, false, callback); } /** * Manual remote config_ update call. Will only update the keys provided. * @param keysToInclude * @param callback */ public void updateRemoteConfigForKeysOnly(String[] keysToInclude, RemoteConfig.RemoteConfigCallback callback){ if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Manually calling to updateRemoteConfig with include keys"); } if (!isInitialized()) { throw new IllegalStateException("Countly.sharedInstance().init must be called before updateRemoteConfigForKeysOnly"); } if(!anyConsentGiven()){ if(callback != null){ callback.callback("No consent given"); } return; } if (keysToInclude == null && Countly.sharedInstance().isLoggingEnabled()) { Log.w(Countly.TAG,"updateRemoteConfigExceptKeys passed 'keys to include' array is null"); } RemoteConfig.updateRemoteConfigValues(context_, keysToInclude, null, connectionQueue_, false, callback); } /** * Manual remote config_ update call. Will update all keys except the ones provided * @param keysToExclude * @param callback */ public void updateRemoteConfigExceptKeys(String[] keysToExclude, RemoteConfig.RemoteConfigCallback callback) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Manually calling to updateRemoteConfig with exclude keys"); } if (!isInitialized()) { throw new IllegalStateException("Countly.sharedInstance().init must be called before updateRemoteConfigExceptKeys"); } if(!anyConsentGiven()){ if(callback != null){ callback.callback("No consent given"); } return; } if (keysToExclude == null && Countly.sharedInstance().isLoggingEnabled()) { Log.w(Countly.TAG,"updateRemoteConfigExceptKeys passed 'keys to ignore' array is null"); } RemoteConfig.updateRemoteConfigValues(context_, null, keysToExclude, connectionQueue_, false, callback); } /** * Get the stored value for the provided remote config_ key * @param key * @return */ public Object getRemoteConfigValueForKey(String key){ if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Calling remoteConfigValueForKey"); } if (!isInitialized()) { throw new IllegalStateException("Countly.sharedInstance().init must be called before remoteConfigValueForKey"); } if(!anyConsentGiven()) { return null; } return RemoteConfig.getValue(key, context_); } /** * Clear all stored remote config_ values */ public void remoteConfigClearValues(){ if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Calling remoteConfigClearValues"); } if (!isInitialized()) { throw new IllegalStateException("Countly.sharedInstance().init must be called before remoteConfigClearValues"); } RemoteConfig.clearValueStore(context_); } /** * Allows you to add custom header key/value pairs to each request * @deprecated use CountlyConfig during init to set this */ public void addCustomNetworkRequestHeaders(Map<String, String> headerValues){ if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Calling addCustomNetworkRequestHeaders"); } requestHeaderCustomValues = headerValues; if(connectionQueue_ != null){ connectionQueue_.setRequestHeaderCustomValues(requestHeaderCustomValues); } } /** * Deletes all stored requests to server. * This includes events, crashes, views, sessions, etc * Call only if you don't need that information */ public void flushRequestQueues(){ if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Calling flushRequestQueues"); } if (!isInitialized()) { throw new IllegalStateException("Countly.sharedInstance().init must be called before flushRequestQueues"); } CountlyStore store = connectionQueue_.getCountlyStore(); int count = 0; while (true) { final String[] storedEvents = store.connections(); if (storedEvents == null || storedEvents.length == 0) { // currently no data to send, we are done for now break; } //remove stored data store.removeConnection(storedEvents[0]); count++; } if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "flushRequestQueues removed [" + count + "] requests"); } } /** * Countly will attempt to fulfill all stored requests on demand */ public void doStoredRequests(){ if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Calling doStoredRequests"); } if (!isInitialized()) { throw new IllegalStateException("Countly.sharedInstance().init must be called before doStoredRequests"); } connectionQueue_.tick(); } /* public Countly offlineModeEnable(){ if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Calling offlineModeEnable"); } } public Countly offlineModeDisable(){ if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Calling offlineModeDisable"); } } */ // for unit testing ConnectionQueue getConnectionQueue() { return connectionQueue_; } void setConnectionQueue(final ConnectionQueue connectionQueue) { connectionQueue_ = connectionQueue; } ExecutorService getTimerService() { return timerService_; } EventQueue getEventQueue() { return eventQueue_; } void setEventQueue(final EventQueue eventQueue) { eventQueue_ = eventQueue; } long getPrevSessionDurationStartTime() { return prevSessionDurationStartTime_; } void setPrevSessionDurationStartTime(final long prevSessionDurationStartTime) { prevSessionDurationStartTime_ = prevSessionDurationStartTime; } int getActivityCount() { return activityCount_; } synchronized boolean getDisableUpdateSessionRequests() { return disableUpdateSessionRequests_; } @SuppressWarnings("InfiniteRecursion") public void stackOverflow() { this.stackOverflow(); } @SuppressWarnings("ConstantConditions") public synchronized Countly crashTest(int crashNumber) { if (crashNumber == 1){ if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Running crashTest 1"); } stackOverflow(); }else if (crashNumber == 2){ if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Running crashTest 2"); } //noinspection UnusedAssignment,divzero @SuppressWarnings("NumericOverflow") int test = 10/0; }else if (crashNumber == 3){ if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Running crashTest 3"); } Object[] o = null; //noinspection InfiniteLoopStatement while (true) { o = new Object[] { o }; } }else if (crashNumber == 4){ if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Running crashTest 4"); } throw new RuntimeException("This is a crash"); } else{ if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Running crashTest 5"); } String test = null; //noinspection ResultOfMethodCallIgnored test.charAt(1); } return Countly.sharedInstance(); } }
package ru.ifmo.nds.dcns; import ru.ifmo.nds.NonDominatedSorting; import ru.ifmo.nds.util.ArrayHelper; import ru.ifmo.nds.util.DominanceHelper; import ru.ifmo.nds.util.ArraySorter; import ru.ifmo.nds.util.MathEx; public abstract class DCNSBase extends NonDominatedSorting { private double[][] points; private int[] next; private int[] firstIndex; private int[] ranks; private int[] parents; private int[] temp; DCNSBase(int maximumPoints, int maximumDimension) { super(maximumPoints, maximumDimension); this.points = new double[maximumPoints][]; this.next = new int[maximumPoints]; this.firstIndex = new int[maximumPoints]; this.ranks = new int[maximumPoints]; this.parents = new int[maximumPoints]; this.temp = new int[maximumPoints]; } @Override protected void closeImpl() { this.points = null; this.next = null; this.firstIndex = null; this.ranks = null; this.parents = null; this.temp = null; } final boolean checkIfDoesNotDominate(int targetFront, int pointIndex) { int index = firstIndex[targetFront]; final double[] point = points[pointIndex]; final int maxObj = point.length - 1; while (index != -1) { // cannot assume `points[index]` is lexicographically smaller than `point` // because the right part is processed front-first. if (DominanceHelper.strictlyDominatesAssumingNotEqual(points[index], point, maxObj)) { parents[pointIndex] = index; return false; } index = next[index]; } return true; } abstract int findRank(int targetFrom, int targetUntil, int pointIndex); private int writeOutAndFindRanksWithoutParentChecking(int insertedFrontStart, int tempStart, int minTargetFrontToCompare, int targetFrontUntil) { for (int index = insertedFrontStart; index != -1; index = next[index], ++tempStart) { ranks[index] = findRank(minTargetFrontToCompare, targetFrontUntil, index); temp[tempStart] = index; } return tempStart; } private int writeOutAndFindRanksWithParentChecking(int insertedFrontStart, int tempStart, int targetFrontUntil) { for (int index = insertedFrontStart; index != -1; index = next[index], ++tempStart) { int myMinTargetFront = ranks[parents[index]] + 1; ranks[index] = myMinTargetFront == targetFrontUntil ? myMinTargetFront : findRank(myMinTargetFront, targetFrontUntil, index); temp[tempStart] = index; } return tempStart; } private int putToFronts(int pointIdx, int m, int targetFrontUntil) { boolean frontMoved = false; boolean allToMoved = true; while (--pointIdx >= m) { int index = temp[pointIdx]; int rankPtr = ranks[index]; int diff = targetFrontUntil - rankPtr; if (diff == 0) { frontMoved = true; next[index] = -1; ++targetFrontUntil; } else { allToMoved &= frontMoved && diff == 1; next[index] = firstIndex[rankPtr]; } firstIndex[rankPtr] = index; } return (frontMoved ? 1 : 0) ^ (allToMoved ? 2 : 0); } private void merge(int l, int m, int n) { int r = Math.min(n, m + m - l); int targetFrontUntil = l; while (targetFrontUntil < m && firstIndex[targetFrontUntil] != -1) { ++targetFrontUntil; } // First front insertion is slightly special int insertedFront = m, insertedFrontStart = firstIndex[insertedFront]; int firstPointIdx = writeOutAndFindRanksWithoutParentChecking(insertedFrontStart, m, l, targetFrontUntil); int firstResult = putToFronts(firstPointIdx, m, targetFrontUntil); targetFrontUntil += firstResult & 1; ++insertedFront; // General insertion if no preliminary break if (firstResult <= 1) { while (insertedFront < r && (insertedFrontStart = firstIndex[insertedFront]) != -1) { int pointIdx = writeOutAndFindRanksWithParentChecking(insertedFrontStart, m, targetFrontUntil); int result = putToFronts(pointIdx, m, targetFrontUntil); targetFrontUntil += result & 1; ++insertedFront; if (result > 1) { break; } } } // Degenerate case if some fronts needs to be simply appended if (insertedFront == targetFrontUntil) { // Case 1: ranks need not be rewritten while (insertedFront < r && firstIndex[insertedFront] != -1) { ++insertedFront; ++targetFrontUntil; } } else { // Case 2: ranks need to be rewritten while (insertedFront < r && (insertedFrontStart = firstIndex[insertedFront]) != -1) { firstIndex[targetFrontUntil] = insertedFrontStart; for (int i = insertedFrontStart; i != -1; i = next[i]) { ranks[i] = targetFrontUntil; } ++insertedFront; ++targetFrontUntil; } } // If there are fewer than N fronts, need to erase the next-to-last front pointer. if (targetFrontUntil < r) { firstIndex[targetFrontUntil] = -1; } } private void merge0(int n, int maxObj) { for (int r = 1; r < n; r += 2) { int l = r - 1; // We can assume, here and only here, that `l` is lexicographically smaller than `r`. if (DominanceHelper.strictlyDominatesAssumingLexicographicallySmaller(points[l], points[r], maxObj)) { parents[r] = l; } else { next[r] = l; firstIndex[l] = r; firstIndex[r] = -1; ranks[r] = l; } } } @Override protected void sortChecked(double[][] points, int[] ranks, int maximalMeaningfulRank) { int oldN = points.length; int maxObj = points[0].length - 1; ArrayHelper.fillIdentity(indices, oldN); sorter.lexicographicalSort(points, indices, 0, oldN, maxObj + 1); int n = ArraySorter.retainUniquePoints(points, indices, this.points, ranks); for (int i = 0; i < n; ++i) { this.ranks[i] = i; firstIndex[i] = i; next[i] = -1; parents[i] = -1; } int treeLevel = MathEx.log2up(n); // The first run of merging can be written with a much smaller leading constant. merge0(n, maxObj); // The rest of the runs use the generic implementation. for (int i = 1; i < treeLevel; i++) { int delta = 1 << i, delta2 = delta + delta; for (int r = delta; r < n; r += delta2) { merge(r - delta, r, n); } } for (int i = 0; i < oldN; ++i) { ranks[i] = this.ranks[ranks[i]]; this.points[i] = null; } } }
package org.pdxfinder.dataloaders; import org.pdxfinder.graph.dao.*; import org.pdxfinder.services.DataImportService; import org.pdxfinder.services.UtilityService; import org.pdxfinder.services.ds.Standardizer; import org.pdxfinder.services.dto.LoaderDTO; import org.pdxfinder.services.dto.NodeSuggestionDTO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Service; import java.io.*; import java.util.*; @Service @PropertySource("classpath:loader.properties") @ConfigurationProperties(prefix = "hci") public class LoadHCI extends LoaderBase { private final static Logger log = LoggerFactory.getLogger(LoadHCI.class); @Value("${data-dir}") private String finderRootDir; public LoadHCI(UtilityService utilityService, DataImportService dataImportService) { super(utilityService, dataImportService); } public void run() throws Exception { initMethod(); globalLoadingOrder(); } @Override protected void initMethod() { log.info("Loading Huntsman PDX data. "); dto = new LoaderDTO(); jsonFile = finderRootDir + "/data/" + dataSourceAbbreviation + "/pdx/models.json"; dataSource = dataSourceAbbreviation; filesDirectory = ""; } @Override protected void step01GetMetaDataFolder() { } // HCI uses common implementation Steps step08GetMetaData,step09LoadPatientData default @Override protected void step10LoadExternalURLs() { loadExternalURLs(dataSourceContact,Standardizer.NOT_SPECIFIED); } @Override protected void step11LoadBreastMarkers() { } // HCI uses common implementation Steps step12CreateModels default @Override protected void step13LoadSpecimens() { dto.getModelCreation().addRelatedSample(dto.getPatientSample()); dto.getModelCreation().addGroup(providerDS); dataImportService.saveSample(dto.getPatientSample()); dataImportService.savePatientSnapshot(dto.getPatientSnapshot()); EngraftmentSite engraftmentSite = dataImportService.getImplantationSite(dto.getImplantationSiteStr()); EngraftmentType engraftmentType = dataImportService.getImplantationType(dto.getImplantationtypeStr()); // uggh parse strains ArrayList<HostStrain> strainList= new ArrayList(); String strains = dto.getStrain(); if(strains.contains(" and ")){ strainList.add(nsgBS); strainList.add(nsBS); }else if(strains.contains("gamma")){ strainList.add(nsBS); }else{ strainList.add(nsBS); } int count = 0; for(HostStrain strain : strainList){ count++; Specimen specimen = new Specimen(); specimen.setExternalId(dto.getModelID()+"-"+count); specimen.setEngraftmentSite(engraftmentSite); specimen.setEngraftmentType(engraftmentType); specimen.setHostStrain(strain); Sample specSample = new Sample(); specSample.setSourceSampleId(dto.getModelID()+"-"+count); specimen.setSample(specSample); dto.getModelCreation().addSpecimen(specimen); dto.getModelCreation().addRelatedSample(specSample); dataImportService.saveSpecimen(specimen); } dataImportService.saveModelCreation(dto.getModelCreation()); } @Override protected void step14LoadPatientTreatments() { } @Override protected void step15LoadImmunoHistoChemistry() { String ihcFileStr = String.format("%s/data/%s/ihc/ihc.txt", finderRootDir, dataSourceAbbreviation); File file = new File(ihcFileStr); if (file.exists()) { Platform pl = dataImportService.getPlatform("immunohistochemistry","cytogenetics", providerDS); String currentLine = ""; int currentLineCounter = 1; String[] row; Map<String, MolecularCharacterization> molCharMap = new HashMap<>(); try { BufferedReader buf = new BufferedReader(new FileReader(ihcFileStr)); while (true) { currentLine = buf.readLine(); if (currentLine == null) { break; //skip the first two rows } else if (currentLineCounter < 3) { currentLineCounter++; continue; } else { row = currentLine.split("\t"); if (row.length > 0) { String modelId = row[0]; String sampleId = row[1]; String markerSymbol = row[2]; String result = row[3]; //System.out.println(modelId); if (modelId.isEmpty() || sampleId.isEmpty() || markerSymbol.isEmpty() || result.isEmpty()) continue; NodeSuggestionDTO nsdto = dataImportService.getSuggestedMarker(this.getClass().getSimpleName(), dataSource, modelId, markerSymbol, "cytogenetics","ImmunoHistoChemistry"); Marker marker = null; if(nsdto.getNode() == null){ //uh oh, we found an unrecognised marker symbol, abort, abort!!!! reportManager.addMessage(nsdto.getLogEntity()); continue; } else{ //we have a marker node, check message marker = (Marker)nsdto.getNode(); if(nsdto.getLogEntity() != null){ reportManager.addMessage(nsdto.getLogEntity()); } MolecularCharacterization mc; if (molCharMap.containsKey(modelId + "---" + sampleId)) { mc = molCharMap.get(modelId + "---" + sampleId); } else { mc = new MolecularCharacterization(); mc.setType("cytogenetics"); mc.setPlatform(pl); MarkerAssociation ma = new MarkerAssociation(); mc.addMarkerAssociation(ma); molCharMap.put(modelId + "---" + sampleId, mc); } MolecularData molecularData = new MolecularData(); molecularData.setMarker(marker.getHgncSymbol()); molecularData.setCytogeneticsResult(result); mc.getFirstMarkerAssociation().addMolecularData(molecularData); } } } } } catch (Exception e) { e.printStackTrace(); System.out.println(currentLineCounter + " " + currentLine.toString()); } //System.out.println(molCharMap.toString()); for (Map.Entry<String, MolecularCharacterization> entry : molCharMap.entrySet()) { String key = entry.getKey(); MolecularCharacterization mc = entry.getValue(); String[] modAndSamp = key.split(" String modelId = modAndSamp[0]; String sampleId = modAndSamp[1]; //Sample sample = dataImportService.findMouseSampleWithMolcharByModelIdAndDataSourceAndSampleId(modelId, hciDS.getAbbreviation(), sampleId); Sample sample = dataImportService.findHumanSampleWithMolcharByModelIdAndDataSource(modelId, providerDS.getAbbreviation()); if (sample == null) { log.warn("Missing model or sample: " + modelId + " " + sampleId); continue; } sample.addMolecularCharacterization(mc); mc.getFirstMarkerAssociation().encodeMolecularData(); dataImportService.saveSample(sample); } } else { log.warn("Skipping loading IHC for HCI"); } } @Override protected void step16LoadVariationData() { } @Override void step17LoadModelDosingStudies() throws Exception { loadModelDosingStudies(); } @Override void step18SetAdditionalGroups() { throw new UnsupportedOperationException(); } }
package com.exedio.cope.instrument; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; import com.exedio.cope.Attribute; import com.exedio.cope.BooleanAttribute; import com.exedio.cope.ComputedFunction; import com.exedio.cope.DateAttribute; import com.exedio.cope.Item; import com.exedio.cope.LengthViolationException; import com.exedio.cope.NestingRuntimeException; import com.exedio.cope.MandatoryViolationException; import com.exedio.cope.ObjectAttribute; import com.exedio.cope.ReadOnlyViolationException; import com.exedio.cope.UniqueViolationException; import com.exedio.cope.util.ClassComparator; abstract class CopeAttribute { final JavaAttribute javaAttribute; final int accessModifier; final CopeClass copeClass; /** * The persistent type of this attribute. */ final String persistentType; final boolean readOnly; final boolean notNull; final boolean lengthConstrained; final boolean computed; final Option getterOption; final Option setterOption; final boolean isBoolean; CopeAttribute( final JavaAttribute javaAttribute, final Class typeClass, final String persistentType, final List initializerArguments, final String setterOption, final String getterOption) throws InjectorParseException { this.javaAttribute = javaAttribute; this.accessModifier = javaAttribute.accessModifier; this.copeClass = CopeClass.getCopeClass(javaAttribute.parent); this.persistentType = persistentType; this.computed = ComputedFunction.class.isAssignableFrom(typeClass); if(!computed) { if(initializerArguments.size()<1) throw new InjectorParseException("attribute "+javaAttribute.name+" has no option."); final String optionString = (String)initializerArguments.get(0); //System.out.println(optionString); final Attribute.Option option = getOption(optionString); this.readOnly = option.readOnly; this.notNull = option.mandatory; if(initializerArguments.size()>1) { final String secondArgument = (String)initializerArguments.get(1); boolean lengthConstrained = true; try { Integer.parseInt(secondArgument); } catch(NumberFormatException e) { lengthConstrained = false; } this.lengthConstrained = lengthConstrained; } else this.lengthConstrained = false; if(option.unique) copeClass.makeUnique(new CopeUniqueConstraint(this)); } else { this.readOnly = false; this.notNull = false; this.lengthConstrained = false; } this.getterOption = new Option(getterOption, true); this.setterOption = new Option(setterOption, true); this.isBoolean = BooleanAttribute.class.equals(typeClass); copeClass.add(this); } private ArrayList hashes; final void addHash(final CopeHash hash) { if(hashes==null) hashes = new ArrayList(); hashes.add(hash); } final List getHashes() { if(hashes==null) return Collections.EMPTY_LIST; else return hashes; } final String getName() { return javaAttribute.name; } final int getGeneratedGetterModifier() { return getterOption.getModifier(javaAttribute.modifier); } final JavaClass getParent() { return javaAttribute.parent; } /** * Returns the type of this attribute to be used in accessor (setter/getter) methods. * Differs from {@link #getPersistentType() the persistent type}, * if and only if the attribute is {@link #isBoxed() boxed}. */ String getBoxedType() { return persistentType; } /** * Returns, whether the persistent type is &quot;boxed&quot; into a native type. * This happens if the attribute is mandatory * and the persistent type is convertable to a native types (int, double, boolean). * @see #getBoxedType() */ boolean isBoxed() { return false; } String getBoxingPrefix() { throw new RuntimeException(); } String getBoxingPostfix() { throw new RuntimeException(); } String getUnBoxingPrefix() { throw new RuntimeException(); } String getUnBoxingPostfix() { throw new RuntimeException(); } final boolean isPartOfUniqueConstraint() { for( final Iterator i = copeClass.getUniqueConstraints().iterator(); i.hasNext(); ) { final CopeAttribute[] uniqueConstraint = ((CopeUniqueConstraint)i.next()).copeAttributes; for(int j=0; j<uniqueConstraint.length; j++) { if(this == uniqueConstraint[j]) return true; } } return false; } final boolean isInitial() { return (readOnly || notNull) && !computed; } private final boolean isWriteable() { return !readOnly && !computed; } final boolean hasIsGetter() { return isBoolean && getterOption.booleanAsIs; } final boolean hasGeneratedSetter() { return isWriteable() && setterOption.exists; } final int getGeneratedSetterModifier() { return setterOption.getModifier(javaAttribute.modifier); } private SortedSet setterExceptions = null; final SortedSet getSetterExceptions() { if(setterExceptions!=null) return setterExceptions; final TreeSet result = new TreeSet(ClassComparator.getInstance()); fillSetterExceptions(result); this.setterExceptions = Collections.unmodifiableSortedSet(result); return this.setterExceptions; } protected void fillSetterExceptions(final SortedSet result) { if(isPartOfUniqueConstraint()) result.add(UniqueViolationException.class); if(readOnly) result.add(ReadOnlyViolationException.class); if(notNull && !isBoxed()) result.add(MandatoryViolationException.class); if(lengthConstrained) result.add(LengthViolationException.class); } private SortedSet exceptionsToCatchInSetter = null; /** * Compute exceptions to be caught in the setter. * These are just those thrown by {@link com.exedio.cope.Item#setAttribute(ObjectAttribute,Object)} * which are not in the setters throws clause. * (see {@link #getSetterExceptions()}) */ final SortedSet getExceptionsToCatchInSetter() { if(exceptionsToCatchInSetter!=null) return exceptionsToCatchInSetter; final TreeSet result = new TreeSet(ClassComparator.getInstance()); fillExceptionsThrownByGenericSetter(result); result.removeAll(getSetterExceptions()); this.exceptionsToCatchInSetter = Collections.unmodifiableSortedSet(result); return this.exceptionsToCatchInSetter; } protected void fillExceptionsThrownByGenericSetter(final SortedSet result) { result.add(UniqueViolationException.class); result.add(MandatoryViolationException.class); result.add(ReadOnlyViolationException.class); result.add(LengthViolationException.class); } private SortedSet toucherExceptions = null; final SortedSet getToucherExceptions() { if(toucherExceptions!=null) return toucherExceptions; final TreeSet modifyableToucherExceptions = new TreeSet(ClassComparator.getInstance()); if(isPartOfUniqueConstraint()) modifyableToucherExceptions.add(UniqueViolationException.class); if(readOnly) modifyableToucherExceptions.add(ReadOnlyViolationException.class); this.toucherExceptions = Collections.unmodifiableSortedSet(modifyableToucherExceptions); return this.toucherExceptions; } private SortedSet exceptionsToCatchInToucher = null; /** * Compute exceptions to be caught in the toucher. * These are just those thrown by {@link com.exedio.cope.Item#touchAttribute(DateAttribute)} * which are not in the touchers throws clause. * (see {@link #getToucherExceptions()}) */ final SortedSet getExceptionsToCatchInToucher() { if(exceptionsToCatchInToucher!=null) return exceptionsToCatchInToucher; final TreeSet result = new TreeSet(ClassComparator.getInstance()); result.add(UniqueViolationException.class); result.add(ReadOnlyViolationException.class); result.removeAll(getSetterExceptions()); this.exceptionsToCatchInToucher = Collections.unmodifiableSortedSet(result); return this.exceptionsToCatchInToucher; } final static Attribute.Option getOption(final String optionString) { try { //System.out.println(optionString); final Attribute.Option result = (Attribute.Option)Item.class.getDeclaredField(optionString).get(null); if(result==null) throw new NullPointerException(optionString); return result; } catch(NoSuchFieldException e) { throw new NestingRuntimeException(e, optionString); } catch(IllegalAccessException e) { throw new NestingRuntimeException(e, optionString); } } }
package tests; import static org.fest.assertions.Assertions.assertThat; import java.io.File; import org.fest.assertions.GenericAssert; import org.kercoin.magrit.Configuration; import org.kercoin.magrit.Configuration.Authentication; public class ConfigurationAssert extends GenericAssert<ConfigurationAssert, Configuration> { ConfigurationAssert(Class<ConfigurationAssert> selfType, Configuration actual) { super(selfType, actual); } public ConfigurationAssert onPort(int expected) { assertThat(actual.getSshPort()).isEqualTo(expected); return this; } public ConfigurationAssert hasHomeDir(String absolutePath) { assertThat(actual.getRepositoriesHomeDir().getAbsolutePath()).isEqualTo(cleanPath(absolutePath)); return this; } public ConfigurationAssert hasWorkDir(String absolutePath) { assertThat(actual.getWorkHomeDir().getAbsolutePath()).isEqualTo(cleanPath(absolutePath)); return this; } public ConfigurationAssert hasPublickeyDir(String absolutePath) { assertThat(actual.getPublickeyRepositoryDir().getAbsolutePath()).isEqualTo(cleanPath(absolutePath)); return this; } public ConfigurationAssert hasAuthentication(Authentication expected) { assertThat(actual.getAuthentication()).isEqualTo(expected); return this; } public ConfigurationAssert isRemoteAllowed(boolean expected) { assertThat(actual.isRemoteAllowed()).isEqualTo(expected); return this; } private static String cleanPath(String absolutePath) { return new File(absolutePath).getPath(); } }
public class Test { private String field; public Test fluentNoop() { return this; } public Test indirectlyFluentNoop() { return this.fluentNoop(); } public Test fluentSet(String x) { this.field = x; return this; } public static Test identity(Test t) { return t; } public String get() { return field; } public static String source() { return "taint"; } public static void sink(String s) {} public static void test1() { Test t = new Test(); t.fluentNoop().fluentSet(source()).fluentNoop(); sink(t.get()); // $hasTaintFlow=y } public static void test2() { Test t = new Test(); Test.identity(t).fluentNoop().fluentSet(source()).fluentNoop(); sink(t.get()); // $hasTaintFlow=y } public static void test3() { Test t = new Test(); t.indirectlyFluentNoop().fluentSet(source()).fluentNoop(); sink(t.get()); // $hasTaintFlow=y } }
package databaseconnectortest.test; import com.mendix.logging.ILogNode; import com.mendix.modules.microflowengine.actions.actioncall.parameters.stringtemplate.TemplateParameter; import com.mendix.systemwideinterfaces.core.IContext; import com.mendix.systemwideinterfaces.core.IMendixObject; import com.mendix.systemwideinterfaces.core.meta.IMetaObject; import com.mendix.systemwideinterfaces.core.meta.IMetaPrimitive; import com.mendix.systemwideinterfaces.javaactions.parameters.IStringTemplate; import com.mendix.systemwideinterfaces.javaactions.parameters.ITemplateParameter; import com.mendix.systemwideinterfaces.javaactions.parameters.TemplateParameterType; import databaseconnector.impl.JdbcConnector; import databaseconnector.interfaces.ConnectionManager; import databaseconnector.interfaces.ObjectInstantiator; import org.junit.Rule; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import java.math.BigDecimal; import java.sql.*; import java.util.*; import java.util.AbstractMap.SimpleEntry; import java.util.Date; import java.util.stream.Collectors; import java.util.stream.Stream; import static com.mendix.systemwideinterfaces.core.meta.IMetaPrimitive.PrimitiveType.Boolean; import static com.mendix.systemwideinterfaces.core.meta.IMetaPrimitive.PrimitiveType.String; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; public class JdbcConnectorTest { private static final String jdbcUrl = "TestUrl"; private static final String userName = "TestUserName"; private static final String password = "TestPassword"; private static final String sqlQuery = "TestSqlQuery"; private static final String entityName = "TestEntityName"; @Rule public MockitoRule rule = MockitoJUnit.rule(); @Mock private IContext context; @Mock private ObjectInstantiator objectInstantiator; @Mock private ILogNode iLogNode; @Mock private Connection connection; @Mock private ConnectionManager connectionManager; @Mock private PreparedStatement preparedStatement; @Mock private ResultSet resultSet; @Mock private ResultSetMetaData resultSetMetaData; @InjectMocks private JdbcConnector jdbcConnector; private IMetaObject mockIMetaObject(SimpleEntry<String, IMetaPrimitive.PrimitiveType>... entries) { IMetaObject metaObject = mock(IMetaObject.class); when(metaObject.getName()).thenReturn(entityName); final Collection<IMetaPrimitive> primitives = new ArrayList<>(); Arrays.asList(entries).forEach(entry -> { IMetaPrimitive metaPrimitive = mock(IMetaPrimitive.class); when(metaPrimitive.getName()).thenReturn(entry.getKey()); when(metaPrimitive.getType()).thenReturn(entry.getValue()); when(metaObject.getMetaPrimitive(entry.getKey())).thenReturn(metaPrimitive); primitives.add(metaPrimitive); }); Mockito.<Collection<? extends IMetaPrimitive>>when(metaObject.getMetaPrimitives()).thenReturn(primitives); return metaObject; } private SimpleEntry<String, IMetaPrimitive.PrimitiveType> entry(String name, IMetaPrimitive.PrimitiveType type) { return new SimpleEntry<>(name, type); } @Test public void testStatementCreationException() throws SQLException { Exception testException = new SQLException("Test Exception Text"); when(connectionManager.getConnection(anyString(), anyString(), anyString())).thenReturn(connection); when(connection.prepareStatement(anyString())).thenThrow(testException); try { jdbcConnector.executeQuery(jdbcUrl, userName, password, mockIMetaObject(), sqlQuery, context); fail("An exception should occur!"); } catch(SQLException sqlException) {} verify(connection).close(); verify(preparedStatement, never()).close(); } @Test public void testObjectInstantiatorException() throws SQLException { Exception testException = new IllegalArgumentException("Test Exception Text"); when(connectionManager.getConnection(anyString(), anyString(), anyString())).thenReturn(connection); when(connection.prepareStatement(anyString())).thenReturn(preparedStatement); when(preparedStatement.executeQuery()).thenReturn(resultSet); when(resultSet.getMetaData()).thenReturn(resultSetMetaData); when(resultSet.next()).thenReturn(true, false); when(objectInstantiator.instantiate(anyObject(), anyString())).thenThrow(testException); Stream<IMendixObject> result = jdbcConnector.executeQuery(jdbcUrl, userName, password, mockIMetaObject(), sqlQuery, context); try { result.collect(Collectors.toList()); fail("An exception should occur!"); } catch(IllegalArgumentException iae) {} verify(objectInstantiator).instantiate(context, entityName); verify(connection).close(); verify(preparedStatement).close(); verify(resultSet).close(); } @Test public void testConnectionClose() throws SQLException { when(connectionManager.getConnection(anyString(), anyString(), anyString())).thenReturn(connection); when(connection.prepareStatement(anyString())).thenReturn(preparedStatement); when(preparedStatement.executeQuery()).thenReturn(resultSet); when(resultSet.getMetaData()).thenReturn(resultSetMetaData); Stream<IMendixObject> result = jdbcConnector.executeQuery(jdbcUrl, userName, password, mockIMetaObject(), sqlQuery, context); assertEquals(0, result.count()); verify(connection).close(); verify(preparedStatement).close(); verify(resultSet).close(); } @Test public void testSomeResults() throws SQLException { IMendixObject resultObject = mock(IMendixObject.class); when(connectionManager.getConnection(anyString(), anyString(), anyString())).thenReturn(connection); when(connection.prepareStatement(anyString())).thenReturn(preparedStatement); when(preparedStatement.executeQuery()).thenReturn(resultSet); when(objectInstantiator.instantiate(anyObject(), anyString())).thenReturn(resultObject); when(resultSetMetaData.getColumnName(anyInt())).thenReturn("a", "b"); when(resultSetMetaData.getColumnCount()).thenReturn(2); when(resultSet.getMetaData()).thenReturn(resultSetMetaData); when(resultSet.getBoolean(anyInt())).thenReturn(true); when(resultSet.next()).thenReturn(true, true, true, true, false); IMetaObject metaObject = mockIMetaObject(entry("a", Boolean), entry("b", Boolean)); Stream<IMendixObject> result = jdbcConnector.executeQuery(jdbcUrl, userName, password, metaObject, sqlQuery, context); List<IMendixObject> lst = result.collect(Collectors.toList()); assertEquals(4, lst.size()); verify(objectInstantiator, times(4)).instantiate(context, entityName); verify(connectionManager).getConnection(jdbcUrl, userName, password); verify(connection).prepareStatement(sqlQuery); verify(resultSet, times(3)).getMetaData(); verify(resultSetMetaData).getColumnCount(); verify(resultSet, times(5)).next(); } @Test public void testSomeResultsWithTwoColumns() throws SQLException { String columnName1 = "TestColumnName1"; String columnName2 = "TestColumnName2"; String row1Value1 = "TestRow1Value1"; String row1Value2 = "TestRow1Value2"; String row2Value1 = "TestRow2Value1"; String row2Value2 = "TestRow2Value2"; IMendixObject resultObject1 = mock(IMendixObject.class); IMendixObject resultObject2 = mock(IMendixObject.class); when(connectionManager.getConnection(anyString(), anyString(), anyString())).thenReturn(connection); when(connection.prepareStatement(anyString())).thenReturn(preparedStatement); when(preparedStatement.executeQuery()).thenReturn(resultSet); when(objectInstantiator.instantiate(anyObject(), anyString())).thenReturn(resultObject1, resultObject2); when(resultSetMetaData.getColumnCount()).thenReturn(2); when(resultSetMetaData.getColumnName(1)).thenReturn(columnName1); when(resultSetMetaData.getColumnName(2)).thenReturn(columnName2); when(resultSet.getMetaData()).thenReturn(resultSetMetaData); when(resultSet.next()).thenReturn(true, true, false); when(resultSet.getString(1)).thenReturn(row1Value1, row2Value1); when(resultSet.getString(2)).thenReturn(row1Value2, row2Value2); IMetaObject metaObject = mockIMetaObject(entry(columnName1, String), entry(columnName2, String)); Stream<IMendixObject> result = jdbcConnector.executeQuery(jdbcUrl, userName, password, metaObject, sqlQuery, context); List<IMendixObject> lst = result.collect(Collectors.toList()); assertEquals(2, lst.size()); verify(resultObject1).setValue(context, columnName1, row1Value1); verify(resultObject1).setValue(context, columnName2, row1Value2); verify(resultObject2).setValue(context, columnName1, row2Value1); verify(resultObject2).setValue(context, columnName2, row2Value2); verify(objectInstantiator, times(2)).instantiate(context, entityName); verify(resultSet, times(3)).next(); } @Test public void testResultForBoolean() throws SQLException { IMendixObject resultObject = mock(IMendixObject.class); when(connectionManager.getConnection(anyString(), anyString(), anyString())).thenReturn(connection); when(connection.prepareStatement(anyString())).thenReturn(preparedStatement); when(preparedStatement.executeQuery()).thenReturn(resultSet); when(objectInstantiator.instantiate(anyObject(), anyString())).thenReturn(resultObject); when(resultSetMetaData.getColumnCount()).thenReturn(1); when(resultSetMetaData.getColumnName(1)).thenReturn("Boolean"); when(resultSet.getMetaData()).thenReturn(resultSetMetaData); when(resultSet.next()).thenReturn(true, false); // As Mockito does not allow to return null, we should not mock getting Boolean // when(resultSet.getBoolean(1)).thenReturn(null); IMetaObject metaObject = mockIMetaObject(entry("Boolean", Boolean), entry("String", String)); Stream<IMendixObject> result = jdbcConnector.executeQuery(jdbcUrl, userName, password, metaObject, sqlQuery, context); List<IMendixObject> lst = result.collect(Collectors.toList()); assertEquals(1, lst.size()); verify(resultObject).setValue(context, "Boolean", false); verify(objectInstantiator, times(1)).instantiate(context, entityName); verify(resultSet, times(2)).next(); } @Test public void testNoResults() throws Exception { IMendixObject resultObject = mock(IMendixObject.class); when(connectionManager.getConnection(anyString(), anyString(), anyString())).thenReturn(connection); when(connection.prepareStatement(anyString())).thenReturn(preparedStatement); when(preparedStatement.executeQuery()).thenReturn(resultSet); when(objectInstantiator.instantiate(anyObject(), anyString())).thenReturn(resultObject); when(resultSetMetaData.getColumnCount()).thenReturn(2); when(resultSetMetaData.getColumnName(1)).thenReturn("a"); when(resultSetMetaData.getColumnName(2)).thenReturn("b"); when(resultSet.getMetaData()).thenReturn(resultSetMetaData); when(resultSet.next()).thenReturn(false); IMetaObject metaObject = mockIMetaObject(entry("a", String), entry("b", Boolean)); Stream<IMendixObject> result = jdbcConnector.executeQuery(jdbcUrl, userName, password, metaObject, sqlQuery, context); assertEquals(0, result.count()); verify(objectInstantiator, never()).instantiate(context, entityName); verify(resultSet, times(1)).next(); } /* * Tests for Execute statement */ @Test public void exceptionOnPrepareStatementForExecuteStatement() throws SQLException { Exception testException = new SQLException("Test Exception Text"); when(connectionManager.getConnection(anyString(), anyString(), anyString())).thenReturn(connection); when(connection.prepareStatement(anyString())).thenThrow(testException); try { jdbcConnector.executeStatement(jdbcUrl, userName, password, sqlQuery); fail("An exception should occur!"); } catch(SQLException sqlException) {} verify(connection).close(); verify(preparedStatement, never()).close(); verify(preparedStatement, never()).executeUpdate(); } @Test public void exceptionOnExecuteUpdate() throws SQLException { Exception testException = new SQLException("Test Exception Text"); when(connectionManager.getConnection(anyString(), anyString(), anyString())).thenReturn(connection); when(connection.prepareStatement(anyString())).thenReturn(preparedStatement); when(preparedStatement.executeUpdate()).thenThrow(testException); try { jdbcConnector.executeStatement(jdbcUrl, userName, password, sqlQuery); fail("An exception should occur!"); } catch(SQLException sqlException) {} verify(connection).close(); verify(preparedStatement).close(); verify(preparedStatement).executeUpdate(); } @Test public void testCloseResourcesForExecuteStatement() throws SQLException { when(connectionManager.getConnection(anyString(), anyString(), anyString())).thenReturn(connection); when(connection.prepareStatement(anyString())).thenReturn(preparedStatement); when(preparedStatement.executeUpdate()).thenReturn(5); long result = jdbcConnector.executeStatement(jdbcUrl, userName, password, sqlQuery); assertEquals(5, result); verify(connection).close(); verify(preparedStatement).close(); } @Test public void testExecuteQueryPlaceholders() throws SQLException{ when(connectionManager.getConnection(anyString(), anyString(), anyString())).thenReturn(connection); when(connection.prepareStatement(anyString())).thenReturn(preparedStatement); when(preparedStatement.executeQuery()).thenReturn(resultSet); when(resultSet.getMetaData()).thenReturn(resultSetMetaData); when(resultSet.next()).thenReturn(false); StringTemplateBuilder builder = new StringTemplateBuilder(); builder.setText("Some query", "Updated query"); jdbcConnector.executeQuery(jdbcUrl, userName, password, mockIMetaObject(), builder.build(), context); verify(connection).prepareStatement("Updated query"); } @Test public void testExecuteStatementPlaceholders() throws SQLException { when(connectionManager.getConnection(anyString(), anyString(), anyString())).thenReturn(connection); when(connection.prepareStatement(anyString())).thenReturn(preparedStatement); when(preparedStatement.executeUpdate()).thenReturn(1); StringTemplateBuilder builder = new StringTemplateBuilder(); builder.setText("Some query", "Updated query"); jdbcConnector.executeStatement(jdbcUrl, userName, password, builder.build()); verify(connection).prepareStatement("Updated query"); } @Test public void testExecuteQueryParameters() throws SQLException { when(connectionManager.getConnection(anyString(), anyString(), anyString())).thenReturn(connection); when(connection.prepareStatement(anyString())).thenReturn(preparedStatement); when(preparedStatement.executeQuery()).thenReturn(resultSet); when(resultSet.getMetaData()).thenReturn(resultSetMetaData); when(resultSet.next()).thenReturn(false); StringTemplateBuilder builder = new StringTemplateBuilder(); builder.setText("Some query", "Updated query"); Date date = new Date(2019, 5, 1, 14, 12, 11); builder.addParameter(date, TemplateParameterType.DATETIME); builder.addParameter(5l, TemplateParameterType.INTEGER); builder.addParameter(true, TemplateParameterType.BOOLEAN); builder.addParameter("Hello", TemplateParameterType.STRING); builder.addParameter(new BigDecimal(45.5), TemplateParameterType.DECIMAL); builder.addParameter(null, TemplateParameterType.DATETIME); builder.addParameter(null, TemplateParameterType.STRING); jdbcConnector.executeQuery(jdbcUrl, userName, password, mockIMetaObject(), builder.build(), context); verify(preparedStatement).setTimestamp(1, new Timestamp(date.getTime())); verify(preparedStatement).setLong(2, 5l); verify(preparedStatement).setBoolean(3, true); verify(preparedStatement).setString(4, "Hello"); verify(preparedStatement).setBigDecimal(5, new BigDecimal(45.5)); verify(preparedStatement).setTimestamp(6, null); verify(preparedStatement).setString(7, null); } @Test public void testExecuteStatementParameters() throws SQLException { when(connectionManager.getConnection(anyString(), anyString(), anyString())).thenReturn(connection); when(connection.prepareStatement(anyString())).thenReturn(preparedStatement); when(preparedStatement.executeUpdate()).thenReturn(1); StringTemplateBuilder builder = new StringTemplateBuilder(); Date date = new Date(2019, 5, 1, 14, 12, 11); builder.addParameter(date, TemplateParameterType.DATETIME); builder.addParameter(5l, TemplateParameterType.INTEGER); builder.addParameter(true, TemplateParameterType.BOOLEAN); builder.addParameter("Hello", TemplateParameterType.STRING); builder.addParameter(new BigDecimal(45.5), TemplateParameterType.DECIMAL); builder.addParameter(null, TemplateParameterType.DATETIME); builder.addParameter(null, TemplateParameterType.STRING); jdbcConnector.executeStatement(jdbcUrl, userName, password, builder.build()); verify(preparedStatement).setTimestamp(1, new Timestamp(date.getTime())); verify(preparedStatement).setLong(2, 5l); verify(preparedStatement).setBoolean(3, true); verify(preparedStatement).setString(4, "Hello"); verify(preparedStatement).setBigDecimal(5, new BigDecimal(45.5)); verify(preparedStatement).setTimestamp(6, null); verify(preparedStatement).setString(7, null); } } class StringTemplateBuilder{ ArrayList<ITemplateParameter> templateParameters = new ArrayList<>(); String template = ""; String updatedTemplate = ""; public StringTemplateBuilder addParameter(Object value, TemplateParameterType type){ ITemplateParameter mockParameter = mock(ITemplateParameter.class); when(mockParameter.getValue()).thenReturn(value); when(mockParameter.getParameterType()).thenReturn(type); templateParameters.add(mockParameter); return this; } public StringTemplateBuilder setText(String template, String updatedTemplate){ this.template = template; this.updatedTemplate = updatedTemplate; return this; } public IStringTemplate build(){ IStringTemplate stringTemplate = mock(IStringTemplate.class); when(stringTemplate.getParameters()).thenReturn(templateParameters); when(stringTemplate.getTemplate()).thenReturn(template); when(stringTemplate.replacePlaceholders(any())).thenReturn(updatedTemplate); return stringTemplate; } }
package databaseconnectortest.test; import com.mendix.logging.ILogNode; import com.mendix.systemwideinterfaces.core.IContext; import com.mendix.systemwideinterfaces.core.IMendixObject; import com.mendix.systemwideinterfaces.core.meta.IMetaObject; import com.mendix.systemwideinterfaces.core.meta.IMetaPrimitive; import com.mendix.systemwideinterfaces.javaactions.parameters.IStringTemplate; import com.mendix.systemwideinterfaces.javaactions.parameters.ITemplateParameter; import com.mendix.systemwideinterfaces.javaactions.parameters.TemplateParameterType; import databaseconnector.impl.JdbcConnector; import databaseconnector.interfaces.ConnectionManager; import databaseconnector.interfaces.ObjectInstantiator; import org.junit.Rule; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import java.math.BigDecimal; import java.sql.*; import java.util.*; import java.util.AbstractMap.SimpleEntry; import java.util.Date; import java.util.stream.Collectors; import java.util.stream.Stream; import static com.mendix.systemwideinterfaces.core.meta.IMetaPrimitive.PrimitiveType.Boolean; import static com.mendix.systemwideinterfaces.core.meta.IMetaPrimitive.PrimitiveType.String; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; public class JdbcConnectorTest { private static final String jdbcUrl = "TestUrl"; private static final String userName = "TestUserName"; private static final String password = "TestPassword"; private static final String sqlQuery = "TestSqlQuery"; private static final String entityName = "TestEntityName"; @Rule public MockitoRule rule = MockitoJUnit.rule(); @Mock private IContext context; @Mock private ObjectInstantiator objectInstantiator; @Mock private ILogNode iLogNode; @Mock private Connection connection; @Mock private ConnectionManager connectionManager; @Mock private PreparedStatement preparedStatement; @Mock private ResultSet resultSet; @Mock private ResultSetMetaData resultSetMetaData; @InjectMocks private JdbcConnector jdbcConnector; private IMetaObject mockIMetaObject(SimpleEntry<String, IMetaPrimitive.PrimitiveType>... entries) { IMetaObject metaObject = mock(IMetaObject.class); when(metaObject.getName()).thenReturn(entityName); final Collection<IMetaPrimitive> primitives = new ArrayList<>(); Arrays.asList(entries).forEach(entry -> { IMetaPrimitive metaPrimitive = mock(IMetaPrimitive.class); when(metaPrimitive.getName()).thenReturn(entry.getKey()); when(metaPrimitive.getType()).thenReturn(entry.getValue()); when(metaObject.getMetaPrimitive(entry.getKey())).thenReturn(metaPrimitive); primitives.add(metaPrimitive); }); Mockito.<Collection<? extends IMetaPrimitive>>when(metaObject.getMetaPrimitives()).thenReturn(primitives); return metaObject; } private SimpleEntry<String, IMetaPrimitive.PrimitiveType> entry(String name, IMetaPrimitive.PrimitiveType type) { return new SimpleEntry<>(name, type); } @Test public void testStatementCreationException() throws SQLException { Exception testException = new SQLException("Test Exception Text"); when(connectionManager.getConnection(anyString(), anyString(), anyString())).thenReturn(connection); when(connection.prepareStatement(anyString())).thenThrow(testException); try { jdbcConnector.executeQuery(jdbcUrl, userName, password, mockIMetaObject(), sqlQuery, context); fail("An exception should occur!"); } catch(SQLException sqlException) {} verify(connection).close(); verify(preparedStatement, never()).close(); } @Test public void testObjectInstantiatorException() throws SQLException { Exception testException = new IllegalArgumentException("Test Exception Text"); when(connectionManager.getConnection(anyString(), anyString(), anyString())).thenReturn(connection); when(connection.prepareStatement(anyString())).thenReturn(preparedStatement); when(preparedStatement.executeQuery()).thenReturn(resultSet); when(resultSet.getMetaData()).thenReturn(resultSetMetaData); when(resultSet.next()).thenReturn(true, false); when(objectInstantiator.instantiate(anyObject(), anyString())).thenThrow(testException); Stream<IMendixObject> result = jdbcConnector.executeQuery(jdbcUrl, userName, password, mockIMetaObject(), sqlQuery, context); try { result.collect(Collectors.toList()); fail("An exception should occur!"); } catch(IllegalArgumentException iae) {} verify(objectInstantiator).instantiate(context, entityName); verify(connection).close(); verify(preparedStatement).close(); verify(resultSet).close(); } @Test public void testConnectionClose() throws SQLException { when(connectionManager.getConnection(anyString(), anyString(), anyString())).thenReturn(connection); when(connection.prepareStatement(anyString())).thenReturn(preparedStatement); when(preparedStatement.executeQuery()).thenReturn(resultSet); when(resultSet.getMetaData()).thenReturn(resultSetMetaData); Stream<IMendixObject> result = jdbcConnector.executeQuery(jdbcUrl, userName, password, mockIMetaObject(), sqlQuery, context); assertEquals(0, result.count()); verify(connection).close(); verify(preparedStatement).close(); verify(resultSet).close(); } @Test public void testSomeResults() throws SQLException { IMendixObject resultObject = mock(IMendixObject.class); when(connectionManager.getConnection(anyString(), anyString(), anyString())).thenReturn(connection); when(connection.prepareStatement(anyString())).thenReturn(preparedStatement); when(preparedStatement.executeQuery()).thenReturn(resultSet); when(objectInstantiator.instantiate(anyObject(), anyString())).thenReturn(resultObject); when(resultSetMetaData.getColumnName(anyInt())).thenReturn("a", "b"); when(resultSetMetaData.getColumnCount()).thenReturn(2); when(resultSet.getMetaData()).thenReturn(resultSetMetaData); when(resultSet.getBoolean(anyInt())).thenReturn(true); when(resultSet.next()).thenReturn(true, true, true, true, false); IMetaObject metaObject = mockIMetaObject(entry("a", Boolean), entry("b", Boolean)); Stream<IMendixObject> result = jdbcConnector.executeQuery(jdbcUrl, userName, password, metaObject, sqlQuery, context); List<IMendixObject> lst = result.collect(Collectors.toList()); assertEquals(4, lst.size()); verify(objectInstantiator, times(4)).instantiate(context, entityName); verify(connectionManager).getConnection(jdbcUrl, userName, password); verify(connection).prepareStatement(sqlQuery); verify(resultSet, times(3)).getMetaData(); verify(resultSetMetaData).getColumnCount(); verify(resultSet, times(5)).next(); } @Test public void testSomeResultsWithTwoColumns() throws SQLException { String columnName1 = "TestColumnName1"; String columnName2 = "TestColumnName2"; String row1Value1 = "TestRow1Value1"; String row1Value2 = "TestRow1Value2"; String row2Value1 = "TestRow2Value1"; String row2Value2 = "TestRow2Value2"; IMendixObject resultObject1 = mock(IMendixObject.class); IMendixObject resultObject2 = mock(IMendixObject.class); when(connectionManager.getConnection(anyString(), anyString(), anyString())).thenReturn(connection); when(connection.prepareStatement(anyString())).thenReturn(preparedStatement); when(preparedStatement.executeQuery()).thenReturn(resultSet); when(objectInstantiator.instantiate(anyObject(), anyString())).thenReturn(resultObject1, resultObject2); when(resultSetMetaData.getColumnCount()).thenReturn(2); when(resultSetMetaData.getColumnName(1)).thenReturn(columnName1); when(resultSetMetaData.getColumnName(2)).thenReturn(columnName2); when(resultSet.getMetaData()).thenReturn(resultSetMetaData); when(resultSet.next()).thenReturn(true, true, false); when(resultSet.getString(1)).thenReturn(row1Value1, row2Value1); when(resultSet.getString(2)).thenReturn(row1Value2, row2Value2); IMetaObject metaObject = mockIMetaObject(entry(columnName1, String), entry(columnName2, String)); Stream<IMendixObject> result = jdbcConnector.executeQuery(jdbcUrl, userName, password, metaObject, sqlQuery, context); List<IMendixObject> lst = result.collect(Collectors.toList()); assertEquals(2, lst.size()); verify(resultObject1).setValue(context, columnName1, row1Value1); verify(resultObject1).setValue(context, columnName2, row1Value2); verify(resultObject2).setValue(context, columnName1, row2Value1); verify(resultObject2).setValue(context, columnName2, row2Value2); verify(objectInstantiator, times(2)).instantiate(context, entityName); verify(resultSet, times(3)).next(); } @Test public void testResultForBoolean() throws SQLException { IMendixObject resultObject = mock(IMendixObject.class); when(connectionManager.getConnection(anyString(), anyString(), anyString())).thenReturn(connection); when(connection.prepareStatement(anyString())).thenReturn(preparedStatement); when(preparedStatement.executeQuery()).thenReturn(resultSet); when(objectInstantiator.instantiate(anyObject(), anyString())).thenReturn(resultObject); when(resultSetMetaData.getColumnCount()).thenReturn(1); when(resultSetMetaData.getColumnName(1)).thenReturn("Boolean"); when(resultSet.getMetaData()).thenReturn(resultSetMetaData); when(resultSet.next()).thenReturn(true, false); // As Mockito does not allow to return null, we should not mock getting Boolean // when(resultSet.getBoolean(1)).thenReturn(null); IMetaObject metaObject = mockIMetaObject(entry("Boolean", Boolean), entry("String", String)); Stream<IMendixObject> result = jdbcConnector.executeQuery(jdbcUrl, userName, password, metaObject, sqlQuery, context); List<IMendixObject> lst = result.collect(Collectors.toList()); assertEquals(1, lst.size()); verify(resultObject).setValue(context, "Boolean", false); verify(objectInstantiator, times(1)).instantiate(context, entityName); verify(resultSet, times(2)).next(); } @Test public void testNoResults() throws Exception { IMendixObject resultObject = mock(IMendixObject.class); when(connectionManager.getConnection(anyString(), anyString(), anyString())).thenReturn(connection); when(connection.prepareStatement(anyString())).thenReturn(preparedStatement); when(preparedStatement.executeQuery()).thenReturn(resultSet); when(objectInstantiator.instantiate(anyObject(), anyString())).thenReturn(resultObject); when(resultSetMetaData.getColumnCount()).thenReturn(2); when(resultSetMetaData.getColumnName(1)).thenReturn("a"); when(resultSetMetaData.getColumnName(2)).thenReturn("b"); when(resultSet.getMetaData()).thenReturn(resultSetMetaData); when(resultSet.next()).thenReturn(false); IMetaObject metaObject = mockIMetaObject(entry("a", String), entry("b", Boolean)); Stream<IMendixObject> result = jdbcConnector.executeQuery(jdbcUrl, userName, password, metaObject, sqlQuery, context); assertEquals(0, result.count()); verify(objectInstantiator, never()).instantiate(context, entityName); verify(resultSet, times(1)).next(); } /* * Tests for Execute statement */ @Test public void exceptionOnPrepareStatementForExecuteStatement() throws SQLException { Exception testException = new SQLException("Test Exception Text"); when(connectionManager.getConnection(anyString(), anyString(), anyString())).thenReturn(connection); when(connection.prepareStatement(anyString())).thenThrow(testException); try { jdbcConnector.executeStatement(jdbcUrl, userName, password, sqlQuery); fail("An exception should occur!"); } catch(SQLException sqlException) {} verify(connection).close(); verify(preparedStatement, never()).close(); verify(preparedStatement, never()).executeUpdate(); } @Test public void exceptionOnExecuteUpdate() throws SQLException { Exception testException = new SQLException("Test Exception Text"); when(connectionManager.getConnection(anyString(), anyString(), anyString())).thenReturn(connection); when(connection.prepareStatement(anyString())).thenReturn(preparedStatement); when(preparedStatement.executeUpdate()).thenThrow(testException); try { jdbcConnector.executeStatement(jdbcUrl, userName, password, sqlQuery); fail("An exception should occur!"); } catch(SQLException sqlException) {} verify(connection).close(); verify(preparedStatement).close(); verify(preparedStatement).executeUpdate(); } @Test public void testCloseResourcesForExecuteStatement() throws SQLException { when(connectionManager.getConnection(anyString(), anyString(), anyString())).thenReturn(connection); when(connection.prepareStatement(anyString())).thenReturn(preparedStatement); when(preparedStatement.executeUpdate()).thenReturn(5); long result = jdbcConnector.executeStatement(jdbcUrl, userName, password, sqlQuery); assertEquals(5, result); verify(connection).close(); verify(preparedStatement).close(); } @Test public void testExecuteQueryPlaceholders() throws SQLException{ when(connectionManager.getConnection(anyString(), anyString(), anyString())).thenReturn(connection); when(connection.prepareStatement(anyString())).thenReturn(preparedStatement); when(preparedStatement.executeQuery()).thenReturn(resultSet); when(resultSet.getMetaData()).thenReturn(resultSetMetaData); when(resultSet.next()).thenReturn(false); StringTemplateBuilder builder = new StringTemplateBuilder(); builder.setText("Some query", "Updated query"); jdbcConnector.executeQuery(jdbcUrl, userName, password, mockIMetaObject(), builder.build(), context); verify(connection).prepareStatement("Updated query"); } @Test public void testExecuteStatementPlaceholders() throws SQLException { when(connectionManager.getConnection(anyString(), anyString(), anyString())).thenReturn(connection); when(connection.prepareStatement(anyString())).thenReturn(preparedStatement); when(preparedStatement.executeUpdate()).thenReturn(1); StringTemplateBuilder builder = new StringTemplateBuilder(); builder.setText("Some query", "Updated query"); jdbcConnector.executeStatement(jdbcUrl, userName, password, builder.build()); verify(connection).prepareStatement("Updated query"); } @Test public void testExecuteQueryParameters() throws SQLException { when(connectionManager.getConnection(anyString(), anyString(), anyString())).thenReturn(connection); when(connection.prepareStatement(anyString())).thenReturn(preparedStatement); when(preparedStatement.executeQuery()).thenReturn(resultSet); when(resultSet.getMetaData()).thenReturn(resultSetMetaData); when(resultSet.next()).thenReturn(false); StringTemplateBuilder builder = new StringTemplateBuilder(); builder.setText("Some query", "Updated query"); Date date = new Date(2019, 5, 1, 14, 12, 11); builder.addParameter(date, TemplateParameterType.DATETIME); builder.addParameter(5l, TemplateParameterType.INTEGER); builder.addParameter(true, TemplateParameterType.BOOLEAN); builder.addParameter("Hello", TemplateParameterType.STRING); builder.addParameter(new BigDecimal(45.5), TemplateParameterType.DECIMAL); builder.addParameter(null, TemplateParameterType.DATETIME); builder.addParameter(null, TemplateParameterType.STRING); jdbcConnector.executeQuery(jdbcUrl, userName, password, mockIMetaObject(), builder.build(), context); verify(preparedStatement).setTimestamp(1, new Timestamp(date.getTime())); verify(preparedStatement).setLong(2, 5l); verify(preparedStatement).setBoolean(3, true); verify(preparedStatement).setString(4, "Hello"); verify(preparedStatement).setBigDecimal(5, new BigDecimal(45.5)); verify(preparedStatement).setTimestamp(6, null); verify(preparedStatement).setString(7, null); } @Test public void testExecuteStatementParameters() throws SQLException { when(connectionManager.getConnection(anyString(), anyString(), anyString())).thenReturn(connection); when(connection.prepareStatement(anyString())).thenReturn(preparedStatement); when(preparedStatement.executeUpdate()).thenReturn(1); StringTemplateBuilder builder = new StringTemplateBuilder(); Date date = new Date(2019, 5, 1, 14, 12, 11); builder.addParameter(date, TemplateParameterType.DATETIME); builder.addParameter(5l, TemplateParameterType.INTEGER); builder.addParameter(true, TemplateParameterType.BOOLEAN); builder.addParameter("Hello", TemplateParameterType.STRING); builder.addParameter(new BigDecimal(45.5), TemplateParameterType.DECIMAL); builder.addParameter(null, TemplateParameterType.DATETIME); builder.addParameter(null, TemplateParameterType.STRING); jdbcConnector.executeStatement(jdbcUrl, userName, password, builder.build()); verify(preparedStatement).setTimestamp(1, new Timestamp(date.getTime())); verify(preparedStatement).setLong(2, 5l); verify(preparedStatement).setBoolean(3, true); verify(preparedStatement).setString(4, "Hello"); verify(preparedStatement).setBigDecimal(5, new BigDecimal(45.5)); verify(preparedStatement).setTimestamp(6, null); verify(preparedStatement).setString(7, null); } } class StringTemplateBuilder{ ArrayList<ITemplateParameter> templateParameters = new ArrayList<>(); String template = ""; String updatedTemplate = ""; public StringTemplateBuilder addParameter(Object value, TemplateParameterType type){ ITemplateParameter mockParameter = mock(ITemplateParameter.class); when(mockParameter.getValue()).thenReturn(value); when(mockParameter.getParameterType()).thenReturn(type); templateParameters.add(mockParameter); return this; } public StringTemplateBuilder setText(String template, String updatedTemplate){ this.template = template; this.updatedTemplate = updatedTemplate; return this; } public IStringTemplate build(){ IStringTemplate stringTemplate = mock(IStringTemplate.class); when(stringTemplate.getParameters()).thenReturn(templateParameters); when(stringTemplate.getTemplate()).thenReturn(template); when(stringTemplate.replacePlaceholders(any())).thenReturn(updatedTemplate); return stringTemplate; } }
package com.scg.domain; import java.util.Formatter; /** * Footer for Small Consulting Group Invoices. * @author Brian Stamm */ public final class InvoiceFooter { private final String businessName; private final String dashes = "==============================="; private int pageNumber = 1; /** * Construct an InvoiceFooter. * @param businessName - name of business to include in footer */ public InvoiceFooter(String businessName) { this.businessName = businessName; } /** * Increment the current page number by one. */ public void incrementPageNumber(){ pageNumber++; } /** * Print the formatted footer. * @returns Formatted footer string. */ @Override public String toString(){ StringBuilder sb = new StringBuilder(); Formatter ft = new Formatter(sb); //(%s%n%s%-69s Page: %3d%n%s%n", businessName, pageNumber, pageBreak); ft.format("%s\n%s\nPage Number: %s\n", businessName,pageNumber,dashes); ft.close(); return sb.toString(); } }
package org.ccnx.ccn.utils.explorer; import java.awt.Color; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.ListSelectionModel; import javax.swing.border.BevelBorder; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import org.ccnx.ccn.CCNHandle; import org.ccnx.ccn.config.UserConfiguration; import org.ccnx.ccn.io.content.Link; import org.ccnx.ccn.profiles.security.access.group.Group; import org.ccnx.ccn.profiles.security.access.group.GroupAccessControlManager; import org.ccnx.ccn.profiles.security.access.group.GroupManager; import org.ccnx.ccn.protocol.ContentName; public class GroupManagerGUI extends JDialog implements ActionListener, ListSelectionListener { private static final long serialVersionUID = 1L; private GroupManager gm; private PrincipalEnumerator pEnum; ContentName userStorage = ContentName.fromNative(UserConfiguration.defaultNamespace(), "Users"); ContentName groupStorage = ContentName.fromNative(UserConfiguration.defaultNamespace(), "Groups"); private ArrayList<ContentName> usersContentNameList = new ArrayList<ContentName>(); private ArrayList<ContentName> groupsContentNameList = new ArrayList<ContentName>(); private ArrayList<ContentName> groupMembersContentNameList = new ArrayList<ContentName>(); private SortedListModel groupsListModel = null; private SortedListModel groupMembershipListModel = null; private SortedListModel principalsListModel = null; // group updates private String selectedGroupFriendlyName; private ArrayList<Link> membersToAdd; private ArrayList<Link> membersToRemove; // GUI elements private JPanel membershipPanel; private JLabel newGroupLabel; private JLabel groupMembershipLabel; private JLabel groupMembersLabel; private JList groupsList; private JList principalsList; private JList groupMembershipList; private JTextField newGroupName; private JButton createGroupButton; private JButton addMemberButton; private JButton removeMemberButton; private JButton applyChangesButton; private JButton cancelChangesButton; private JScrollPane scrollPaneGroupMembership; private JScrollPane scrollPaneUsers; // GUI positions private int LEFT_MARGIN = 30; private int SCROLL_PANEL_WIDTH = 185; private int SCROLL_PANEL_HEIGHT = 210; private int VERTICAL_OFFSET = 170; public GroupManagerGUI(String path) { super(); setTitle("Group Manager"); getContentPane().setLayout(null); setBounds(100, 100, 550, 600); // enumerate existing users and groups try{ GroupAccessControlManager acm = new GroupAccessControlManager(null, groupStorage, userStorage, CCNHandle.open()); gm = acm.groupManager(); } catch (Exception e) { e.printStackTrace(); } pEnum = new PrincipalEnumerator(gm); usersContentNameList = pEnum.enumerateUsers(); groupsContentNameList = pEnum.enumerateGroups(); groupMembershipListModel = new SortedListModel(); // group list (single group selection) final JLabel groupsLabel = new JLabel(); groupsLabel.setText("Select an existing group:"); groupsLabel.setBounds(LEFT_MARGIN, 10, 200, 15); getContentPane().add(groupsLabel); final JScrollPane scrollPaneGroups = new JScrollPane(); scrollPaneGroups.setBounds(LEFT_MARGIN, 37, 388, 58); getContentPane().add(scrollPaneGroups); groupsListModel = new SortedListModel(); groupsListModel.addAll(groupsContentNameList.toArray()); groupsList = new JList(groupsListModel); groupsList.setName("groups"); scrollPaneGroups.setViewportView(groupsList); groupsList.setBorder(new BevelBorder(BevelBorder.LOWERED)); groupsList.addListSelectionListener(this); // create new group newGroupLabel = new JLabel(); newGroupLabel.setText("New group name: "); newGroupLabel.setBounds(LEFT_MARGIN, 120, 150, 20); getContentPane().add(newGroupLabel); newGroupName = new JTextField(); newGroupName.setBounds(LEFT_MARGIN + 150, 120, 150, 20); getContentPane().add(newGroupName); createGroupButton = new JButton(); createGroupButton.setText("Create New Group"); createGroupButton.addActionListener(this); createGroupButton.setBounds(LEFT_MARGIN, 120, 200, 20); getContentPane().add(createGroupButton); // Membership panel membershipPanel = new JPanel(); membershipPanel.setLayout(null); membershipPanel.setBounds(LEFT_MARGIN, VERTICAL_OFFSET, 480, 350); getContentPane().add(membershipPanel); // principal list groupMembersLabel = new JLabel(); groupMembersLabel.setAutoscrolls(true); groupMembersLabel.setText("Principals"); groupMembersLabel.setBounds(30, 30, 98, 15); membershipPanel.add(groupMembersLabel); scrollPaneUsers = new JScrollPane(); scrollPaneUsers.setBounds(10, 60, SCROLL_PANEL_WIDTH, SCROLL_PANEL_HEIGHT); membershipPanel.add(scrollPaneUsers); ArrayList<ContentName> principalFriendlyNames = new ArrayList<ContentName>(); principalFriendlyNames.addAll(usersContentNameList); principalFriendlyNames.addAll(groupsContentNameList); principalsListModel = new SortedListModel(); principalsListModel.addAll(principalFriendlyNames.toArray()); principalsList = new JList(principalsListModel); principalsList.setName("users"); scrollPaneUsers.setViewportView(principalsList); principalsList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); principalsList.setBorder(new BevelBorder(BevelBorder.LOWERED)); // add and remove buttons addMemberButton = new JButton(); addMemberButton.addActionListener(this); addMemberButton.setText("->"); addMemberButton.setBounds(205, 80, 52, 25); membershipPanel.add(addMemberButton); removeMemberButton = new JButton(); removeMemberButton.addActionListener(this); removeMemberButton.setText("<-"); removeMemberButton.setBounds(205, 150, 52, 25); membershipPanel.add(removeMemberButton); // group membership list groupMembershipLabel = new JLabel(); groupMembershipLabel.setAutoscrolls(true); groupMembershipLabel.setText("Group Members"); groupMembershipLabel.setBounds(312, 30, 153, 15); membershipPanel.add(groupMembershipLabel); scrollPaneGroupMembership = new JScrollPane(); scrollPaneGroupMembership.setBounds(275, 60, SCROLL_PANEL_WIDTH, SCROLL_PANEL_HEIGHT); membershipPanel.add(scrollPaneGroupMembership); groupMembershipList = new JList(groupMembershipListModel); groupMembershipList.setName("groupMembers"); scrollPaneGroupMembership.setViewportView(groupMembershipList); groupMembershipList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); groupMembershipList.setBorder(new BevelBorder(BevelBorder.LOWERED)); // apply and cancel buttons applyChangesButton = new JButton(); applyChangesButton.addActionListener(this); applyChangesButton.setMargin(new Insets(2, 2, 2, 2)); applyChangesButton.setBounds(LEFT_MARGIN, 300, 112, 25); applyChangesButton.setText("Apply Changes"); membershipPanel.add(applyChangesButton); cancelChangesButton = new JButton(); cancelChangesButton.addActionListener(this); cancelChangesButton.setMargin(new Insets(2, 2, 2, 2)); cancelChangesButton.setText("Cancel Changes"); cancelChangesButton.setBounds(320, 300, 112, 25); membershipPanel.add(cancelChangesButton); selectGroupView(); } /** * Display the basic view in which the user can select a group to edit. */ public void selectGroupView() { createGroupButton.setVisible(true); newGroupLabel.setVisible(false); newGroupName.setVisible(false); membershipPanel.setVisible(false); } /** * Display the view which allows a user to edit the membership of a group. */ public void editGroupMembershipView() { createGroupButton.setVisible(true); newGroupLabel.setVisible(false); newGroupName.setVisible(false); applyChangesButton.setText("Apply Changes"); cancelChangesButton.setText("Cancel Changes"); membershipPanel.setBorder( BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.BLACK, 2), "Group: " + selectedGroupFriendlyName)); membershipPanel.setVisible(true); } /** * Display the view which allows the user to create a new group. */ public void createNewGroupView() { createGroupButton.setVisible(false); newGroupLabel.setVisible(true); newGroupName.setVisible(true); applyChangesButton.setText("Create Group"); cancelChangesButton.setText("Cancel"); membershipPanel.setBorder( BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.BLACK, 2), "New Group")); membershipPanel.setVisible(true); } public void actionPerformed(ActionEvent e) { if (applyChangesButton == e.getSource()) applyChanges(); else if (cancelChangesButton == e.getSource()) cancelChanges(); else if (addMemberButton == e.getSource()) addPrincipals(); else if (removeMemberButton == e.getSource()) removePrincipals(); else if (createGroupButton == e.getSource()) createNewGroup(); } /** * Apply all batched operations (addition or removal of principals) */ private void applyChanges() { try{ if (selectedGroupFriendlyName != null) { // we are applying changes to an existing group Group g = gm.getGroup(selectedGroupFriendlyName); g.modify(membersToAdd, membersToRemove); } else { // we are creating a new group selectedGroupFriendlyName = newGroupName.getText(); gm.createGroup(selectedGroupFriendlyName, membersToAdd); groupsContentNameList = pEnum.enumerateGroups(); groupsListModel.clear(); groupsListModel.addAll(groupsContentNameList.toArray()); selectGroupView(); } } catch (Exception e) { e.printStackTrace(); } } /** * Cancel all batched operations (addition or removal of principals) */ private void cancelChanges() { membersToAdd = new ArrayList<Link>(); membersToRemove = new ArrayList<Link>(); populateGroupMembershipList(); populatePrincipalsList(); if (selectedGroupFriendlyName == null) selectGroupView(); } /** * Add selected principals (users of groups) to the group * identified by selectedGroupFriendlyName. * Note that addition (and removal) operations are batched and only applied when the * method applyChanges() is called. */ private void addPrincipals() { ArrayList<Object> principalsToAdd = new ArrayList<Object>(); int[] selectedPrincipals = principalsList.getSelectedIndices(); for (int index: selectedPrincipals) { Object obj = principalsList.getModel().getElementAt(index); principalsToAdd.add(obj); } for (Object obj: principalsToAdd) { ((SortedListModel) groupMembershipList.getModel()).add(obj); ((SortedListModel) principalsList.getModel()).removeElement(obj); ContentName principalContentName = (ContentName) obj; Link lk = new Link(principalContentName); membersToAdd.add(lk); } principalsList.clearSelection(); } /** * Remove selected principals (users of groups) from the group * identified by selectedGroupFriendlyName. * Note that removal (and addition) operations are batched and only applied when the * method applyChanges() is called. */ private void removePrincipals() { ArrayList<Object> principalsToRemove = new ArrayList<Object>(); int[] selectedPrincipals = groupMembershipList.getSelectedIndices(); for (int index: selectedPrincipals) { Object obj = groupMembershipList.getModel().getElementAt(index); principalsToRemove.add(obj); } for (Object obj: principalsToRemove) { ((SortedListModel) principalsList.getModel()).add(obj); ((SortedListModel) groupMembershipList.getModel()).removeElement(obj); ContentName principalContentName = (ContentName) obj; Link lk = new Link(principalContentName); membersToRemove.add(lk); } groupMembershipList.clearSelection(); } /** * Create a new group */ private void createNewGroup() { groupsList.clearSelection(); newGroupName.setText(""); selectedGroupFriendlyName = null; populateGroupMembershipList(); populatePrincipalsList(); membersToAdd = new ArrayList<Link>(); membersToRemove = new ArrayList<Link>(); createNewGroupView(); } /** * Display the members of selectedGroupFriendlyName. * If selectedGroupFriendlyName is null, the membership list is empty (e.g. we are creating a new group) */ public void populateGroupMembershipList() { groupMembershipListModel.clear(); groupMembersContentNameList = pEnum.enumerateGroupMembers(selectedGroupFriendlyName); groupMembershipListModel.addAll(groupMembersContentNameList.toArray()); } /** * Display the list of principals (users and groups) which are not already included * in the membership list of selectedGroupFriendlyName. */ public void populatePrincipalsList() { principalsListModel.clear(); ArrayList<ContentName> principalFriendlyName = new ArrayList<ContentName>(); principalFriendlyName.addAll(usersContentNameList); principalFriendlyName.addAll(groupsContentNameList); System.out.println("Group members list:"); for (ContentName cn: groupMembersContentNameList) System.out.println(cn); System.out.println(" principalFriendlyName.removeAll(groupMembersContentNameList); principalsListModel.addAll(principalFriendlyName.toArray()); } /** * Display the membership list and the list of principals that can be added * to the selected group. */ public void valueChanged(ListSelectionEvent e) { JList list = (JList) e.getSource(); if(list.getSelectedValue() != null){ ContentName groupContentName = (ContentName) list.getSelectedValue(); selectedGroupFriendlyName = ContentName.componentPrintNative(groupContentName.lastComponent()); membersToAdd = new ArrayList<Link>(); membersToRemove = new ArrayList<Link>(); populateGroupMembershipList(); populatePrincipalsList(); editGroupMembershipView(); } } }
package common; import java.awt.Graphics2D; /** * This class describes projectile in the game * @author smaboshe */ public class Projectile extends Actor { protected Position startPos; protected Position direction; protected int owner; public Projectile(Position startPos, Position direction, float startTime, float curTime, int owner) { this.startPos = new Position(startPos); // Duplicate this one so we're not following somebody else this.direction = direction; position = new Position(startPos); position.move(direction, (curTime - startTime) * BULLET_SPEED); this.owner = owner; } public boolean animate(float dTime) { position.move(direction, dTime * BULLET_SPEED); return false; } public void collision(Actor a) { // If we bump into anything, we vanish kill(); } public void draw(Graphics2D g, float scale) { // TODO Auto-generated method stub } public int getOwner() { return owner; } }
package net.acomputerdog.ircbot.command; import com.sorcix.sirc.*; import net.acomputerdog.core.logger.CLogger; import net.acomputerdog.ircbot.command.types.*; import net.acomputerdog.ircbot.command.util.CommandLine; import net.acomputerdog.ircbot.config.Config; import net.acomputerdog.ircbot.main.IrcBot; import java.util.HashMap; import java.util.Map; public abstract class Command { private static final Map<String, Command> commandNameMap = new HashMap<>(); private static final Map<String, Command> commandMap = new HashMap<>(); private final String name; private final String[] commands; private String helpString; private CLogger logger; public Command(String name, String... commands) { this.name = name; if (commands == null || commands.length == 0) { throw new IllegalArgumentException("Cannot create a command with no command strings!"); } this.commands = commands; } public Command(String command) { this(command, command); } public int getMinArgs() { return 0; } //Not actually maximum, but the maximum that can be used public int getMaxArgs() { return getMinArgs(); } public boolean allowedInChannel(Channel channel, User sender) { return true; } public boolean allowedInPM(User sender) { return true; } public abstract boolean processCommand(IrcBot bot, Channel channel, User sender, Chattable target, CommandLine command); public String getName() { return name; } public String[] getCommands() { return commands; } public String getHelpString() { if (helpString == null) { StringBuilder builder = new StringBuilder(); builder.append(Config.COMMAND_PREFIX); builder.append(commands[0]); if (getMinArgs() > 0) { for (int count = 1; count <= getMinArgs(); count++) { builder.append(' '); builder.append("<arg"); builder.append(count); builder.append('>'); } } if (getMaxArgs() > getMinArgs()) { for (int count = getMinArgs(); count <= getMaxArgs(); count++) { builder.append(' '); builder.append("[arg"); builder.append(count); builder.append(']'); } } helpString = builder.toString(); } return helpString; } protected CLogger getLogger() { if (logger == null) { logger = new CLogger("Command" + name, false, true); } return logger; } public static void onChat(IrcBot bot, Channel channel, User sender, Chattable target, String message) { if (message.length() > 1 && message.startsWith(Config.COMMAND_PREFIX)) { CommandLine cmdLine = new CommandLine(message.substring(1)); Command cmd = commandMap.get(cmdLine.command); if (cmd != null) { if (cmd.getMinArgs() <= 0 || cmdLine.hasArgs()) { if (channel == null && cmd.allowedInPM(sender)) { cmd.processCommand(bot, null, sender, target, cmdLine); } else if (cmd.allowedInChannel(channel, sender)) { cmd.processCommand(bot, channel, sender, target, cmdLine); } } else { target.send(colorError("Not enough arguments, use \"" + cmd.getHelpString() + "\".")); } } else { target.send(colorError("Unknown command, use \"" + Config.COMMAND_PREFIX + "help\" for a list of commands.")); } } } public static Map<String, Command> getCommandNameMap() { return commandNameMap; } public static Map<String, Command> getCommandMap() { return commandMap; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Command)) return false; Command command = (Command) o; return name.equals(command.name); } @Override public int hashCode() { return name.hashCode(); } @Override public String toString() { return "Command{" + "helpString='" + helpString + '\'' + '}'; } private static void registerCommand(Command command) { commandNameMap.put(command.getName(), command); for (String cmd : command.getCommands()) { Command oldCmd = commandMap.put(cmd.toLowerCase(), command); if (oldCmd != null) { command.getLogger().logWarning("Overriding command: \"" + oldCmd.getName() + "\" (alias \"" + cmd.toLowerCase() + "\")!"); } } } public static void init() { registerCommand(new CommandHelp()); registerCommand(new CommandInfo()); registerCommand(new CommandStop()); registerCommand(new CommandJoin()); registerCommand(new CommandLeave()); registerCommand(new CommandSay()); registerCommand(new CommandSayIn()); registerCommand(new CommandSayInAll()); registerCommand(new CommandMe()); registerCommand(new CommandMeIn()); registerCommand(new CommandMeInAll()); registerCommand(new CommandStatus()); registerCommand(new CommandChannels()); registerCommand(new CommandGithub()); } protected static String colorError(String message) { return IrcColors.color(message, IrcColors.RED); } }
package net.sourceforge.pebble.web.view; import java.io.ByteArrayInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.File; import java.io.FilenameFilter; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.w3c.dom.Document; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import net.sourceforge.pebble.PebbleContext; import net.sourceforge.pebble.domain.Tag; import net.sourceforge.pebble.domain.BlogEntry; import net.sourceforge.pebble.util.StringUtils; import net.sourceforge.pebble.web.listener.PebblePDFCreationListener; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Iterator; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.lowagie.text.pdf.PdfWriter; import com.lowagie.text.pdf.BaseFont; import com.lowagie.text.DocumentException; import org.xhtmlrenderer.pdf.ITextRenderer; import org.xhtmlrenderer.pdf.TrueTypeUtil; /** * Represents a binary view component and prepares the model for display. * * @author Alexander Zagniotov */ public class PdfView extends BinaryView { private static Log log = LogFactory.getLog(PdfView.class); private static final String SEP = "/"; private static final String FONTS_PATH = "fonts"; private static final String THEMES_PATH = "themes"; private static final String DEFAULT_ENCODING = "UTF-8"; private static final String PDF_CSS = "pdf.css"; private static final String SYSTEM_THEME_PATH = HtmlView.SYSTEM_THEME; private String filename = "default.pdf"; private BlogEntry entry; private long length = 0; public PdfView(BlogEntry entry, String filename) { this.entry = entry; this.filename = filename; } /** * Gets the title of this view. * * @return the title as a String */ public String getContentType() { return "application/pdf"; } public long getContentLength() { return length; } /** * Dispatches this view. * * @param request the HttpServletRequest instance * @param response the HttpServletResponse instance * @param context */ public void dispatch(HttpServletRequest request, HttpServletResponse response, ServletContext context) throws ServletException { try { ITextRenderer renderer = new ITextRenderer(); //This will be an attachment response.setHeader("Content-Disposition", "attachment; filename=" + filename); response.setHeader("Expires", "0"); response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); response.setHeader("Pragma", "public"); String author = entry.getUser().getName(); String title = entry.getTitle(); String subtitle = entry.getSubtitle(); String body = entry.getBody(); String blogName = entry.getBlog().getName(); String entryPermalink = entry.getPermalink(); String entryDescription = entry.getBlog().getDescription(); //Some of the HTML entities need to be escaped to Unicode notation \\uXXXX for XHTML markup to validate /* ugly hack */ subtitle = subtitle.replaceAll("amp;", ""); subtitle = subtitle.replaceAll("&", "&amp;"); title = title.replaceAll("amp;", ""); title = title.replaceAll("&", "&amp;"); /* ugly hack */ body = StringUtils.unescapeHTMLEntities(body); //Build absolute path to: <pebble_root>/themes/_pebble/fonts/ String webApplicationRoot = PebbleContext.getInstance().getWebApplicationRoot() + SEP + THEMES_PATH; //<pebble_root> + / + themes + / + _pebble + / + fonts String fontDirAbsolutePath = webApplicationRoot + SEP + SYSTEM_THEME_PATH + SEP + FONTS_PATH; File fontDir = new File(fontDirAbsolutePath); //Get blog entry tags for PDF metadata 'keywords' StringBuffer tags = new StringBuffer(); Iterator<Tag> currentEntryTags = entry.getAllTags().iterator(); //Build a string out of blog entry tags and seperate them by comma while (currentEntryTags.hasNext()) { Tag currentTag = currentEntryTags.next(); if (currentTag.getName() != null && !currentTag.getName().equals("")) { tags.append(currentTag.getName()); if (currentEntryTags.hasNext()) { tags.append(","); } } } //Build valid XHTML source from blog entry for parsing StringBuffer buf = new StringBuffer(); buf.append("<html>"); buf.append("<head>"); buf.append("<meta name=\"title\" content=\"" + title + " - " + blogName + "\"/>"); buf.append("<meta name=\"subject\" content=\"" + title + "\"/>"); buf.append("<meta name=\"keywords\" content=\"" + tags.toString().trim() + "\"/>"); buf.append("<meta name=\"author\" content=\"" + author + "\"/>"); buf.append("<meta name=\"creator\" content=\"Pebble (by pebble.sourceforge.net)\"/>"); buf.append("<meta name=\"producer\" content=\"Flying Saucer (by xhtmlrenderer.dev.java.net)\"/>"); buf.append("<link rel='stylesheet' type='text/css' href='" + entry.getBlog().getUrl() + THEMES_PATH + SEP + SYSTEM_THEME_PATH + SEP + PDF_CSS + "' media='print' />"); buf.append("</head>"); buf.append("<body>"); buf.append("<div id=\"header\" style=\"\">" + blogName + " - " + entryDescription + "</div>"); buf.append("<p>"); //Gets TTF or OTF font file from the font directory in the system theme folder if (fontDir.isDirectory()) { File[] files = fontDir.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { String lower = name.toLowerCase(); //Load TTF or OTF files return lower.endsWith(".otf") || lower.endsWith(".ttf"); } }); if (files.length > 0) { String fontFamilyName = ""; //You should always embed TrueType fonts. renderer.getFontResolver().addFont(files[0].getAbsolutePath(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED); log.info("Added font: " + files[0].getAbsolutePath()); //Get font family name from the BaseFont object. All this work just to get font family name BaseFont font = BaseFont.createFont(files[0].getAbsolutePath(), BaseFont.IDENTITY_H , BaseFont.NOT_EMBEDDED); fontFamilyName = TrueTypeUtil.getFamilyName(font); if (!fontFamilyName.equals("")) { //Wrap DIV with font family name around the content of the blog entry author = "<div style=\"font-family: " + fontFamilyName + ";\">" + author + "</div>"; title = "<div style=\"font-family: " + fontFamilyName + ";\">" + title + "</div>"; subtitle = "<div style=\"font-family: " + fontFamilyName + ";\">" + subtitle + "</div>"; body = "<div style=\"font-family: " + fontFamilyName + ";\">" + body + "</div>"; log.info("PDFGenerator - Added font family: '" + fontFamilyName + "' to PDF content"); } } } buf.append("<h1>" + title + "</h1>"); buf.append("<h2>" + subtitle + "</h2>"); buf.append("</p>"); buf.append("<p>" + body + "</p>"); buf.append("<p><br /><br /><br />"); buf.append("<i>Published by " + author + "</i><br />"); buf.append("<i>" + entry.getDate().toString() + "</i><br />"); buf.append("<i><a href=\"" + entryPermalink + "\" title=\"" + entryPermalink + "\">" + entryPermalink + "</a></i>"); buf.append("</p>"); buf.append("</body>"); buf.append("</html>"); byte[] bytes = buf.toString().getBytes(DEFAULT_ENCODING); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); InputSource is = new InputSource(bais); Document doc = builder.parse(is); //Listener that will parse HTML header meta tags, and will set them to PDF document as meta data PebblePDFCreationListener pdfListener = new PebblePDFCreationListener(); pdfListener.parseMetaTags(doc); renderer.setListener(pdfListener); renderer.setDocument(doc, null); renderer.layout(); BufferedOutputStream bufferedOutput = new BufferedOutputStream(response.getOutputStream()); renderer.createPDF(bufferedOutput); bufferedOutput.flush(); bufferedOutput.close(); log.info("Successfully generated PDF document: " + filename); } catch (ParserConfigurationException e) { log.error("Could not create PDF, could not get new instance of DocumentBuilder: " + e); } catch (SAXException e) { log.error("Could not create PDF, could not parse InputSource: " + e); } catch (IOException e) { log.error("Could not create PDF: " + e); } catch (DocumentException e) { log.error("iText could not create PDF document: " + e); } catch (Exception e) { log.error("Could not create PDF: " + e); } } }
package org.slf4j.helpers; /** * An internal utility class. * * @author Alexander Dorokhine * @author Ceki G&uuml;lc&uuml; */ public final class Util { private Util() { } public static String safeGetSystemProperty(String key) { if (key == null) throw new IllegalArgumentException("null input"); String result = null; try { result = System.getProperty(key); } catch (java.lang.SecurityException sm) { ; // ignore } return result; } public static boolean safeGetBooleanSystemProperty(String key) { String value = safeGetSystemProperty(key); if (value == null) return false; else return value.equalsIgnoreCase("true"); } /** * In order to call {@link SecurityManager#getClassContext()}, which is a * protected method, we add this wrapper which allows the method to be visible * inside this package. */ private static final class ClassContextSecurityManager extends SecurityManager { protected Class<?>[] getClassContext() { return super.getClassContext(); } } private static ClassContextSecurityManager SECURITY_MANAGER; private static boolean SECURITY_MANAGER_CREATION_ALREADY_ATTEMPTED = false; private static ClassContextSecurityManager getSecurityManager() { if (SECURITY_MANAGER != null) return SECURITY_MANAGER; else if (SECURITY_MANAGER_CREATION_ALREADY_ATTEMPTED) return null; else { SECURITY_MANAGER = safeCreateSecurityManager(); SECURITY_MANAGER_CREATION_ALREADY_ATTEMPTED = true; return SECURITY_MANAGER; } } private static ClassContextSecurityManager safeCreateSecurityManager() { try { return new ClassContextSecurityManager(); } catch (java.lang.SecurityException sm) { return null; } } /** * Returns the name of the class which called the invoking method. * * @return the name of the class which called the invoking method. */ public static Class<?> getCallingClass() { ClassContextSecurityManager securityManager = getSecurityManager(); if (securityManager == null) return null; Class<?>[] trace = securityManager.getClassContext(); String thisClassName = Util.class.getName(); // Advance until Util is found int i; for (i = 0; i < trace.length; i++) { if (thisClassName.equals(trace[i].getName())) break; } // trace[i] = Util; trace[i+1] = caller; trace[i+2] = caller's caller if (i >= trace.length || i + 2 >= trace.length) { throw new IllegalStateException("Failed to find org.slf4j.helpers.Util or its caller in the stack; " + "this should not happen"); } return trace[i + 2]; } static final public void report(String msg, Throwable t) { System.err.println(msg); System.err.println("Reported exception:"); t.printStackTrace(); } static final public void report(String msg) { System.err.println("SLF4J: " + msg); } /** * Helper method to determine if an {@link Object} array contains a {@link Throwable} as last element * * @param argArray * The arguments off which we want to know if it contains a {@link Throwable} as last element * @return if the last {@link Object} in argArray is a {@link Throwable} this method will return it, * otherwise it returns null */ public static Throwable getThrowableCandidate(final Object[] argArray) { if (argArray == null || argArray.length == 0) { return null; } final Object lastEntry = argArray[argArray.length - 1]; if (lastEntry instanceof Throwable) { return (Throwable) lastEntry; } return null; } /** * Helper method to get all but the last element of an array * * @param argArray * The arguments from which we want to remove the last element * * @return a copy of the array without the last element */ public static Object[] trimmedCopy(final Object[] argArray) { if (argArray == null || argArray.length == 0) { throw new IllegalStateException("non-sensical empty or null argument array"); } final int trimmedLen = argArray.length - 1; Object[] trimmed = new Object[trimmedLen]; if (trimmedLen > 0) { System.arraycopy(argArray, 0, trimmed, 0, trimmedLen); } return trimmed; } }
package com.intellij.lang.xml; import com.intellij.codeInsight.folding.CodeFoldingSettings; import com.intellij.lang.ASTNode; import com.intellij.lang.Language; import com.intellij.lang.folding.FoldingBuilder; import com.intellij.lang.folding.FoldingDescriptor; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiWhiteSpace; import com.intellij.psi.tree.TokenSet; import com.intellij.psi.impl.source.jsp.jspXml.JspXmlRootTag; import com.intellij.psi.xml.*; import java.util.ArrayList; import java.util.List; public class XmlFoldingBuilder implements FoldingBuilder { private static final Logger LOG = Logger.getInstance("#com.intellij.lang.xml.XmlFoldingBuilder"); private static TokenSet XML_ATTRIBUTE_SET = TokenSet.create(XmlElementType.XML_ATTRIBUTE); public FoldingDescriptor[] buildFoldRegions(ASTNode node, Document document) { final PsiElement psiElement = node.getPsi(); XmlDocument xmlDocument = null; if (psiElement instanceof XmlFile) { XmlFile file = ((XmlFile)psiElement); xmlDocument = file.getDocument(); } else if (psiElement instanceof XmlDocument) { xmlDocument = (XmlDocument)psiElement; } XmlElement rootTag = xmlDocument == null ? null : xmlDocument.getRootTag(); if (rootTag == null) { rootTag = xmlDocument; } List<FoldingDescriptor> foldings = null; if (rootTag != null) { foldings = new ArrayList<FoldingDescriptor>(); if (rootTag instanceof XmlTag) { addElementsToFold(foldings, rootTag, document); // HTML tags in JSP for(PsiElement sibling = rootTag.getNextSibling(); sibling != null; sibling = sibling.getNextSibling()) { if (sibling instanceof XmlTag) addElementsToFold(foldings, (XmlElement) sibling, document); } } else doAddForChildren(xmlDocument, foldings, document); } return foldings != null ? foldings.toArray(new FoldingDescriptor[foldings.size()]):FoldingDescriptor.EMPTY; } protected void addElementsToFold(List<FoldingDescriptor> foldings, XmlElement tag, Document document) { if (addToFold(foldings, tag, document) || tag instanceof JspXmlRootTag // has no name but has content ) { doAddForChildren(tag, foldings, document); } } private void doAddForChildren(final XmlElement tag, final List<FoldingDescriptor> foldings, final Document document) { final PsiElement[] children = tag.getChildren(); for (PsiElement child : children) { ProgressManager.getInstance().checkCanceled(); if (child instanceof XmlTag || child instanceof XmlConditionalSection ) { addElementsToFold(foldings, (XmlElement)child, document); } else if(child instanceof XmlComment) { addToFold(foldings, (PsiElement)child, document); } else if (child instanceof XmlText) { final PsiElement[] grandChildren = child.getChildren(); for(PsiElement grandChild:grandChildren) { ProgressManager.getInstance().checkCanceled(); if (grandChild instanceof XmlComment) { addToFold(foldings, grandChild, document); } } } else { final Language language = child.getLanguage(); if (!(language instanceof XMLLanguage) && language != Language.ANY) { final FoldingBuilder foldingBuilder = language.getFoldingBuilder(); if (foldingBuilder != null) { final FoldingDescriptor[] foldingDescriptors = foldingBuilder.buildFoldRegions(child.getNode(), document); if (foldingDescriptors != null) { for (FoldingDescriptor descriptor : foldingDescriptors) { foldings.add(descriptor); } } } } } } } public TextRange getRangeToFold(PsiElement element) { if (element instanceof XmlTag) { final ASTNode tagNode = element.getNode(); ASTNode tagNameElement = XmlChildRole.START_TAG_NAME_FINDER.findChild(tagNode); if (tagNameElement == null) return null; int nameEnd = tagNameElement.getTextRange().getEndOffset(); int end = tagNode.getLastChildNode().getTextRange().getStartOffset(); ASTNode[] attributes = tagNode.getChildren(XML_ATTRIBUTE_SET); if (attributes.length > 0) { ASTNode lastAttribute = attributes[attributes.length - 1]; ASTNode lastAttributeBeforeCR = null; for (ASTNode child = tagNode.getFirstChildNode(); child != lastAttribute.getTreeNext(); child = child.getTreeNext()) { if (child.getElementType() == XmlElementType.XML_ATTRIBUTE) { lastAttributeBeforeCR = child; } else if (child.getPsi() instanceof PsiWhiteSpace) { if (child.textContains('\n')) break; } } if (lastAttributeBeforeCR != null) { int attributeEnd = lastAttributeBeforeCR.getTextRange().getEndOffset(); return new TextRange(attributeEnd, end); } } return new TextRange(nameEnd, end); } else if (element instanceof XmlComment) { final XmlComment xmlComment = (XmlComment)element; final TextRange textRange = element.getTextRange(); int commentStartOffset = getCommentStartOffset(xmlComment); int commentEndOffset = getCommentStartEnd(xmlComment); if (textRange.getEndOffset() - textRange.getStartOffset() > commentStartOffset + commentEndOffset) { return new TextRange(textRange.getStartOffset() + commentStartOffset, textRange.getEndOffset() - commentEndOffset); } else { return null; } } else if (element instanceof XmlConditionalSection) { final XmlConditionalSection conditionalSection = (XmlConditionalSection)element; final TextRange textRange = element.getTextRange(); final PsiElement bodyStart = conditionalSection.getBodyStart(); int startOffset = bodyStart != null ? bodyStart.getStartOffsetInParent() : 3; int endOffset = 3; if (textRange.getEndOffset() - textRange.getStartOffset() > startOffset + endOffset) { return new TextRange(textRange.getStartOffset() + startOffset, textRange.getEndOffset() - endOffset); } else { return null; } } else { return null; } } protected int getCommentStartOffset(final XmlComment element) { return 4; } protected int getCommentStartEnd(final XmlComment element) { return 3; } protected boolean addToFold(List<FoldingDescriptor> foldings, PsiElement elementToFold, Document document) { LOG.assertTrue(elementToFold.isValid()); TextRange range = getRangeToFold(elementToFold); if (range == null) return false; if(range.getStartOffset() >= 0 && range.getEndOffset() <= elementToFold.getContainingFile().getTextRange().getEndOffset()) { int startLine = document.getLineNumber(range.getStartOffset()); int endLine = document.getLineNumber(range.getEndOffset() - 1); if (startLine < endLine) { foldings.add(new FoldingDescriptor(elementToFold.getNode(), range)); return true; } } return false; } public String getPlaceholderText(ASTNode node) { final PsiElement psi = node.getPsi(); if (psi instanceof XmlTag || psi instanceof XmlComment || psi instanceof XmlConditionalSection ) return "..."; return null; } public boolean isCollapsedByDefault(ASTNode node) { final PsiElement psi = node.getPsi(); if (psi instanceof XmlTag) { return CodeFoldingSettings.getInstance().isCollapseXmlTags(); } return false; } }
package com.intellij.pom.xml.impl; import com.intellij.lang.ASTNode; import com.intellij.lang.Language; import com.intellij.lang.StdLanguages; import com.intellij.pom.PomModel; import com.intellij.pom.PomModelAspect; import com.intellij.pom.event.PomModelEvent; import com.intellij.pom.tree.TreeAspect; import com.intellij.pom.tree.events.ChangeInfo; import com.intellij.pom.tree.events.ReplaceChangeInfo; import com.intellij.pom.tree.events.TreeChange; import com.intellij.pom.tree.events.TreeChangeEvent; import com.intellij.pom.tree.events.impl.ChangeInfoImpl; import com.intellij.pom.tree.events.impl.TreeChangeImpl; import com.intellij.pom.xml.XmlAspect; import com.intellij.pom.xml.impl.events.*; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiReferenceExpression; import com.intellij.psi.impl.source.tree.FileElement; import com.intellij.psi.xml.*; import com.intellij.util.CharTable; import java.util.Collections; public class XmlAspectImpl implements XmlAspect { private final PomModel myModel; private final TreeAspect myTreeAspect; public XmlAspectImpl(PomModel model, TreeAspect aspect) { myModel = model; myTreeAspect = aspect; myModel.registerAspect(XmlAspect.class, this, Collections.singleton((PomModelAspect)myTreeAspect)); } public void update(PomModelEvent event) { if (!event.getChangedAspects().contains(myTreeAspect)) return; final TreeChangeEvent changeSet = (TreeChangeEvent)event.getChangeSet(myTreeAspect); if (changeSet == null) return; final ASTNode rootElement = changeSet.getRootElement(); final PsiFile file = (PsiFile)rootElement.getPsi(); if (!(file instanceof XmlFile)) return; final XmlAspectChangeSetImpl xmlChangeSet = new XmlAspectChangeSetImpl(myModel, (XmlFile)file); event.registerChangeSet(this, xmlChangeSet); final ASTNode[] changedElements = changeSet.getChangedElements(); final CharTable table = ((FileElement)changeSet.getRootElement()).getCharTable(); for (int i = 0; i < changedElements.length; i++) { ASTNode changedElement = changedElements[i]; TreeChange changesByElement = changeSet.getChangesByElement(changedElement); PsiElement psiElement = null; while (changedElement != null && (psiElement = changedElement.getPsi()) == null) { final ASTNode parent = changedElement.getTreeParent(); final ChangeInfoImpl changeInfo = ChangeInfoImpl.create(ChangeInfo.CONTENTS_CHANGED, changedElement); changeInfo.compactChange(changedElement, changesByElement); changesByElement = new TreeChangeImpl(parent); changesByElement.addChange(changedElement, changeInfo); changedElement = parent; } if(changedElement == null) continue; final TreeChange finalChangedElement = changesByElement; psiElement.accept(new PsiElementVisitor() { TreeChange myChange = finalChangedElement; public void visitReferenceExpression(PsiReferenceExpression expression) { } public void visitElement(PsiElement element) { final Language language = element.getNode().getElementType().getLanguage(); if (language != StdLanguages.XML && language != Language.ANY) return; final ASTNode child = element.getNode(); final ASTNode treeParent = child.getTreeParent(); if (treeParent == null) return; final PsiElement parent = treeParent.getPsi(); final ChangeInfoImpl changeInfo = ChangeInfoImpl.create(ChangeInfo.CONTENTS_CHANGED, child); changeInfo.compactChange(child, myChange); myChange = new TreeChangeImpl(treeParent); myChange.addChange(child, changeInfo); parent.accept(this); } public void visitXmlAttribute(XmlAttribute attribute) { final ASTNode[] affectedChildren = myChange.getAffectedChildren(); String oldName = null; String oldValue = null; for (int j = 0; j < affectedChildren.length; j++) { final ASTNode treeElement = affectedChildren[j]; final ChangeInfo changeByChild = myChange.getChangeByChild(treeElement); final int changeType = changeByChild.getChangeType(); if (treeElement.getElementType() == XmlTokenType.XML_NAME) { if (changeType == ChangeInfo.REMOVED) { oldName = treeElement.getText(); } else if (changeType == ChangeInfo.REPLACE) { oldName = ((ReplaceChangeInfo)changeByChild).getReplaced().getText(); } } if (treeElement.getElementType() == XmlElementType.XML_ATTRIBUTE_VALUE) { if (changeType == ChangeInfo.REMOVED) { oldValue = treeElement.getText(); } else if (changeType == ChangeInfo.REPLACE) { oldValue = ((ReplaceChangeInfo)changeByChild).getReplaced().getText(); } } } if (oldName != null && !oldName.equals(attribute.getName())) { xmlChangeSet.add(new XmlAttributeSetImpl(attribute.getParent(), oldName, null)); xmlChangeSet.add(new XmlAttributeSetImpl(attribute.getParent(), attribute.getName(), attribute.getValue())); } else if (oldValue != null) { xmlChangeSet.add(new XmlAttributeSetImpl(attribute.getParent(), attribute.getName(), attribute.getValue())); } else { xmlChangeSet.add(new XmlElementChangedImpl(attribute)); } } public void visitXmlTag(XmlTag tag) { ASTNode[] affectedChildren = shortenChange(myChange.getAffectedChildren(), changeSet); for (int j = 0; j < affectedChildren.length; j++) { final ASTNode treeElement = affectedChildren[j]; if (!(treeElement instanceof XmlTagChild)) { visitElement(tag); return; } } for (int j = 0; j < affectedChildren.length; j++) { final ChangeInfo changeByChild = myChange.getChangeByChild(affectedChildren[j]); final int changeType = changeByChild.getChangeType(); final ASTNode treeElement = affectedChildren[j]; switch (changeType) { case ChangeInfo.ADD: xmlChangeSet.add(new XmlTagChildAddImpl(tag, (XmlTagChild)treeElement)); break; case ChangeInfo.REMOVED: treeElement.putUserData(CharTable.CHAR_TABLE_KEY, table); xmlChangeSet.add(new XmlTagChildRemovedImpl(tag, (XmlTagChild)treeElement)); break; case ChangeInfo.CONTENTS_CHANGED: xmlChangeSet.add(new XmlTagChildChangedImpl(tag, (XmlTagChild)treeElement)); break; case ChangeInfo.REPLACE: final XmlTagChild replaced = (XmlTagChild)((ReplaceChangeInfo)changeByChild).getReplaced(); replaced.putUserData(CharTable.CHAR_TABLE_KEY, table); xmlChangeSet.add(new XmlTagChildRemovedImpl(tag, replaced)); xmlChangeSet.add(new XmlTagChildAddImpl(tag, (XmlTagChild)treeElement)); break; } } } public void visitXmlDocument(XmlDocument document) { xmlChangeSet.clear(); xmlChangeSet.add(new XmlDocumentChangedImpl(document)); } public void visitFile(PsiFile file) { final XmlDocument document = ((XmlFile)file).getDocument(); if (document != null) { xmlChangeSet.clear(); xmlChangeSet.add(new XmlDocumentChangedImpl(document)); } } }); } } private ASTNode[] shortenChange(ASTNode[] affectedChildren, TreeChangeEvent event) { // TODO return affectedChildren; } public void projectOpened() { } public void projectClosed() { } public void initComponent() { } public void disposeComponent() { } public String getComponentName() { return "XML POM aspect"; } }
package be.ibridge.kettle.core.dialog; import java.util.Hashtable; import java.util.StringTokenizer; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DragSource; import org.eclipse.swt.dnd.DragSourceEvent; import org.eclipse.swt.dnd.DragSourceListener; import org.eclipse.swt.dnd.DropTarget; import org.eclipse.swt.dnd.DropTargetEvent; import org.eclipse.swt.dnd.DropTargetListener; import org.eclipse.swt.dnd.TextTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; 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.Dialog; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.List; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import be.ibridge.kettle.core.Const; import be.ibridge.kettle.core.LogWriter; import be.ibridge.kettle.core.Props; import be.ibridge.kettle.core.WindowProperty; import be.ibridge.kettle.trans.step.BaseStepDialog; import be.ibridge.kettle.trans.step.combinationlookup.Messages; /** * This dialogs allows you to select a number of items from a list of strings. * * @author Matt * @since 21-10-2004 */ public class EnterListDialog extends Dialog { private LogWriter log; private Props props; private String input[]; private String retval[]; private Hashtable selection; private Shell shell; private List wListSource, wListDest; private Label wlListSource, wlListDest; private Button wOK; private Button wCancel; private Button wAddOne, wAddAll, wRemoveAll, wRemoveOne; private boolean opened; /** @deprecated */ public EnterListDialog(Shell parent, int style, LogWriter log, Props props, String input[]) { this(parent, style, input); } public EnterListDialog(Shell parent, int style, String input[]) { super(parent, style); this.log = LogWriter.getInstance(); this.props = Props.getInstance(); this.input = input; this.retval = null; selection = new Hashtable(); opened = false; } public String[] open() { Shell parent = getParent(); shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN); props.setLook(shell); shell.setText("Enter list"); shell.setLayout(new FormLayout()); int margin = Const.MARGIN; // Top & Bottom regions. Composite top = new Composite(shell, SWT.NONE); FormLayout topLayout = new FormLayout(); topLayout.marginHeight = margin; topLayout.marginWidth = margin; top.setLayout(topLayout); FormData fdTop = new FormData(); fdTop.left = new FormAttachment(0, 0); fdTop.top = new FormAttachment(0, 0); fdTop.right = new FormAttachment(100, 0); fdTop.bottom = new FormAttachment(100, -50); top.setLayoutData(fdTop); props.setLook(top); Composite bottom = new Composite(shell, SWT.NONE); bottom.setLayout(new FormLayout()); FormData fdBottom = new FormData(); fdBottom.left = new FormAttachment(0, 0); fdBottom.top = new FormAttachment(top, 0); fdBottom.right = new FormAttachment(100, 0); fdBottom.bottom = new FormAttachment(100, 0); bottom.setLayoutData(fdBottom); props.setLook(bottom); // Sashform SashForm sashform = new SashForm(top, SWT.HORIZONTAL); sashform.setLayout(new FormLayout()); FormData fdSashform = new FormData(); fdSashform.left = new FormAttachment(0, 0); fdSashform.top = new FormAttachment(0, 0); fdSashform.right = new FormAttachment(100, 0); fdSashform.bottom = new FormAttachment(100, 0); sashform.setLayoutData(fdSashform); /// LEFT Composite leftsplit = new Composite(sashform, SWT.NONE); leftsplit.setLayout(new FormLayout()); FormData fdLeftsplit = new FormData(); fdLeftsplit.left = new FormAttachment(0, 0); fdLeftsplit.top = new FormAttachment(0, 0); fdLeftsplit.right = new FormAttachment(100, 0); fdLeftsplit.bottom = new FormAttachment(100, 0); leftsplit.setLayoutData(fdLeftsplit); props.setLook(leftsplit); // Source list to the left... wlListSource = new Label(leftsplit, SWT.NONE); wlListSource.setText("Available items:"); props.setLook(wlListSource); FormData fdlListSource = new FormData(); fdlListSource.left = new FormAttachment(0, 0); fdlListSource.top = new FormAttachment(0, 0); wlListSource.setLayoutData(fdlListSource); wListSource = new List(leftsplit, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL); props.setLook(wListSource); FormData fdListSource = new FormData(); fdListSource.left = new FormAttachment(0, 0); fdListSource.top = new FormAttachment(wlListSource, 0); fdListSource.right = new FormAttachment(100, 0); fdListSource.bottom = new FormAttachment(100, 0); wListSource.setLayoutData(fdListSource); // MIDDLE Composite compmiddle = new Composite(sashform, SWT.NONE); compmiddle.setLayout (new FormLayout()); FormData fdCompMiddle = new FormData(); fdCompMiddle.left = new FormAttachment(0, 0); fdCompMiddle.top = new FormAttachment(0, 0); fdCompMiddle.right = new FormAttachment(100, 0); fdCompMiddle.bottom = new FormAttachment(100, 0); compmiddle.setLayoutData(fdCompMiddle); props.setLook(compmiddle); Composite gButtonGroup = new Composite(compmiddle, SWT.NONE); GridLayout gridLayout = new GridLayout(1, false); gButtonGroup.setLayout(gridLayout); wAddOne = new Button(gButtonGroup, SWT.PUSH); wAddOne .setText(" > "); wAddOne .setToolTipText("Add the selected items on the left."); wAddAll = new Button(gButtonGroup, SWT.PUSH); wAddAll .setText(" >> "); wAddAll .setToolTipText("Add all items on the left."); wRemoveOne = new Button(gButtonGroup, SWT.PUSH); wRemoveOne.setText(" < "); wRemoveOne.setToolTipText("Remove the selected items on the right."); wRemoveAll = new Button(gButtonGroup, SWT.PUSH); wRemoveAll.setText(" << "); wRemoveAll.setToolTipText("Add all items on the right."); GridData gdAddOne = new GridData(GridData.FILL_BOTH); wAddOne.setLayoutData(gdAddOne); GridData gdAddAll = new GridData(GridData.FILL_BOTH); wAddAll.setLayoutData(gdAddAll); GridData gdRemoveAll = new GridData(GridData.FILL_BOTH); wRemoveAll.setLayoutData(gdRemoveAll); GridData gdRemoveOne = new GridData(GridData.FILL_BOTH); wRemoveOne.setLayoutData(gdRemoveOne); FormData fdButtonGroup=new FormData(); wAddAll.pack(); // get a size fdButtonGroup.left = new FormAttachment(50, -(wAddAll.getSize().x/2)-5); fdButtonGroup.top = new FormAttachment(30, 0); gButtonGroup.setBackground(shell.getBackground()); // the default looks ugly gButtonGroup.setLayoutData(fdButtonGroup); // RIGHT Composite rightsplit = new Composite(sashform, SWT.NONE); rightsplit.setLayout(new FormLayout()); FormData fdRightsplit = new FormData(); fdRightsplit .left = new FormAttachment(0, 0); fdRightsplit .top = new FormAttachment(0, 0); fdRightsplit .right = new FormAttachment(100, 0); fdRightsplit .bottom = new FormAttachment(100, 0); rightsplit.setLayoutData(fdRightsplit ); props.setLook(rightsplit); wlListDest = new Label(rightsplit, SWT.NONE); wlListDest.setText("Your selection:"); props.setLook(wlListDest); FormData fdlListDest = new FormData(); fdlListDest.left = new FormAttachment(0, 0); fdlListDest.top = new FormAttachment(0, 0); wlListDest.setLayoutData(fdlListDest); wListDest = new List(rightsplit, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL); props.setLook(wListDest); FormData fdListDest = new FormData(); fdListDest .left = new FormAttachment(0, 0); fdListDest .top = new FormAttachment(wlListDest, 0); fdListDest .right = new FormAttachment(100, 0); fdListDest .bottom = new FormAttachment(100, 0); wListDest.setLayoutData(fdListDest ); sashform.setWeights(new int[] { 40, 16, 40 }); // THE BOTTOM BUTTONS... wOK = new Button(bottom, SWT.PUSH); wOK.setText(" &OK "); wCancel = new Button(bottom, SWT.PUSH); wCancel.setText(" &Cancel "); FormData fdOK = new FormData(); FormData fdCancel = new FormData(); fdOK.left = new FormAttachment(35, 0); fdOK.bottom = new FormAttachment(100, 0); wOK.setLayoutData(fdOK); fdCancel.left = new FormAttachment(wOK, 10); fdCancel.bottom = new FormAttachment(100, 0); wCancel.setLayoutData(fdCancel); // Add listeners wCancel.addListener(SWT.Selection, new Listener () { public void handleEvent (Event e) { log.logDebug(this.getClass().getName(), "CANCEL SelectFieldsDialog"); dispose(); } } ); // Add listeners wOK.addListener(SWT.Selection, new Listener () { public void handleEvent (Event e) { handleOK(); } } ); // Drag & Drop for steps Transfer[] ttypes = new Transfer[] {TextTransfer.getInstance() }; DragSource ddSource = new DragSource(wListSource, DND.DROP_MOVE | DND.DROP_COPY); ddSource.setTransfer(ttypes); ddSource.addDragListener(new DragSourceListener() { public void dragStart(DragSourceEvent event){ } public void dragSetData(DragSourceEvent event) { String ti[] = wListSource.getSelection(); String data = new String(); for (int i=0;i<ti.length;i++) data+=ti[i]+Const.CR; event.data = data; } public void dragFinished(DragSourceEvent event) {} } ); DropTarget ddTarget = new DropTarget(wListDest, DND.DROP_MOVE | DND.DROP_COPY); ddTarget.setTransfer(ttypes); ddTarget.addDropListener(new DropTargetListener() { public void dragEnter(DropTargetEvent event) { } public void dragLeave(DropTargetEvent event) { } public void dragOperationChanged(DropTargetEvent event) { } public void dragOver(DropTargetEvent event) { } public void drop(DropTargetEvent event) { if (event.data == null) { // no data to copy, indicate failure in event.detail event.detail = DND.DROP_NONE; return; } StringTokenizer strtok = new StringTokenizer((String)event.data, Const.CR); while (strtok.hasMoreTokens()) { String source = strtok.nextToken(); addToDestination(source); } } public void dropAccept(DropTargetEvent event) { } }); wListSource.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.character==SWT.CR) { addToSelection(wListSource.getSelection()); } } }); wListDest.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.character==SWT.CR) { delFromSelection(wListDest.getSelection()); } } }); // Double click adds to destination. wListSource.addSelectionListener(new SelectionAdapter() { public void widgetDefaultSelected(SelectionEvent e) { addToSelection(wListSource.getSelection()); } } ); // Double click adds to source wListDest.addSelectionListener(new SelectionAdapter() { public void widgetDefaultSelected(SelectionEvent e) { delFromSelection(wListDest.getSelection()); } } ); wAddOne.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { addToSelection(wListSource.getSelection()); } } ); wRemoveOne.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { delFromSelection(wListDest.getSelection()); } } ); wAddAll.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { addToSelection(wListSource.getItems()); } } ); wRemoveAll.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { delFromSelection(wListDest.getItems()); } } ); opened=true; getData(); BaseStepDialog.setSize(shell); shell.open(); Display display = parent.getDisplay(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } return retval; } public void getData() { if (!opened) return; wListSource.removeAll(); wListDest.removeAll(); for (int i=0;i<input.length;i++) { Integer idx = new Integer(i); String str = (String)selection.get(idx); if (str==null) // Not selected: show in source! { wListSource.add(input[i]); } else // Selected, show in destination! { wListDest.add(input[i]); } } } public void addToSelection(String string[]) { for (int i=0;i<string.length;i++) addToDestination(string[i]); } public void delFromSelection(String string[]) { for (int i=0;i<string.length;i++) delFromDestination(string[i]); } public void addToDestination(String string) { int idxInput = Const.indexOfString(string, input); selection.put(new Integer(idxInput), string); getData(); } public void delFromDestination(String string) { int idxInput = Const.indexOfString(string, input); selection.remove(new Integer(idxInput)); getData(); } public void dispose() { WindowProperty winprop = new WindowProperty(shell); props.setScreen(winprop); shell.dispose(); } public void handleOK() { retval=wListDest.getItems(); dispose(); } public String toString() { return this.getClass().getName(); } }
package be.ibridge.kettle.core.widget; import java.util.ArrayList; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ControlAdapter; import org.eclipse.swt.events.ControlEvent; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseMoveListener; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; import org.eclipse.swt.widgets.ScrollBar; import org.eclipse.swt.widgets.Shell; import org.w3c.dom.Document; import org.w3c.dom.Node; import be.ibridge.kettle.core.Condition; import be.ibridge.kettle.core.Const; import be.ibridge.kettle.core.GUIResource; import be.ibridge.kettle.core.Props; import be.ibridge.kettle.core.Row; import be.ibridge.kettle.core.XMLHandler; import be.ibridge.kettle.core.dialog.EnterSelectionDialog; import be.ibridge.kettle.core.dialog.EnterValueDialog; import be.ibridge.kettle.core.dialog.ErrorDialog; import be.ibridge.kettle.core.exception.KettleXMLException; import be.ibridge.kettle.core.value.Value; /** * Widget that allows you to edit a Condition in a graphical way. * * @author Matt * @since 29-07-2004 * */ public class ConditionEditor extends Composite { private static final String STRING_NOT = "NOT"; private static final String STRING_UP = " ^^ UP ^^ "; private static final int AREA_NONE = 0; private static final int AREA_BACKGROUND = 1; private static final int AREA_NOT = 2; private static final int AREA_CONDITION = 3; private static final int AREA_SUBCONDITION = 4; private static final int AREA_OPERATOR = 5; private static final int AREA_UP = 6; private static final int AREA_LEFT = 7; private static final int AREA_FUNCTION = 8; private static final int AREA_RIGHT_VALUE = 9; private static final int AREA_RIGHT_EXACT = 10; private static final int AREA_ICON_ADD = 11; protected Composite widget; private Shell shell; private Display display; private Condition active_condition; private Props props; private Color bg, white, black, red, green, blue, gray; private Font fixed; private Image imageAdd; private Rectangle size_not, size_widget, size_and_not; private Rectangle size_up; private Rectangle size_left, size_fn, size_rightval, size_rightex; private Rectangle size_cond[]; private Rectangle size_oper[]; private Rectangle size_add; private Rectangle maxdrawn; private int hover_condition; private int hover_operator; private boolean hover_not, hover_up; private boolean hover_left, hover_fn, hover_rightval, hover_rightex; private int previous_area; private int previous_area_nr; private ArrayList parents; private Row fields; private int max_field_length; private ScrollBar sbVertical, sbHorizontal; private int offsetx, offsety; private ArrayList modListeners; private String messageString; public ConditionEditor(Composite composite, int arg1, Condition co, Props pr, Row input_fields) { super(composite, arg1 | SWT.NO_BACKGROUND | SWT.V_SCROLL | SWT.H_SCROLL); widget = this; this.active_condition = co; this.props = pr; this.fields = input_fields; imageAdd = new Image(composite.getDisplay(), getClass().getResourceAsStream(Const.IMAGE_DIRECTORY + "eq_add.png")); addDisposeListener( new DisposeListener() { public void widgetDisposed(DisposeEvent arg0) { imageAdd.dispose(); } } ); modListeners = new ArrayList(); sbVertical = getVerticalBar(); sbHorizontal = getHorizontalBar(); offsetx = 0; offsety = 0; maxdrawn = null; size_not = null; size_widget = null; size_cond = null; previous_area = -1; previous_area_nr = -1; parents = new ArrayList(); // Remember parent in drill-down... hover_condition = -1; hover_operator = -1; hover_not = false; hover_up = false; hover_left = false; hover_fn = false; hover_rightval = false; hover_rightex = false; /* * Determine the maximum field length... */ getMaxFieldLength(); shell = composite.getShell(); display = shell.getDisplay(); bg = GUIResource.getInstance().getColorBackground(); fixed = GUIResource.getInstance().getFontFixed(); white = GUIResource.getInstance().getColorWhite(); black = GUIResource.getInstance().getColorBlack(); red = GUIResource.getInstance().getColorRed(); green = GUIResource.getInstance().getColorGreen(); blue = GUIResource.getInstance().getColorBlue(); gray = GUIResource.getInstance().getColorGray(); widget.addPaintListener(new PaintListener() { public void paintControl(PaintEvent pe) { Rectangle r = widget.getBounds(); if (r.width>0 && r.height>0) { repaint(pe.gc, r.width, r.height); } } }); widget.addMouseMoveListener(new MouseMoveListener() { public void mouseMove(MouseEvent e) { Point screen = new Point(e.x, e.y); int area = getAreaCode(screen); int nr = 0; boolean need_redraw = false; hover_condition = -1; hover_operator = -1; hover_not = false; hover_up = false; hover_left = false; hover_fn = false; hover_rightval = false; hover_rightex = false; if (area!=AREA_ICON_ADD) setToolTipText(null); else setToolTipText("Add condition"); switch(area) { case AREA_NOT : hover_not = true; nr = 1; break; case AREA_UP : hover_up = getLevel()>0; nr = 1; break; case AREA_BACKGROUND : break; case AREA_SUBCONDITION : hover_condition = getNrSubcondition(screen); nr=hover_condition; break; case AREA_OPERATOR : hover_operator = getNrOperator(screen); nr=hover_operator; break; case AREA_LEFT: hover_left = true; nr = 1; break; case AREA_FUNCTION: hover_fn = true; nr = 1; break; case AREA_RIGHT_VALUE: hover_rightval = true; nr = 1; break; case AREA_RIGHT_EXACT: hover_rightex = true; nr = 1; break; case AREA_CONDITION : break; case AREA_NONE : break; } if (area!=previous_area || nr!=previous_area_nr) need_redraw = true; if (need_redraw) { offsetx = -sbHorizontal.getSelection(); offsety = -sbVertical.getSelection(); widget.redraw(); } previous_area = area; previous_area_nr = nr; } }); widget.addMouseListener(new MouseAdapter() { public void mouseDown(MouseEvent e) { Point screen = new Point(e.x, e.y); // Point real = Screen2Real(screen); int area = getAreaCode(screen); if (e.button==1) // Left click on widget... { switch(area) { case AREA_NOT : active_condition.negate(); widget.redraw(); break; case AREA_OPERATOR: { int operator = getNrOperator(screen); EnterSelectionDialog esd = new EnterSelectionDialog(shell, props, Condition.getRealOperators(), "Operator", "Select the operator:"); Condition selcond = active_condition.getCondition(operator); String def = selcond.getOperatorDesc(); int defnr = esd.getSelectionNr(Const.trim(def)); String selection = esd.open(defnr); if (selection!=null) { int opnr = Condition.getOperator(selection); active_condition.getCondition(operator).setOperator(opnr); } widget.redraw(); } break; case AREA_SUBCONDITION: int nr = getNrSubcondition(screen); editCondition(nr); setMessageString("Level="+getLevel()+", Select 'UP' to go up one level"); redraw(); break; case AREA_UP: // Go to the parent condition... goUp(); break; case AREA_FUNCTION: if (active_condition.isAtomic()) { EnterSelectionDialog esd = new EnterSelectionDialog(shell, props, Condition.functions, "Functions", "Select the function:"); String def = active_condition.getFunctionDesc(); int defnr = esd.getSelectionNr(def); String selection = esd.open(defnr); if (selection!=null) { int fnnr = Condition.getFunction(selection); active_condition.setFunction(fnnr); } widget.redraw(); } break; case AREA_LEFT: if (active_condition.isAtomic() && fields!=null) { EnterSelectionDialog esd = new EnterSelectionDialog(shell, props, fields.getFieldNamesAndTypes(max_field_length), "Fields", "Select a field:"); String def = active_condition.getLeftValuename(); int defnr = esd.getSelectionNr(def); String selection = esd.open(defnr); if (selection!=null) { Value v = fields.getValue( esd.getSelectionNr() ); active_condition.setLeftValuename(v.getName()); } widget.redraw(); } break; case AREA_RIGHT_VALUE: if (active_condition.isAtomic() && fields!=null) { EnterSelectionDialog esd = new EnterSelectionDialog(shell, props, fields.getFieldNamesAndTypes(max_field_length), "Fields", "Select a field:"); String def = active_condition.getLeftValuename(); int defnr = esd.getSelectionNr(def); String selection = esd.open(defnr); if (selection!=null) { Value v = fields.getValue( esd.getSelectionNr() ); active_condition.setRightValuename(v.getName()); active_condition.setRightExact(null); } widget.redraw(); } break; case AREA_RIGHT_EXACT: if (active_condition.isAtomic()) { Value v = active_condition.getRightExact(); if (v==null) { Value leftval = fields!=null?fields.searchValue( active_condition.getLeftValuename() ):null; if (leftval!=null) { v=new Value("constant", leftval.getType()); } else { v=new Value("constant", Value.VALUE_TYPE_STRING); } } EnterValueDialog evd = new EnterValueDialog(shell, SWT.NONE, props, v); Value newval = evd.open(); if (newval!=null) { active_condition.setRightValuename(null); active_condition.setRightExact(newval); } widget.redraw(); } break; case AREA_ICON_ADD: addCondition(); break; default: break; } } // Set the pop-up menu if (e.button == 3) { setMenu(area, screen); } } public void mouseUp(MouseEvent e) { } }); sbVertical.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { offsety = -sbVertical.getSelection(); widget.redraw(); } }); sbHorizontal.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { offsetx = -sbHorizontal.getSelection(); widget.redraw(); } }); widget.addControlListener(new ControlAdapter() { public void controlResized(ControlEvent arg0) { size_widget = widget.getBounds(); setBars(); } }); } private void getMaxFieldLength() { max_field_length=5; if (fields!=null) for (int i=0;i<fields.size();i++) { int len = fields.getValue(i).getName().length(); if (len>max_field_length) max_field_length=len; } } public int getLevel() { return parents.size(); } public void goUp() { if (parents.size()>0) { int last = parents.size()-1; active_condition = (Condition)parents.get(last); parents.remove(last); redraw(); } if (getLevel()>0) setMessageString("Level="+getLevel()+", Select 'UP' to go up one level"); else setMessageString("To edit a subcondition, simply click on it"); } private void setMenu(int area, Point screen) { final int cond_nr = getNrSubcondition(screen); switch(area) { case AREA_NOT: { Menu mPop = new Menu(widget); MenuItem miNegate = new MenuItem(mPop, SWT.CASCADE); miNegate.setText("Negate condition"); miNegate.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { active_condition.negate(); widget.redraw(); setModified(); } }); setMenu(mPop); } break; case AREA_BACKGROUND: case AREA_ICON_ADD: { Menu mPop = new Menu(widget); MenuItem miAdd = new MenuItem(mPop, SWT.CASCADE); miAdd.setText("Add condition"); miAdd.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { addCondition(); } }); setMenu(mPop); } break; case AREA_SUBCONDITION: { Menu mPop = new Menu(widget); MenuItem miEdit = new MenuItem(mPop, SWT.CASCADE); miEdit.setText("Edit condition"); miEdit.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { editCondition(cond_nr); setModified(); widget.redraw(); } }); MenuItem miDel = new MenuItem(mPop, SWT.CASCADE); miDel.setText("Delete condition"); miDel.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { removeCondition(cond_nr); setModified(); widget.redraw(); } }); // Add a sub-condition in the subcondition... (move down) final Condition sub = active_condition.getCondition(cond_nr); if (sub.getLeftValuename()!=null) { MenuItem miAdd = new MenuItem(mPop, SWT.CASCADE); miAdd.setText("add sub-condition"); miAdd.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { Condition c = new Condition(); c.setOperator(Condition.OPERATOR_AND); sub.addCondition(c); setModified(); widget.redraw(); } }); } new MenuItem(mPop, SWT.SEPARATOR); MenuItem miCopy = new MenuItem(mPop, SWT.CASCADE); miCopy.setText("Copy to clipboard"); miCopy.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { Condition c = active_condition.getCondition(cond_nr); String xml = c.getXML(); props.toClipboard(xml); widget.redraw(); } }); MenuItem miPasteBef = new MenuItem(mPop, SWT.CASCADE); miPasteBef.setText("Paste from clipboard (before this condition)"); miPasteBef.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { String xml = props.fromClipboard(); try { Document d = XMLHandler.loadXMLString(xml); Node condNode = XMLHandler.getSubNode(d, "condition"); if (condNode!=null) { Condition c = new Condition(condNode); active_condition.addCondition(cond_nr, c); widget.redraw(); } else { new ErrorDialog(shell, props, "Error", "No condition found in the XML", new KettleXMLException("No condition found in XML:"+Const.CR+Const.CR+xml) ); } } catch(KettleXMLException ex) { new ErrorDialog(shell, props, "Error", "Error pasting condition", ex); } } }); new MenuItem(mPop, SWT.SEPARATOR); MenuItem miPasteAft = new MenuItem(mPop, SWT.CASCADE); miPasteAft.setText("Paste from clipboard (after this condition)"); miPasteAft.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { String xml = props.fromClipboard(); try { Document d = XMLHandler.loadXMLString(xml); Node condNode = XMLHandler.getSubNode(d, "condition"); if (condNode!=null) { Condition c = new Condition(condNode); active_condition.addCondition(cond_nr+1, c); widget.redraw(); } else { new ErrorDialog(shell, props, "Error", "No condition found in the XML", new KettleXMLException("No condition found in XML:"+Const.CR+Const.CR+xml) ); } } catch(KettleXMLException ex) { new ErrorDialog(shell, props, "Error", "Error pasting condition", ex); } } }); new MenuItem(mPop, SWT.SEPARATOR); MenuItem miMoveSub = new MenuItem(mPop, SWT.CASCADE); miMoveSub.setText("Move condition to subcondition ( miMoveSub.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { // Move the condition lower: this means create a subcondition and put the condition there in the list. Condition down = active_condition.getCondition(cond_nr); Condition c = new Condition(); c.setOperator(down.getOperator()); down.setOperator(Condition.OPERATOR_NONE); active_condition.setCondition(cond_nr, c); c.addCondition(down); widget.redraw(); } }); MenuItem miMoveParent = new MenuItem(mPop, SWT.CASCADE); miMoveParent.setText("Move condition to parent (< if (getLevel()==0) miMoveParent.setEnabled(false); miMoveParent.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { // Move the condition lower: this means delete the condition from the active_condition. // After that, move it to the parent. Condition up = active_condition.getCondition(cond_nr); active_condition.removeCondition(cond_nr); Condition parent = (Condition) parents.get(getLevel()-1); parent.addCondition(up); // Take a look upward... goUp(); widget.redraw(); } }); new MenuItem(mPop, SWT.SEPARATOR); MenuItem miMoveDown = new MenuItem(mPop, SWT.CASCADE); miMoveDown.setText("Move condition down"); if (cond_nr>=active_condition.nrConditions()-1) miMoveDown.setEnabled(false); miMoveDown.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { Condition down = active_condition.getCondition(cond_nr); active_condition.removeCondition(cond_nr); active_condition.addCondition(cond_nr+1, down); widget.redraw(); } }); MenuItem miMoveUp = new MenuItem(mPop, SWT.CASCADE); miMoveUp.setText("Move condition up"); if (cond_nr==0) miMoveUp.setEnabled(false); miMoveUp.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { Condition up = active_condition.getCondition(cond_nr); active_condition.removeCondition(cond_nr); active_condition.addCondition(cond_nr-1, up); widget.redraw(); } }); setMenu(mPop); } break; case AREA_OPERATOR: { Menu mPop = new Menu(widget); MenuItem miDown = new MenuItem(mPop, SWT.CASCADE); miDown.setText("move down"); miDown.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { // Move a condition down! // oper_nr = 1 : means move down setModified(); widget.redraw(); } }); setMenu(mPop); } break; default: setMenu(null); break; } } public void repaint(GC dgc, int width, int height) { Image im = new Image(display, width, height); GC gc = new GC(im); // Initialize some information size_not = getNotSize(gc); size_widget = getWidgetSize(gc); size_and_not = getAndNotSize(gc); size_up = getUpSize(gc); size_add = getAddSize(gc); size_left = null; size_fn = null; size_rightval= null; size_rightex = null; // Clear the background... gc.setBackground(white); gc.setForeground(black); gc.fillRectangle(0,0,width, height); // Set the fixed font: gc.setFont(fixed); // Atomic condition? if (active_condition.isAtomic()) { size_cond = null; drawNegated(gc, 0, 0, active_condition); drawAtomic(gc, 0, 0, active_condition); // gc.drawText("ATOMIC", 10, size_widget.height-20); } else { drawNegated(gc, 0, 0, active_condition); size_cond = new Rectangle[active_condition.nrConditions()]; size_oper = new Rectangle[active_condition.nrConditions()]; int basex=10; int basey=size_not.y+5; for (int i=0;i<active_condition.nrConditions();i++) { Point to = drawCondition(gc, basex, basey, i, active_condition.getCondition(i)); basey += size_and_not.height + to.y + 15; } } gc.drawImage(imageAdd, size_add.x, size_add.y); /* * Draw the up-symbol if needed... */ if (parents.size()>0) { drawUp(gc); } if (messageString!=null) { drawMessage(gc); } /* * Determine the maximum size of the displayed items... * Normally, they are all size up already. */ getMaxSize(); /* * Set the scroll bars: show/don't show and set the size */ setBars(); // Draw the result on the canvas, all in 1 go. dgc.drawImage(im, 0, 0); im.dispose(); } private Rectangle getNotSize(GC gc) { Point p = gc.textExtent(STRING_NOT); return new Rectangle(0, 0, p.x+10, p.y+4); } private Rectangle getWidgetSize(GC gc) { return widget.getBounds(); } private Rectangle getAndNotSize(GC gc) { Point p = gc.textExtent(Condition.operators[Condition.OPERATOR_AND_NOT]); return new Rectangle(0,0, p.x, p.y); } private Rectangle getUpSize(GC gc) { Point p = gc.textExtent(STRING_UP); return new Rectangle(size_not.x+size_not.width+40, size_not.y, p.x+20, size_not.height); } private Rectangle getAddSize(GC gc) { Rectangle is = imageAdd.getBounds(); // image size Rectangle cs = getBounds(); // Canvas size return new Rectangle(cs.width-is.width-5, 5, is.width, is.height); } private void drawNegated(GC gc, int x, int y, Condition condition) { Color color = gc.getForeground(); if (hover_not) gc.setBackground(gray); gc.fillRectangle(Real2Screen(size_not)); gc.drawRectangle(Real2Screen(size_not)); if (condition.isNegated()) { if (hover_not) gc.setForeground(green); gc.drawText(STRING_NOT, size_not.x+5+offsetx, size_not.y+2+offsety, SWT.DRAW_TRANSPARENT); gc.drawText(STRING_NOT, size_not.x+6+offsetx, size_not.y+2+offsety, SWT.DRAW_TRANSPARENT); if (hover_not) gc.setForeground(color); } else { if (hover_not) { gc.setForeground(red); gc.drawText(STRING_NOT, size_not.x+5+offsetx, size_not.y+2+offsety, SWT.DRAW_TRANSPARENT); gc.drawText(STRING_NOT, size_not.x+6+offsetx, size_not.y+2+offsety, SWT.DRAW_TRANSPARENT); gc.setForeground(color); } } if (hover_not) gc.setBackground(bg); } private void drawAtomic(GC gc, int x, int y, Condition condition) { // First the text sizes... String left = Const.rightPad(condition.getLeftValuename(), max_field_length); Point ext_left = gc.textExtent(left); if (condition.getLeftValuename()==null) ext_left = gc.textExtent("<field>"); String fn_max = Condition.functions[Condition.FUNC_NOT_NULL]; String fn = condition.getFunctionDesc(); Point ext_fn = gc.textExtent(fn_max); String rightval = Const.rightPad(condition.getRightValuename(), max_field_length); Point ext_rval = gc.textExtent(rightval); if (condition.getLeftValuename()==null) ext_rval = gc.textExtent("<field>"); String rightex = condition.getRightExactString(); String rightex_max = rightex; if (rightex == null) { rightex_max = Const.rightPad(" ", 10); } else { if (rightex.length()<10) { rightex_max = Const.rightPad(rightex, 10); } } Point ext_rex = gc.textExtent(rightex_max); size_left = new Rectangle(x+5, y+size_not.height+5, ext_left.x + 5, ext_left.y + 5); size_fn = new Rectangle(size_left.x + size_left.width + 15, y+size_not.height+5, ext_fn.x + 5, ext_fn.y + 5); size_rightval = new Rectangle(size_fn.x + size_fn.width + 15, y+size_not.height+5, ext_rval.x + 5, ext_rval.y + 5); size_rightex = new Rectangle(size_fn.x + size_fn.width + 15, y+size_not.height+5+size_rightval.height+5, ext_rex.x + 5, ext_rex.y + 5); if (hover_left) gc.setBackground(gray); gc.fillRectangle(Real2Screen(size_left)); gc.drawRectangle(Real2Screen(size_left)); gc.setBackground(bg); if (hover_fn) gc.setBackground(gray); gc.fillRectangle(Real2Screen(size_fn)); gc.drawRectangle(Real2Screen(size_fn)); gc.setBackground(bg); if (hover_rightval) gc.setBackground(gray); gc.fillRectangle(Real2Screen(size_rightval)); gc.drawRectangle(Real2Screen(size_rightval)); gc.setBackground(bg); if (hover_rightex) gc.setBackground(gray); gc.fillRectangle(Real2Screen(size_rightex)); gc.drawRectangle(Real2Screen(size_rightex)); gc.setBackground(bg); if (condition.getLeftValuename()!=null) { gc.drawText(left, size_left.x+1+offsetx, size_left.y+1+offsety, SWT.DRAW_TRANSPARENT); } else { gc.setForeground(gray); gc.drawText("<field>", size_left.x+1+offsetx, size_left.y+1+offsety, SWT.DRAW_TRANSPARENT); gc.setForeground(black); } gc.drawText(fn, size_fn.x+1+offsetx, size_fn.y+1+offsety, SWT.DRAW_TRANSPARENT); if (condition.getFunction()!=Condition.FUNC_NOT_NULL && condition.getFunction()!=Condition.FUNC_NULL ) { String re = rightex==null?"":rightex; String stype = ""; Value v = condition.getRightExact(); if (v!=null) stype=" ("+v.getTypeDesc()+")"; if (condition.getRightValuename()!=null) { gc.drawText(rightval, size_rightval.x+1+offsetx, size_rightval.y+1+offsety, SWT.DRAW_TRANSPARENT); } else { String nothing = rightex==null?"<field>":""; gc.setForeground( gray ); gc.drawText(nothing, size_rightval.x+1+offsetx, size_rightval.y+1+offsety, SWT.DRAW_TRANSPARENT); if (condition.getRightValuename()==null) gc.setForeground( black ); } if (rightex!=null) { gc.drawText(re, size_rightex.x+1+offsetx, size_rightex.y+1+offsety, SWT.DRAW_TRANSPARENT); } else { String nothing = condition.getRightValuename()==null?"<value>":""; gc.setForeground(gray); gc.drawText(nothing, size_rightex.x+1+offsetx, size_rightex.y+1+offsety, SWT.DRAW_TRANSPARENT); gc.setForeground(black); } gc.drawText(stype, size_rightex.x+1+size_rightex.width+10+offsetx, size_rightex.y+1+offsety, SWT.DRAW_TRANSPARENT); } else { gc.drawText("-", size_rightval.x+1+offsetx, size_rightval.y+1+offsety, SWT.DRAW_TRANSPARENT); gc.drawText("-", size_rightex.x+1+offsetx, size_rightex.y+1+offsety, SWT.DRAW_TRANSPARENT); } } private Point drawCondition(GC gc, int x, int y, int nr, Condition condition) { int opx, opy, opw, oph; int cx, cy, cw, ch; opx = x; opy = y; opw = size_and_not.width + 6; oph = size_and_not.height + 2; /* * First draw the operator ... */ if (nr>0) { String operator = condition.getOperatorDesc(); // Remember the size of the rectangle! size_oper[nr] = new Rectangle(opx, opy, opw, oph); if (nr==hover_operator) { gc.setBackground(gray); gc.fillRectangle(Real2Screen(size_oper[nr])); gc.drawRectangle(Real2Screen(size_oper[nr])); gc.setBackground(bg); } gc.drawText(operator, size_oper[nr].x+2+offsetx, size_oper[nr].y+2+offsety, SWT.DRAW_TRANSPARENT ); } /* * Then draw the condition below, possibly negated! */ String str = condition.toString(0, true, false); // don't show the operator! Point p = gc.textExtent(str); cx = opx + 23; cy = opy + oph+10; cw = p.x + 5; ch = p.y + 5; // Remember the size of the rectangle! size_cond[nr] = new Rectangle(cx, cy, cw, ch); if (nr==hover_condition) { gc.setBackground(gray); gc.fillRectangle(Real2Screen(size_cond[nr])); gc.drawRectangle(Real2Screen(size_cond[nr])); gc.setBackground(bg); } gc.drawText(str, size_cond[nr].x+2+offsetx, size_cond[nr].y+5+offsety, SWT.DRAW_DELIMITER | SWT.DRAW_TRANSPARENT | SWT.DRAW_TAB | SWT.DRAW_MNEMONIC); p.x+=0; p.y+=5; return p; } public void drawUp(GC gc) { if (hover_up) { gc.setBackground(gray); gc.fillRectangle(size_up); } gc.drawRectangle(size_up); gc.drawText(STRING_UP, size_up.x+1+offsetx, size_up.y+1+offsety, SWT.DRAW_TRANSPARENT ); } public void drawMessage(GC gc) { gc.setForeground(blue); gc.drawText(getMessageString(), size_up.x+size_up.width+offsetx+40, size_up.y+1+offsety, SWT.DRAW_TRANSPARENT); // widget.setToolTipText(getMessageString()); } private boolean isInNot(Point screen) { if (size_not==null) return false; return Real2Screen(size_not).contains(screen); } private boolean isInUp(Point screen) { if (parents.size()==0) return false; // not displayed! return Real2Screen(size_up).contains(screen); } private boolean isInAdd(Point screen) { return size_add.contains(screen); } private boolean isInWidget(Point screen) { return Real2Screen(size_widget).contains(screen); } private int getNrSubcondition(Point screen) { if (size_cond==null) return -1; for (int i=0;i<size_cond.length;i++) { if (size_cond[i]!=null && Screen2Real(size_cond[i]).contains(screen)) { return i; } } return -1; } private boolean isInSubcondition(Point screen) { return getNrSubcondition(screen)>=0; } private int getNrOperator(Point screen) { if (size_oper==null) return -1; for (int i=0;i<size_oper.length;i++) { if (size_oper[i]!=null && Screen2Real(size_oper[i]).contains(screen)) { return i; } } return -1; } private boolean isInOperator(Point screen) { return getNrOperator(screen)>=0; } private boolean isInLeft(Point screen) { if (size_left==null) return false; return Real2Screen(size_left).contains(screen); } private boolean isInFunction(Point screen) { if (size_fn==null) return false; return Real2Screen(size_fn).contains(screen); } private boolean isInRightValue(Point screen) { if (size_rightval==null) return false; return Real2Screen(size_rightval).contains(screen); } private boolean isInRightExact(Point screen) { if (size_rightex==null) return false; return Real2Screen(size_rightex).contains(screen); } private int getAreaCode(Point screen) { if (isInNot(screen)) return AREA_NOT; if (isInUp(screen)) return AREA_UP; if (isInAdd(screen)) return AREA_ICON_ADD; if (active_condition.isAtomic()) { if (isInLeft(screen)) return AREA_LEFT; if (isInFunction(screen)) return AREA_FUNCTION; if (isInRightExact(screen)) return AREA_RIGHT_EXACT; if (isInRightValue(screen)) return AREA_RIGHT_VALUE; } else { if (isInSubcondition(screen)) return AREA_SUBCONDITION; if (isInOperator(screen)) return AREA_OPERATOR; } if (isInWidget(screen)) return AREA_BACKGROUND; return AREA_NONE; } /** * Edit the condition in a separate dialog box... * @param condition The condition to be edited */ private void editCondition(int nr) { if (active_condition.isComposite()) { parents.add(active_condition); active_condition = active_condition.getCondition(nr); } } private void addCondition() { Condition c = new Condition(); c.setOperator(Condition.OPERATOR_AND); addCondition(c); setModified(); widget.redraw(); } /** * Add a sub-condition to the active condition... * @param condition The condition to which we want to add one more. */ private void addCondition(Condition condition) { active_condition.addCondition(condition); } /** * Remove a sub-condition from the active condition... * @param condition The condition to which we want to add one more. */ private void removeCondition(int nr) { active_condition.removeCondition(nr); } /** * @param messageString The messageString to set. */ public void setMessageString(String messageString) { this.messageString = messageString; } /** * @return Returns the messageString. */ public String getMessageString() { return messageString; } private Rectangle Real2Screen(Rectangle r) { return new Rectangle(r.x+offsetx, r.y+offsety, r.width, r.height); } private Rectangle Screen2Real(Rectangle r) { return new Rectangle(r.x-offsetx, r.y-offsety, r.width, r.height); } /** * Determine the maximum rectangle of used canvas space... */ private void getMaxSize() { // Top line... maxdrawn = size_not.union(size_up); // Atomic if ( active_condition.isAtomic() ) { maxdrawn = maxdrawn.union(size_left); maxdrawn = maxdrawn.union(size_fn); maxdrawn = maxdrawn.union(size_rightval); maxdrawn = maxdrawn.union(size_rightex); maxdrawn.width+=100; } else { if (size_cond!=null) for (int i=0;i<size_cond.length;i++) if (size_cond[i]!=null) maxdrawn = maxdrawn.union(size_cond[i]); if (size_oper!=null) for (int i=0;i<size_oper.length;i++) if (size_oper[i]!=null) maxdrawn = maxdrawn.union(size_oper[i]); } maxdrawn.width+=10; maxdrawn.height+=10; } private void setBars() { if (size_widget==null || maxdrawn==null) return; // Horizontal scrollbar behavior if (size_widget.width > maxdrawn.width ) { offsetx=0; sbHorizontal.setSelection(0); sbHorizontal.setVisible(false); } else { offsetx=-sbHorizontal.getSelection(); sbHorizontal.setVisible(true); // Set the bar's parameters... sbHorizontal.setMaximum(maxdrawn.width); sbHorizontal.setMinimum(0); sbHorizontal.setPageIncrement(size_widget.width); sbHorizontal.setIncrement(10); } // Vertical scrollbar behavior if (size_widget.height > maxdrawn.height) { offsety=0; sbVertical.setSelection(0); sbVertical.setVisible(false); } else { offsety=sbVertical.getSelection(); sbVertical.setVisible(true); // Set the bar's parameters... sbVertical.setMaximum(maxdrawn.height); sbVertical.setMinimum(0); sbVertical.setPageIncrement(size_widget.height); sbVertical.setIncrement(10); } } public void addModifyListener(ModifyListener lsMod) { modListeners.add(lsMod); } public void setModified() { for (int i=0;i<modListeners.size();i++) { ModifyListener lsMod = (ModifyListener)modListeners.get(i); if (lsMod!=null) { Event e = new Event(); e.widget=this; lsMod.modifyText(new ModifyEvent(e)); } } } }
package ru.job4j.chess; public class Horse extends Figure { Board board = new Board(); public Horse(Cell cell) { super(cell); } public void initHorse() { Horse horse = new Horse(new Cell(1, 0)); } private Cell[] MoveHorse = new Cell[8]; public void moveHorse(int x, int y) { MoveHorse[0] = new Cell(x - 2, y + 1); MoveHorse[1] = new Cell(x - 2, y - 1); MoveHorse[2] = new Cell(x - 1, y + 2); MoveHorse[3] = new Cell(x + 1, y + 2); MoveHorse[4] = new Cell(x + 2, y + 1); MoveHorse[5] = new Cell(x + 2, y - 1); MoveHorse[6] = new Cell(x + 1, y - 2); MoveHorse[7] = new Cell(x - 1, y - 2); } public void test(Cell dist) { board.figure[1][0] = new Horse(dist); } public void clone(Cell dist) { board.figure[1][0] = new Horse(dist); } public Cell[] way(Cell dist) throws ImposibleMoveException { int x = dist.getX(); int y = dist.getY(); board.alignmentFigures(); moveHorse(board.figure[1][0].position.getX(), board.figure[1][0].position.getY()); if (board.indexOf(dist) == 0) { for (int i = 0; i < 8; i++) { if (x == MoveHorse[i].getX() && y == MoveHorse[i].getY() && MoveHorse[i].getX() > 0 && MoveHorse[i].getY() > 0) { System.out.println("Фигура может пойти в ячейку [" + x + "][" + y + "]"); if (y == board.figure[1][0].position.getY() + 2) { System.out.println("Клетки через которые проходит фигура: [" + board.figure[1][0].position.getX() + "][" + (board.figure[1][0].position.getY() + 1) + "]"); System.out.println("Клетки через которые проходит фигура: [" + board.figure[1][0].position.getX() + "][" + (board.figure[1][0].position.getY() + 2) + "]"); } else if (y == board.figure[1][0].position.getY() - 2) { System.out.println("Клетки через которые проходит фигура: [" + board.figure[1][0].position.getX() + "][" + (board.figure[1][0].position.getY() - 1) + "]"); System.out.println("Клетки через которые проходит фигура: [" + board.figure[1][0].position.getX() + "][" + (board.figure[1][0].position.getY() - 2) + "]"); } else if (x == board.figure[1][0].position.getX() + 2) { System.out.println("Клетки через которые проходит фигура: [" + (board.figure[1][0].position.getX() + 1) + "][" + board.figure[1][0].position.getY() + "]"); System.out.println("Клетки через которые проходит фигура: [" + (board.figure[1][0].position.getX() + 2) + "][" + board.figure[1][0].position.getY() + "]"); } else if (x == board.figure[1][0].position.getX() - 2) { System.out.println("Клетки через которые проходит фигура: [" + (board.figure[1][0].position.getX() - 1) + "][" + board.figure[1][0].position.getY() + "]"); System.out.println("Клетки через которые проходит фигура: [" + (board.figure[1][0].position.getX() - 2) + "][" + board.figure[1][0].position.getY() + "]"); } break; } } } else { System.out.println("Здесь в Horse.java"); throw new ImposibleMoveException("Недопустимый ход [" + x + "][" + y + "]"); } return MoveHorse; } }
package ca.ualberta.cs.lonelytwitter; import java.util.Date; public class LonelyTweetModel { private String text; private Date timestamp; public String getText() { return text; } public LonelyTweetModel(String text) { super(); this.text = text; timestamp = new Date(); } public LonelyTweetModel(String text, Date timestamp) { super(); this.text = text; this.timestamp = timestamp; } public void setText(String text) { this.text = text; } public Date getTimestamp() { return timestamp; } public void setTimestamp(Date timestamp) { this.timestamp = timestamp; } }
package org.boreas.spring.jdbc.dao; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import java.sql.PreparedStatement; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.boreas.spring.jdbc.PageQuery; import org.boreas.spring.jdbc.config.oracle.OracleDaoConfig; import org.boreas.spring.jdbc.config.oracle.OracleNameMapper; import org.boreas.spring.util.StringUtils; import org.springframework.jdbc.core.PreparedStatementCreatorFactory; import org.springframework.jdbc.core.StatementCreatorUtils; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; import org.springframework.util.NumberUtils; /** * Implementation of {@code AbstractDao} for Oracle. Offer some common used * functions for convenience. * * @author boreas * * @param <ID> * type of id which is only a single column primary key. * @param <T> * type of POJO */ public abstract class OracleDao<ID, T> extends AbstractJdbcDao<ID, T> { private List<String> columns; private String sequenceSql; private String batchSequenceSql; private PreparedStatementCreatorFactory insertWithGenerateIdFactory; private String insertWithFilledIdSql; /** * Hold a thread-safe {@code SimpleDateFormat} object. */ private final ThreadLocal<SimpleDateFormat> sdf; public OracleDao() { sdf = new ThreadLocal<SimpleDateFormat>() { @Override protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); } }; } @Resource public final void initWithNameMapper(OracleNameMapper nameMapper) { Assert.notNull(nameMapper, "nameMapper cannot be null."); init(nameMapper); } @Override public void insert(T bean) { Assert.state(columns != null, "must initialize first."); String idColumn = getDaoConfig().getIdColumn(); if (getValue(bean, idColumn) == null) { KeyHolder keyHolder = new GeneratedKeyHolder(); Object[] params = initInsertParameters(bean, true); getJdbcTemplate() .update(insertWithGenerateIdFactory .newPreparedStatementCreator(params), keyHolder); for (String column : keyHolder.getKeys().keySet()) { if (idColumn.equalsIgnoreCase(column)) { Number id = (Number) keyHolder.getKeys().get(column); setAutoGeneratedId(bean, idColumn, id); } } } else getJdbcTemplate().update(insertWithFilledIdSql, initInsertParameters(bean, false)); } @Override public void insert(Collection<T> beans) { if (CollectionUtils.isEmpty(beans)) return; if (beans.size() == 1) { insert(beans.iterator().next()); return; } String idColumn = getDaoConfig().getIdColumn(); List<T> needId = new ArrayList<T>(); for (T bean : beans) { if (getValue(bean, idColumn) == null) needId.add(bean); } Iterator<ID> ids = generateIds(needId.size()).iterator(); for (T bean : needId) { setValue(bean, idColumn, ids.next()); } List<Object[]> batchArgs = new ArrayList<Object[]>(beans.size()); for (T bean : beans) { batchArgs.add(initInsertParameters(bean, false)); } getJdbcTemplate().batchUpdate(insertWithFilledIdSql, batchArgs); } @SuppressWarnings("unchecked") private void setAutoGeneratedId(T bean, String idColumn, Number id) { Method setter = getDescriptors().get(idColumn).getWriteMethod(); Class<?>[] paramTypes = setter.getParameterTypes(); if (paramTypes.length > 0) { Class<? extends Number> idType = (Class<? extends Number>) paramTypes[0]; setValue(bean, idColumn, NumberUtils.convertNumberToTargetClass(id, idType)); } } private Object[] initInsertParameters(T bean, boolean generateId) { Object[] params = new Object[generateId ? columns.size() - 1 : columns .size()]; String idColumn = getDaoConfig().getIdColumn(); for (int i = 0; i < params.length; i++) { String column = columns.get(i); if (!generateId || !idColumn.equals(column)) { Object value = getValue(bean, column); if (value instanceof Date && value != null) params[i] = sdf.get().format(value); else params[i] = value; } } return params; } /** * <p> * Generate a bunch of IDs which are usually used in batch insert for the * reason that {@link PreparedStatement#getGeneratedKeys()} cannot return * more than 1 record with the restriction of socket protocol so that it's * impossible to get the IDs inserted by {@code sequence_name.nextval} * directly. An alternative solution is querying a bunch of IDs from * sequence first, then insert them into table. But these actions are not * atomic. * </p> * <b>Note: </b>If no more rules is in demand, just return * {@link #querySequence(Class, int)}. Otherwise handle the additional * transitions(eg. add a prefix/suffix) in implementation. * * @param n * indicate how many IDs need to generate * @return the list of generated IDs */ protected abstract List<ID> generateIds(int n); /** * Query several values from sequence. * * @param sequencename * @return * @see #generateIds(int) */ protected <N extends Number> List<N> querySequence(Class<N> sequenceType, int n) { Assert.isTrue(n > 0, "The value must be greater than zero"); if (n == 1) { Assert.state(StringUtils.isEmpty(sequenceSql), "sequenceSql must be initialized."); return getJdbcTemplate().queryForList(sequenceSql, sequenceType); } else { Assert.state(StringUtils.isEmpty(batchSequenceSql), "batchSequenceSql must be initialized."); return getJdbcTemplate().queryForList(batchSequenceSql, sequenceType, n); } } private void init(OracleNameMapper nameMapper) { OracleDaoConfig<T> daoConfig = (OracleDaoConfig<T>) config(); Class<T> beanType = daoConfig.getBeanType(); Assert.notNull(beanType, "beanType cannot be null."); String tableName = nameMapper.buildTableName(beanType); daoConfig.setTableName(tableName); String sequenceName = nameMapper.buildSequenceName(beanType) .toUpperCase(); daoConfig.setSequenceName(sequenceName.toUpperCase()); buildSequenceSql(sequenceName); setConfig(daoConfig); buildInsertSql(tableName, daoConfig.getIdColumn(), sequenceName); } /** * Create the SQL strings with the specified sequence name, including a * single value query and a batch query. Cache the generated SQLs. * * @param sequenceName */ private void buildSequenceSql(String sequenceName) { StringBuilder sql = new StringBuilder("select ").append(sequenceName) .append(".nextval from "); sequenceSql = new StringBuilder(sql).append("dual").toString() .toUpperCase(); batchSequenceSql = new StringBuilder(sql) .append("(select level from dual connect by level<=?") .toString().toUpperCase(); } /** * Initialize SQLs, columns and {@code PreparedStatementCreatorFactory} with * the specified table name, id column and sequence name. * * @param tableName * @param idColumn * @param sequenceName */ private void buildInsertSql(String tableName, String idColumn, String sequenceName) { Assert.state(getDescriptors() != null, "Must initialize descriptors."); Map<String, PropertyDescriptor> descriptors = getDescriptors(); StringBuilder insert = new StringBuilder("INSERT INTO ").append( tableName).append(" ("); columns = new ArrayList<String>(descriptors.size()); List<String> values = new ArrayList<String>(descriptors.size()); int[] types = new int[descriptors.size() > 1 ? descriptors.size() - 1 : 0]; int i = 0; Integer indexOfId = null; for (String column : descriptors.keySet()) { Class<?> type = descriptors.get(column).getPropertyType(); columns.add(column); String value; int sqlType; if (Date.class.isAssignableFrom(type)) { value = "to_date(?,'yyyy-MM-dd HH24:mi:ss')"; sqlType = StatementCreatorUtils .javaTypeToSqlParameterType(String.class); } else { value = "?"; sqlType = StatementCreatorUtils .javaTypeToSqlParameterType(type); } if (column.equalsIgnoreCase(idColumn)) indexOfId = columns.size() - 1; else types[i++] = sqlType; values.add(value); } Assert.notNull(indexOfId, idColumn + " is not found in class " + getDaoConfig().getBeanType().getName()); insertWithFilledIdSql = new StringBuilder(insert) .append(StringUtils.combine(",", columns)).append(") values(") .append(StringUtils.combine(",", values)).append(")") .toString().toUpperCase(); values.set(indexOfId, sequenceName + ".nextval"); String insertWithGenerateIdSql = new StringBuilder(insert) .append(StringUtils.combine(",", columns)).append(") values(") .append(StringUtils.combine(",", values)).append(")") .toString().toUpperCase(); insertWithGenerateIdFactory = new PreparedStatementCreatorFactory( insertWithGenerateIdSql, types); insertWithGenerateIdFactory.setReturnGeneratedKeys(true); insertWithGenerateIdFactory .setGeneratedKeysColumnNames(new String[] { idColumn }); } @Override protected String buildPagedSQL(PageQuery pageQuery) { int start = (pageQuery.getPagination() - 1) * pageQuery.getPageSize(); int end = start + pageQuery.getPageSize(); return new StringBuilder("select * from (select t.*,rownum rn from (") .append(pageQuery.getRecordSql()).append(") t) where rn>") .append(start).append(" and rn<=").append(end).toString(); } }
package org.jsimpledb.kv.mvcc; import com.google.common.base.Converter; import com.google.common.base.Preconditions; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Map; import java.util.NavigableMap; import java.util.NavigableSet; import java.util.TreeMap; import org.jsimpledb.kv.KVStore; import org.jsimpledb.kv.KeyRange; import org.jsimpledb.kv.KeyRanges; import org.jsimpledb.kv.util.KeyListEncoder; import org.jsimpledb.util.ByteUtil; import org.jsimpledb.util.ConvertedNavigableMap; import org.jsimpledb.util.ImmutableNavigableMap; import org.jsimpledb.util.LongEncoder; import org.jsimpledb.util.UnsignedIntEncoder; /** * Holds a set of writes to a {@link KVStore}. * * <p> * Each mutation is either a key/value put, the removal of a key range (possibly containing only a single key), * or a counter adjustment. * * <p> * Instances are not thread safe. */ public class Writes implements Cloneable, Mutations { private /*final*/ KeyRanges removes; private /*final*/ NavigableMap<byte[], byte[]> puts; private /*final*/ NavigableMap<byte[], Long> adjusts; private /*final*/ boolean immutable; public Writes() { this(KeyRanges.empty(), new TreeMap<>(ByteUtil.COMPARATOR), new TreeMap<>(ByteUtil.COMPARATOR), false); } private Writes(KeyRanges removes, NavigableMap<byte[], byte[]> puts, NavigableMap<byte[], Long> adjusts, boolean immutable) { this.removes = removes; this.puts = puts; this.adjusts = adjusts; this.immutable = immutable; } // Accessors /** * Get the key ranges removals contained by this instance. * * @return key ranges removed */ public KeyRanges getRemoves() { return this.removes; } /** * Get the written key/value pairs contained by this instance. * * <p> * The caller must not modify any of the returned {@code byte[]} arrays. * * @return mapping from key to corresponding value */ public NavigableMap<byte[], byte[]> getPuts() { return this.puts; } /** * Get the set of counter adjustments contained by this instance. * * <p> * The caller must not modify any of the returned {@code byte[]} arrays. * * @return mapping from key to corresponding counter adjustment */ public NavigableMap<byte[], Long> getAdjusts() { return this.adjusts; } /** * Determine whether this instance is empty, i.e., contains zero mutations. * * @return true if this instance contains zero mutations, otherwise false */ public boolean isEmpty() { return this.removes.isEmpty() && this.puts.isEmpty() && this.adjusts.isEmpty(); } /** * Clear all mutations. */ public void clear() { this.removes.clear(); this.puts.clear(); this.adjusts.clear(); } // Mutations @Override public NavigableSet<KeyRange> getRemoveRanges() { return this.removes.asSet(); } @Override public Iterable<Map.Entry<byte[], byte[]>> getPutPairs() { return this.getPuts().entrySet(); } @Override public Iterable<Map.Entry<byte[], Long>> getAdjustPairs() { return this.getAdjusts().entrySet(); } // Application public void applyTo(KVStore target) { Writes.apply(this, target); } public static void apply(Mutations mutations, KVStore target) { Preconditions.checkArgument(mutations != null, "null mutations"); Preconditions.checkArgument(target != null, "null target"); for (KeyRange remove : mutations.getRemoveRanges()) { final byte[] min = remove.getMin(); final byte[] max = remove.getMax(); assert min != null; if (max != null && ByteUtil.isConsecutive(min, max)) target.remove(min); else target.removeRange(min, max); } for (Map.Entry<byte[], byte[]> entry : mutations.getPutPairs()) target.put(entry.getKey(), entry.getValue()); for (Map.Entry<byte[], Long> entry : mutations.getAdjustPairs()) target.adjustCounter(entry.getKey(), entry.getValue()); } // Serialization /** * Serialize this instance. * * @param out output * @throws IOException if an error occurs */ public void serialize(OutputStream out) throws IOException { // Removes this.removes.serialize(out); // Puts UnsignedIntEncoder.write(out, this.puts.size()); byte[] prev = null; for (Map.Entry<byte[], byte[]> entry : this.puts.entrySet()) { final byte[] key = entry.getKey(); final byte[] value = entry.getValue(); KeyListEncoder.write(out, key, prev); KeyListEncoder.write(out, value, null); prev = key; } // Adjusts UnsignedIntEncoder.write(out, this.adjusts.size()); prev = null; for (Map.Entry<byte[], Long> entry : this.adjusts.entrySet()) { final byte[] key = entry.getKey(); final long value = entry.getValue(); KeyListEncoder.write(out, key, prev); LongEncoder.write(out, value); prev = key; } } /** * Calculate the number of bytes required to serialize this instance via {@link #serialize serialize()}. * * @return number of serialized bytes */ public long serializedLength() { // Removes long total = this.removes.serializedLength(); // Puts total += UnsignedIntEncoder.encodeLength(this.puts.size()); byte[] prev = null; for (Map.Entry<byte[], byte[]> entry : this.puts.entrySet()) { final byte[] key = entry.getKey(); final byte[] value = entry.getValue(); total += KeyListEncoder.writeLength(key, prev); total += KeyListEncoder.writeLength(value, null); prev = key; } // Adjusts total += UnsignedIntEncoder.encodeLength(this.adjusts.size()); prev = null; for (Map.Entry<byte[], Long> entry : this.adjusts.entrySet()) { final byte[] key = entry.getKey(); final long value = entry.getValue(); total += KeyListEncoder.writeLength(key, prev); total += LongEncoder.encodeLength(value); prev = key; } // Done return total; } public static Writes deserialize(InputStream input) throws IOException { return Writes.deserialize(input, false); } public static Writes deserialize(InputStream input, boolean immutable) throws IOException { Preconditions.checkArgument(input != null, "null input"); // Get removes final KeyRanges removes = new KeyRanges(input, immutable); // Get puts final int putCount = UnsignedIntEncoder.read(input); final byte[][] putKeys = new byte[putCount][]; final byte[][] putVals = new byte[putCount][]; byte[] prev = null; for (int i = 0; i < putCount; i++) { putKeys[i] = KeyListEncoder.read(input, prev); putVals[i] = KeyListEncoder.read(input, null); prev = putKeys[i]; } final NavigableMap<byte[], byte[]> puts; if (immutable) puts = new ImmutableNavigableMap<>(putKeys, putVals, ByteUtil.COMPARATOR); else { puts = new TreeMap<>(ByteUtil.COMPARATOR); for (int i = 0; i < putCount; i++) puts.put(putKeys[i], putVals[i]); } // Get adjusts final int adjCount = UnsignedIntEncoder.read(input); final byte[][] adjKeys = new byte[adjCount][]; final Long[] adjVals = new Long[adjCount]; prev = null; for (int i = 0; i < adjCount; i++) { adjKeys[i] = KeyListEncoder.read(input, prev); adjVals[i] = LongEncoder.read(input); prev = adjKeys[i]; } final NavigableMap<byte[], Long> adjusts; if (immutable) adjusts = new ImmutableNavigableMap<>(adjKeys, adjVals, ByteUtil.COMPARATOR); else { adjusts = new TreeMap<>(ByteUtil.COMPARATOR); for (int i = 0; i < adjCount; i++) adjusts.put(adjKeys[i], adjVals[i]); } // Done return new Writes(removes, puts, adjusts, immutable); } // Cloneable /** * Clone this instance. * * <p> * This is a "mostly deep" clone: all of the mutations are copied, but the actual * {@code byte[]} keys and values, which are already assumed non-mutable, are not copied. * * <p> * The returned clone will always be mutable, even if this instance is not. */ @Override @SuppressWarnings("unchecked") public Writes clone() { final Writes clone; try { clone = (Writes)super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } clone.removes = this.removes.clone(); clone.puts = new TreeMap<>(clone.puts); clone.adjusts = new TreeMap<>(clone.adjusts); clone.immutable = false; return clone; } /** * Return an immutable snapshot of this instance. * * @return immutable snapshot */ public Writes immutableSnapshot() { if (this.immutable) return this; return new Writes(this.removes.immutableSnapshot(), new ImmutableNavigableMap<>(this.puts), new ImmutableNavigableMap<>(this.adjusts), true); } // Object @Override public String toString() { final Converter<String, byte[]> byteConverter = ByteUtil.STRING_CONVERTER.reverse(); final ConvertedNavigableMap<String, String, byte[], byte[]> putsView = new ConvertedNavigableMap<>(this.puts, byteConverter, byteConverter); final ConvertedNavigableMap<String, Long, byte[], Long> adjustsView = new ConvertedNavigableMap<>(this.adjusts, byteConverter, Converter.<Long>identity()); final StringBuilder buf = new StringBuilder(); buf.append(this.getClass().getSimpleName()) .append("[removes=") .append(this.removes); if (!this.puts.isEmpty()) { buf.append(",puts="); this.appendEntries(buf, putsView); } if (!this.adjusts.isEmpty()) { buf.append(",adjusts="); this.appendEntries(buf, adjustsView); } buf.append("]"); return buf.toString(); } private void appendEntries(StringBuilder buf, Map<String, ?> map) { buf.append('{'); int index = 0; entryLoop: for (Map.Entry<String, ?> entry : map.entrySet()) { final String key = entry.getKey(); final Object val = entry.getValue(); switch (index++) { case 0: break; case 32: buf.append("..."); break entryLoop; default: buf.append(", "); break; } buf.append(this.truncate(key, 32)) .append('=') .append(this.truncate(String.valueOf(val), 32)); } } private String truncate(String s, int max) { if (s == null || s.length() <= max) return s; return s.substring(0, max) + "..."; } }
package com.fsck.k9.mailstore; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Date; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.annotation.VisibleForTesting; import android.util.Log; import com.fsck.k9.Account; import com.fsck.k9.BuildConfig; import com.fsck.k9.K9; import com.fsck.k9.activity.MessageReference; import com.fsck.k9.mail.Address; import com.fsck.k9.mail.Flag; import com.fsck.k9.mail.Folder; import com.fsck.k9.mail.MessagingException; import com.fsck.k9.mail.internet.MimeMessage; import com.fsck.k9.mail.message.MessageHeaderParser; import com.fsck.k9.mailstore.LockableDatabase.DbCallback; import com.fsck.k9.mailstore.LockableDatabase.WrappedException; import com.fsck.k9.message.extractors.PreviewResult.PreviewType; public class LocalMessage extends MimeMessage { protected MessageReference mReference; private final LocalStore localStore; private long mId; private int mAttachmentCount; private String mSubject; private String mPreview = ""; private long mThreadId; private long mRootId; private long messagePartId; private String mimeType; private PreviewType previewType; private boolean headerNeedsUpdating = false; private LocalMessage(LocalStore localStore) { this.localStore = localStore; } LocalMessage(LocalStore localStore, String uid, Folder folder) { this.localStore = localStore; this.mUid = uid; this.mFolder = folder; } void populateFromGetMessageCursor(Cursor cursor) throws MessagingException { final String subject = cursor.getString(0); this.setSubject(subject == null ? "" : subject); Address[] from = Address.unpack(cursor.getString(1)); if (from.length > 0) { this.setFrom(from[0]); } this.setInternalSentDate(new Date(cursor.getLong(2))); this.setUid(cursor.getString(3)); String flagList = cursor.getString(4); if (flagList != null && flagList.length() > 0) { String[] flags = flagList.split(","); for (String flag : flags) { try { this.setFlagInternal(Flag.valueOf(flag), true); } catch (Exception e) { if (!"X_BAD_FLAG".equals(flag)) { Log.w(K9.LOG_TAG, "Unable to parse flag " + flag); } } } } this.mId = cursor.getLong(5); this.setRecipients(RecipientType.TO, Address.unpack(cursor.getString(6))); this.setRecipients(RecipientType.CC, Address.unpack(cursor.getString(7))); this.setRecipients(RecipientType.BCC, Address.unpack(cursor.getString(8))); this.setReplyTo(Address.unpack(cursor.getString(9))); this.mAttachmentCount = cursor.getInt(10); this.setInternalDate(new Date(cursor.getLong(11))); this.setMessageId(cursor.getString(12)); String previewTypeString = cursor.getString(24); DatabasePreviewType databasePreviewType = DatabasePreviewType.fromDatabaseValue(previewTypeString); previewType = databasePreviewType.getPreviewType(); if (previewType == PreviewType.TEXT) { mPreview = cursor.getString(14); } else { mPreview = ""; } if (this.mFolder == null) { LocalFolder f = new LocalFolder(this.localStore, cursor.getInt(13)); f.open(LocalFolder.OPEN_MODE_RW); this.mFolder = f; } mThreadId = (cursor.isNull(15)) ? -1 : cursor.getLong(15); mRootId = (cursor.isNull(16)) ? -1 : cursor.getLong(16); boolean deleted = (cursor.getInt(17) == 1); boolean read = (cursor.getInt(18) == 1); boolean flagged = (cursor.getInt(19) == 1); boolean answered = (cursor.getInt(20) == 1); boolean forwarded = (cursor.getInt(21) == 1); setFlagInternal(Flag.DELETED, deleted); setFlagInternal(Flag.SEEN, read); setFlagInternal(Flag.FLAGGED, flagged); setFlagInternal(Flag.ANSWERED, answered); setFlagInternal(Flag.FORWARDED, forwarded); setMessagePartId(cursor.getLong(22)); mimeType = cursor.getString(23); byte[] header = cursor.getBlob(25); if (header != null) { MessageHeaderParser.parse(this, new ByteArrayInputStream(header)); } else { Log.d(K9.LOG_TAG, "No headers available for this message!"); } headerNeedsUpdating = false; } @VisibleForTesting void setMessagePartId(long messagePartId) { this.messagePartId = messagePartId; } public long getMessagePartId() { return messagePartId; } @Override public String getMimeType() { return mimeType; } /* Custom version of writeTo that updates the MIME message based on localMessage * changes. */ public PreviewType getPreviewType() { return previewType; } public String getPreview() { return mPreview; } @Override public String getSubject() { return mSubject; } @Override public void setSubject(String subject) { mSubject = subject; headerNeedsUpdating = true; } @Override public void setMessageId(String messageId) { mMessageId = messageId; headerNeedsUpdating = true; } @Override public void setUid(String uid) { super.setUid(uid); this.mReference = null; } @Override public boolean hasAttachments() { return (mAttachmentCount > 0); } public int getAttachmentCount() { return mAttachmentCount; } @Override public void setFrom(Address from) { this.mFrom = new Address[] { from }; headerNeedsUpdating = true; } @Override public void setReplyTo(Address[] replyTo) { if (replyTo == null || replyTo.length == 0) { mReplyTo = null; } else { mReplyTo = replyTo; } headerNeedsUpdating = true; } /* * For performance reasons, we add headers instead of setting them (see super implementation) * which removes (expensive) them before adding them */ @Override public void setRecipients(RecipientType type, Address[] addresses) { if (type == RecipientType.TO) { if (addresses == null || addresses.length == 0) { this.mTo = null; } else { this.mTo = addresses; } } else if (type == RecipientType.CC) { if (addresses == null || addresses.length == 0) { this.mCc = null; } else { this.mCc = addresses; } } else if (type == RecipientType.BCC) { if (addresses == null || addresses.length == 0) { this.mBcc = null; } else { this.mBcc = addresses; } } else { throw new IllegalArgumentException("Unrecognized recipient type."); } headerNeedsUpdating = true; } public void setFlagInternal(Flag flag, boolean set) throws MessagingException { super.setFlag(flag, set); } @Override public long getId() { return mId; } @Override public void setFlag(final Flag flag, final boolean set) throws MessagingException { try { this.localStore.database.execute(true, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { try { if (flag == Flag.DELETED && set) { delete(); } LocalMessage.super.setFlag(flag, set); } catch (MessagingException e) { throw new WrappedException(e); } /* * Set the flags on the message. */ ContentValues cv = new ContentValues(); cv.put("flags", LocalMessage.this.localStore.serializeFlags(getFlags())); cv.put("read", isSet(Flag.SEEN) ? 1 : 0); cv.put("flagged", isSet(Flag.FLAGGED) ? 1 : 0); cv.put("answered", isSet(Flag.ANSWERED) ? 1 : 0); cv.put("forwarded", isSet(Flag.FORWARDED) ? 1 : 0); db.update("messages", cv, "id = ?", new String[] { Long.toString(mId) }); return null; } }); } catch (WrappedException e) { throw(MessagingException) e.getCause(); } this.localStore.notifyChange(); } /* * If a message is being marked as deleted we want to clear out its content. Delete will not actually remove the * row since we need to retain the UID for synchronization purposes. */ private void delete() throws MessagingException { try { localStore.database.execute(true, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { ContentValues cv = new ContentValues(); cv.put("deleted", 1); cv.put("empty", 1); cv.putNull("subject"); cv.putNull("sender_list"); cv.putNull("date"); cv.putNull("to_list"); cv.putNull("cc_list"); cv.putNull("bcc_list"); cv.putNull("preview"); cv.putNull("reply_to_list"); cv.putNull("message_part_id"); db.update("messages", cv, "id = ?", new String[] { Long.toString(mId) }); try { ((LocalFolder) mFolder).deleteMessagePartsAndDataFromDisk(messagePartId); } catch (MessagingException e) { throw new WrappedException(e); } return null; } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } localStore.notifyChange(); } public void debugClearLocalData() throws MessagingException { if (!BuildConfig.DEBUG) { throw new AssertionError("method must only be used in debug build!"); } try { localStore.database.execute(true, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException, MessagingException { ContentValues cv = new ContentValues(); cv.putNull("message_part_id"); db.update("messages", cv, "id = ?", new String[] { Long.toString(mId) }); try { ((LocalFolder) mFolder).deleteMessagePartsAndDataFromDisk(messagePartId); } catch (MessagingException e) { throw new WrappedException(e); } setFlag(Flag.X_DOWNLOADED_FULL, false); setFlag(Flag.X_DOWNLOADED_PARTIAL, false); return null; } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } localStore.notifyChange(); } /* * Completely remove a message from the local database * * TODO: document how this updates the thread structure */ @Override public void destroy() throws MessagingException { try { this.localStore.database.execute(true, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { try { LocalFolder localFolder = (LocalFolder) mFolder; localFolder.deleteMessagePartsAndDataFromDisk(messagePartId); deleteFulltextIndexEntry(db, mId); if (hasThreadChildren(db, mId)) { // This message has children in the thread structure so we need to // make it an empty message. ContentValues cv = new ContentValues(); cv.put("id", mId); cv.put("folder_id", localFolder.getId()); cv.put("deleted", 0); cv.put("message_id", getMessageId()); cv.put("empty", 1); db.replace("messages", null, cv); // Nothing else to do return null; } // Get the message ID of the parent message if it's empty long currentId = getEmptyThreadParent(db, mId); // Delete the placeholder message deleteMessageRow(db, mId); /* * Walk the thread tree to delete all empty parents without children */ while (currentId != -1) { if (hasThreadChildren(db, currentId)) { // We made sure there are no empty leaf nodes and can stop now. break; } // Get ID of the (empty) parent for the next iteration long newId = getEmptyThreadParent(db, currentId); // Delete the empty message deleteMessageRow(db, currentId); currentId = newId; } } catch (MessagingException e) { throw new WrappedException(e); } return null; } }); } catch (WrappedException e) { throw(MessagingException) e.getCause(); } this.localStore.notifyChange(); } /** * Get ID of the the given message's parent if the parent is an empty message. * * @param db * {@link SQLiteDatabase} instance to access the database. * @param messageId * The database ID of the message to get the parent for. * * @return Message ID of the parent message if there exists a parent and it is empty. * Otherwise {@code -1}. */ private long getEmptyThreadParent(SQLiteDatabase db, long messageId) { Cursor cursor = db.rawQuery( "SELECT m.id " + "FROM threads t1 " + "JOIN threads t2 ON (t1.parent = t2.id) " + "LEFT JOIN messages m ON (t2.message_id = m.id) " + "WHERE t1.message_id = ? AND m.empty = 1", new String[] { Long.toString(messageId) }); try { return (cursor.moveToFirst() && !cursor.isNull(0)) ? cursor.getLong(0) : -1; } finally { cursor.close(); } } /** * Check whether or not a message has child messages in the thread structure. * * @param db * {@link SQLiteDatabase} instance to access the database. * @param messageId * The database ID of the message to get the children for. * * @return {@code true} if the message has children. {@code false} otherwise. */ private boolean hasThreadChildren(SQLiteDatabase db, long messageId) { Cursor cursor = db.rawQuery( "SELECT COUNT(t2.id) " + "FROM threads t1 " + "JOIN threads t2 ON (t2.parent = t1.id) " + "WHERE t1.message_id = ?", new String[] { Long.toString(messageId) }); try { return (cursor.moveToFirst() && !cursor.isNull(0) && cursor.getLong(0) > 0L); } finally { cursor.close(); } } private void deleteFulltextIndexEntry(SQLiteDatabase db, long messageId) { String[] idArg = { Long.toString(messageId) }; db.delete("messages_fulltext", "docid = ?", idArg); } /** * Delete a message from the 'messages' and 'threads' tables. * * @param db * {@link SQLiteDatabase} instance to access the database. * @param messageId * The database ID of the message to delete. */ private void deleteMessageRow(SQLiteDatabase db, long messageId) { String[] idArg = { Long.toString(messageId) }; // Delete the message db.delete("messages", "id = ?", idArg); // Delete row in 'threads' table // TODO: create trigger for 'messages' table to get rid of the row in 'threads' table db.delete("threads", "message_id = ?", idArg); } @Override public LocalMessage clone() { LocalMessage message = new LocalMessage(localStore); super.copy(message); message.mReference = mReference; message.mId = mId; message.mAttachmentCount = mAttachmentCount; message.mSubject = mSubject; message.mPreview = mPreview; message.mThreadId = mThreadId; message.mRootId = mRootId; message.messagePartId = messagePartId; message.mimeType = mimeType; message.previewType = previewType; message.headerNeedsUpdating = headerNeedsUpdating; return message; } public long getThreadId() { return mThreadId; } public long getRootId() { return mRootId; } public Account getAccount() { return localStore.getAccount(); } public MessageReference makeMessageReference() { if (mReference == null) { mReference = new MessageReference(getFolder().getAccountUuid(), getFolder().getName(), mUid, null); } return mReference; } @Override public LocalFolder getFolder() { return (LocalFolder) super.getFolder(); } public String getUri() { return "email://messages/" + getAccount().getAccountNumber() + "/" + getFolder().getName() + "/" + getUid(); } @Override public void writeTo(OutputStream out) throws IOException, MessagingException { if (headerNeedsUpdating) { updateHeader(); } super.writeTo(out); } private void updateHeader() { super.setSubject(mSubject); super.setReplyTo(mReplyTo); super.setRecipients(RecipientType.TO, mTo); super.setRecipients(RecipientType.CC, mCc); super.setRecipients(RecipientType.BCC, mBcc); if (mFrom != null && mFrom.length > 0) { super.setFrom(mFrom[0]); } if (mMessageId != null) { super.setMessageId(mMessageId); } headerNeedsUpdating = false; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } // distinguish by account uuid, in addition to what Message.equals() does above String thisAccountUuid = getAccountUuid(); String thatAccountUuid = ((LocalMessage) o).getAccountUuid(); return thisAccountUuid != null ? thisAccountUuid.equals(thatAccountUuid) : thatAccountUuid == null; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (getAccountUuid() != null ? getAccountUuid().hashCode() : 0); return result; } private String getAccountUuid() { return getAccount().getUuid(); } public boolean isBodyMissing() { return getBody() == null; } }
package opendap.bes.dapResponders; import opendap.bes.BESDataSource; import opendap.bes.BesDapResponder; import opendap.coreServlet.*; import opendap.dap.DapResponder; import org.jdom.Element; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Date; import java.util.Vector; public class DapDispatcher implements DispatchHandler { private Logger log; private boolean initialized; private HttpServlet dispatchServlet; private String systemPath; private Element _config; private Vector<DapResponder> responders; private static boolean _allowDirectDataSourceAccess = false; private static boolean _useDAP2ResourceUrlResponse = false; private BesApi _besApi; public DapDispatcher(){ log = LoggerFactory.getLogger(getClass()); responders = new Vector<DapResponder>(); } public static boolean allowDirectDataSourceAccess(){ return _allowDirectDataSourceAccess; } public static boolean useDAP2ResourceUrlResponse(){ return _useDAP2ResourceUrlResponse; } protected Vector<DapResponder> getResponders(){ return responders; } protected void addResponder(DapResponder r){ responders.add(r); } public Element getConfig(){ return _config; } public void init(HttpServlet servlet,Element config) throws Exception { BesApi besApi = new BesApi(); init(servlet, config, besApi); } protected void init(HttpServlet servlet, Element config, BesApi besApi) throws Exception { if(initialized) return; _besApi = besApi; _config = config; Element besApiImpl = _config.getChild("BesApiImpl"); if(besApiImpl!=null){ String className = besApiImpl.getTextTrim(); log.debug("Building BesApi: " + className); Class classDefinition = Class.forName(className); Object classInstance = classDefinition.newInstance(); if(classInstance instanceof BesApi){ log.debug("Loading BesApi from configuration."); besApi = (BesApi) classDefinition.newInstance(); } } log.debug("Using BesApi implementation: {}",besApi.getClass().getName()); _allowDirectDataSourceAccess = false; Element dv = config.getChild("AllowDirectDataSourceAccess"); if(dv!=null){ _allowDirectDataSourceAccess = true; } _useDAP2ResourceUrlResponse = false; dv = config.getChild("UseDAP2ResourceUrlResponse"); if(dv!=null){ _useDAP2ResourceUrlResponse = true; } dispatchServlet = servlet; systemPath = ServletUtil.getSystemPath(dispatchServlet,""); BesDapResponder hr; responders.add(new HtmlDataRequestForm(systemPath, besApi)); responders.add(new Dataset(systemPath, besApi)); responders.add(new DataDDX(systemPath, besApi)); responders.add(new Dap2Data(systemPath, besApi)); responders.add(new Ascii(systemPath, besApi)); responders.add(new NetcdfFileOut(systemPath, besApi)); responders.add(new XmlData(systemPath, besApi)); hr = new DDX(systemPath,besApi); responders.add(hr); responders.add(new DDS(systemPath, besApi)); responders.add(new DAS(systemPath, besApi)); responders.add(new RDF(systemPath, besApi)); responders.add(new DatasetInfoHtmlPage(systemPath, besApi)); responders.add(new VersionResponse(systemPath, besApi)); responders.add(new IsoMetadata(systemPath, besApi)); responders.add(new IsoRubric(systemPath, besApi)); if(_useDAP2ResourceUrlResponse){ DatasetFileAccess dfa = new DatasetFileAccess(systemPath, besApi); dfa.setRequestMatchRegex(".*");// The match anything regex. dfa.setAllowDirectDataSourceAccess(_allowDirectDataSourceAccess); dfa.setDap2Response(true); responders.add(dfa); } else { DatasetFileAccess dfa = new DatasetFileAccess(systemPath, besApi); dfa.setAllowDirectDataSourceAccess(_allowDirectDataSourceAccess); responders.add(dfa); DatasetServices sd = new DatasetServices(systemPath, besApi); responders.add(sd); sd.setDapResponders(responders); } log.info("Initialized. Direct Data Source Access: " + (_allowDirectDataSourceAccess ?"Enabled":"Disabled")+" "+ "Resource URL returns: " + (_useDAP2ResourceUrlResponse ?"DAP2 File Response":"DAP4 Service Description")); initialized = true; } public boolean requestCanBeHandled(HttpServletRequest request) throws Exception { if(requestDispatch(request,null,false)) { log.debug("Request can be handled."); return true; } log.debug("Request can not be handled."); return false; } public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { if(!requestDispatch(request,response,true)){ log.error("Unable to service request."); } } public boolean requestDispatch(HttpServletRequest request, HttpServletResponse response, boolean sendResponse) throws Exception { String relativeUrl = ReqInfo.getLocalUrl(request); String besDataSourceId = ReqInfo.getBesDataSourceID(relativeUrl); log.debug("The client requested this BES DataSource: " + besDataSourceId); for (HttpResponder r : responders) { //log.debug(r.getClass().getSimpleName()+ ".getPathPrefix(): "+r.getPathPrefix()); if (r.matches(relativeUrl)) { log.info("The relative URL: " + relativeUrl + " matches " + "the pattern: \"" + r.getRequestMatchRegexString() + "\""); if(sendResponse) r.respondToHttpGetRequest(request, response); return true; } } return false; } public boolean requestDispatch_OLD(HttpServletRequest request, HttpServletResponse response, boolean sendResponse) throws Exception { String relativeUrl = ReqInfo.getLocalUrl(request); String besDataSourceId = ReqInfo.getBesDataSourceID(relativeUrl); DataSourceInfo dsi; log.debug("The client requested this BES DataSource: " + besDataSourceId); for (HttpResponder r : responders) { log.debug(r.getPathPrefix()); if (r.matches(relativeUrl)) { log.info("The relative URL: " + relativeUrl + " matches " + "the pattern: \"" + r.getRequestMatchRegexString() + "\""); dsi = getDataSourceInfo(besDataSourceId); if(dsi.isDataset()){ if(sendResponse) r.respondToHttpGetRequest(request, response); return true; } } } return false; } public long getLastModified(HttpServletRequest req) { String relativeUrl = ReqInfo.getLocalUrl(req); String dataSource = ReqInfo.getBesDataSourceID(relativeUrl); if(!initialized) return -1; log.debug("getLastModified(): Tomcat requesting getlastModified() " + "for collection: " + dataSource ); for (HttpResponder r : responders) { if (r.matches(relativeUrl)) { log.info("The relative URL: " + relativeUrl + " matches " + "the pattern: \"" + r.getRequestMatchRegexString() + "\""); try { log.debug("getLastModified(): Getting datasource info for "+dataSource); DataSourceInfo dsi = getDataSourceInfo(dataSource); log.debug("getLastModified(): Returning: " + new Date(dsi.lastModified())); return dsi.lastModified(); } catch (Exception e) { log.debug("getLastModified(): Returning: -1"); return -1; } } } return -1; } public DataSourceInfo getDataSourceInfo(String dataSourceName) throws Exception { return new BESDataSource(dataSourceName,_besApi); } public void destroy() { log.info("Destroy complete."); } }
package org._3pq.jgrapht.ext; import java.awt.Color; import java.awt.Font; import java.awt.geom.Rectangle2D; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.swing.BorderFactory; import org._3pq.jgrapht.DirectedGraph; import org._3pq.jgrapht.EdgeFactory; import org._3pq.jgrapht.Graph; import org._3pq.jgrapht.ListenableGraph; import org._3pq.jgrapht.event.GraphEdgeChangeEvent; import org._3pq.jgrapht.event.GraphListener; import org._3pq.jgrapht.event.GraphVertexChangeEvent; import org.jgraph.event.GraphModelEvent; import org.jgraph.event.GraphModelEvent.GraphModelChange; import org.jgraph.event.GraphModelListener; import org.jgraph.graph.AttributeMap; import org.jgraph.graph.ConnectionSet; import org.jgraph.graph.DefaultEdge; import org.jgraph.graph.DefaultGraphCell; import org.jgraph.graph.DefaultGraphModel; import org.jgraph.graph.DefaultPort; import org.jgraph.graph.GraphCell; import org.jgraph.graph.GraphConstants; import org.jgraph.graph.Port; /* * FUTURE WORK: Now that the adapter supports JGraph dangling edges, it is * possible, with a little effort, to eliminate the "known bugs" above. Some * todo and fixme marks in the code indicate where the possible imporovements * could be made to realize that. */ public class JGraphModelAdapter extends DefaultGraphModel { private static final long serialVersionUID = 3256722883706302515L; /** * The following m_(jCells|jtElement)Being(Added|Removed) sets are used to * prevent bouncing of events between the JGraph and JGraphT listeners. They * ensure that their respective add/remove operations are done exactly once. * Here is an example of how m_jCellsBeingAdded is used when an edge is * added to a JGraph graph: * * <pre> 1. First, we add the desired edge to m_jCellsBeingAdded to indicate that the edge is being inserted internally. 2. Then we invoke the JGraph 'insert' operation. 3. The JGraph listener will detect the newly inserted edge. 4. It checks if the edge is contained in m_jCellsBeingAdded. 5. If yes, it just removes it and does nothing else. if no, it knows that the edge was inserted externally and performs the insertion. 6. Lastly, we remove the edge from the m_jCellsBeingAdded. * </pre> * * <p>Step 6 is not always required but we do it anyway as a safeguard * against the rare case where the edge to be added is already contained in * the graph and thus NO event will be fired. If 6 is not done, a junk edge * will remain in the m_jCellsBeingAdded set.</p> * * <p>The other sets are used in a similar manner to the above. Apparently, * All that complication could be eliminated if JGraph and JGraphT had both * allowed operations that do not inform listeners...</p> */ final Set m_jCellsBeingAdded = new HashSet(); /** * @see #m_jCellsBeingAdded */ final Set m_jCellsBeingRemoved = new HashSet(); /** * @see #m_jCellsBeingAdded */ final Set m_jtElementsBeingAdded = new HashSet(); /** * @see #m_jCellsBeingAdded */ final Set m_jtElementsBeingRemoved = new HashSet(); private final CellFactory m_cellFactory; /** Maps JGraph edges to JGraphT edges */ private final Map m_cellToEdge = new HashMap(); /** Maps JGraph vertices to JGraphT vertices */ private final Map m_cellToVertex = new HashMap(); private final AttributeMap m_defaultEdgeAttributes; private final AttributeMap m_defaultVertexAttributes; /** Maps JGraphT edges to JGraph edges */ private final Map m_edgeToCell = new HashMap(); private final ShieldedGraph m_jtGraph; /** Maps JGraphT vertices to JGraph vertices */ private final Map m_vertexToCell = new HashMap(); /** * Constructs a new JGraph model adapter for the specified JGraphT graph. * * @param jGraphTGraph the JGraphT graph for which JGraph model adapter to * be created. <code>null</code> is NOT permitted. */ public JGraphModelAdapter( Graph jGraphTGraph ) { this( jGraphTGraph, createDefaultVertexAttributes(), createDefaultEdgeAttributes( jGraphTGraph ) ); } /** * Constructs a new JGraph model adapter for the specified JGraphT graph. * * @param jGraphTGraph the JGraphT graph for which JGraph model adapter to * be created. <code>null</code> is NOT permitted. * @param defaultVertexAttributes a default map of JGraph attributes to * format vertices. <code>null</code> is NOT * permitted. * @param defaultEdgeAttributes a default map of JGraph attributes to format * edges. <code>null</code> is NOT permitted. */ public JGraphModelAdapter( Graph jGraphTGraph, AttributeMap defaultVertexAttributes, AttributeMap defaultEdgeAttributes ) { this( jGraphTGraph, defaultVertexAttributes, defaultEdgeAttributes, new DefaultCellFactory() ); } public JGraphModelAdapter( Graph jGraphTGraph, AttributeMap defaultVertexAttributes, AttributeMap defaultEdgeAttributes, CellFactory cellFactory ) { super(); if( jGraphTGraph == null || defaultVertexAttributes == null || defaultEdgeAttributes == null || cellFactory == null ) { throw new IllegalArgumentException( "null is NOT permitted" ); } m_jtGraph = new ShieldedGraph( jGraphTGraph ); m_defaultVertexAttributes = defaultVertexAttributes; m_defaultEdgeAttributes = defaultEdgeAttributes; m_cellFactory = cellFactory; if( jGraphTGraph instanceof ListenableGraph ) { ListenableGraph g = ( ListenableGraph )jGraphTGraph; g.addGraphListener( new JGraphTListener() ); } this.addGraphModelListener( new JGraphListener() ); for( Iterator i = jGraphTGraph.vertexSet().iterator(); i.hasNext(); ) { handleJGraphTAddedVertex( i.next() ); } for( Iterator i = jGraphTGraph.edgeSet().iterator(); i.hasNext(); ) { handleJGraphTAddedEdge( ( org._3pq.jgrapht.Edge )i.next() ); } } /** * Creates and returns a map of attributes to be used as defaults for edge * attributes, depending on the specified graph. * * @param jGraphTGraph the graph for which default edge attributes to be * created. * * @return a map of attributes to be used as default for edge attributes. */ public static AttributeMap createDefaultEdgeAttributes( Graph jGraphTGraph ) { AttributeMap map = new AttributeMap(); if( jGraphTGraph instanceof DirectedGraph ) { GraphConstants.setLineEnd( map, GraphConstants.ARROW_TECHNICAL ); GraphConstants.setEndFill( map, true ); GraphConstants.setEndSize( map, 10 ); } GraphConstants.setForeground( map, Color.decode( "#25507C" ) ); GraphConstants.setFont( map, GraphConstants.DEFAULTFONT.deriveFont( Font.BOLD, 12 ) ); GraphConstants.setLineColor( map, Color.decode( "#7AA1E6" ) ); return map; } /** * Creates and returns a map of attributes to be used as defaults for vertex * attributes. * * @return a map of attributes to be used as defaults for vertex attributes. */ public static AttributeMap createDefaultVertexAttributes() { AttributeMap map = new AttributeMap(); Color c = Color.decode( "#FF9900" ); GraphConstants.setBounds( map, new Rectangle2D.Double( 50, 50, 90, 30 ) ); GraphConstants.setBorder( map, BorderFactory.createRaisedBevelBorder() ); GraphConstants.setBackground( map, c ); GraphConstants.setForeground( map, Color.white ); GraphConstants.setFont( map, GraphConstants.DEFAULTFONT.deriveFont( Font.BOLD, 12 ) ); GraphConstants.setOpaque( map, true ); return map; } /** * Applies the specified attributes to the model, as in the * {@link DefaultGraphModel#edit(java.util.Map, org.jgraph.graph.ConnectionSet, org.jgraph.graph.ParentMap, javax.swing.undo.UndoableEdit[])} * method. * * @param attrs the attributes to be applied to the model. * * @deprecated this method will be deleted in the future. Use * DefaultGraphModel#edit instead. */ public void edit( Map attrs ) { edit( attrs, null, null, null ); } /** * Returns the cell factory used to create the JGraph cells. * * @return the cell factory used to create the JGraph cells. */ public CellFactory getCellFactory() { return m_cellFactory; } /** * Returns the JGraph edge cell that corresponds to the specified JGraphT * edge. If no corresponding cell found, returns <code>null</code>. * * @param jGraphTEdge a JGraphT edge of the JGraphT graph. * * @return the JGraph edge cell that corresponds to the specified JGraphT * edge, or <code>null</code> if no corresponding cell found. */ public DefaultEdge getEdgeCell( org._3pq.jgrapht.Edge jGraphTEdge ) { return ( DefaultEdge )m_edgeToCell.get( jGraphTEdge ); } /** * Returns the JGraph vertex cell that corresponds to the specified JGraphT * vertex. If no corresponding cell found, returns <code>null</code>. * * @param jGraphTVertex a JGraphT vertex of the JGraphT graph. * * @return the JGraph vertex cell that corresponds to the specified JGraphT * vertex, or <code>null</code> if no corresponding cell found. */ public DefaultGraphCell getVertexCell( Object jGraphTVertex ) { return ( DefaultGraphCell )m_vertexToCell.get( jGraphTVertex ); } /** * Returns the JGraph port cell that corresponds to the specified JGraphT * vertex. If no corresponding port found, returns <code>null</code>. * * @param jGraphTVertex a JGraphT vertex of the JGraphT graph. * * @return the JGraph port cell that corresponds to the specified JGraphT * vertex, or <code>null</code> if no corresponding cell found. */ public DefaultPort getVertexPort( Object jGraphTVertex ) { DefaultGraphCell vertexCell = getVertexCell( jGraphTVertex ); if( vertexCell == null ) { return null; } else { return ( DefaultPort )vertexCell.getChildAt( 0 ); } } /** * Adds/removes an edge to/from the underlying JGraphT graph according to * the change in the specified JGraph edge. If both vertices are connected, * we ensure to have a corresponding JGraphT edge. Otherwise, we ensure NOT * to have a corresponding JGraphT edge. * * <p>This method is to be called only for edges that have already been * changed in the JGraph graph.</p> * * @param jEdge the JGraph edge that has changed. */ void handleJGraphChangedEdge( org.jgraph.graph.Edge jEdge ) { if( isDangling( jEdge ) ) { if( m_cellToEdge.containsKey( jEdge ) ) { // a non-dangling edge became dangling -- remove the JGraphT // edge by faking as if the edge is removed from the JGraph. // TODO: Consider keeping the JGraphT edges outside the graph // to avoid loosing user data, such as weights. handleJGraphRemovedEdge( jEdge ); } else { // a dangling edge is still dangling -- just ignore. } } else { // edge is not dangling if( m_cellToEdge.containsKey( jEdge ) ) { // edge already has a corresponding JGraphT edge. // check if any change to its endpoints. org._3pq.jgrapht.Edge jtEdge = ( org._3pq.jgrapht.Edge )m_cellToEdge.get( jEdge ); Object jSource = getSourceVertex( this, jEdge ); Object jTarget = getTargetVertex( this, jEdge ); Object jtSource = m_cellToVertex.get( jSource ); Object jtTarget = m_cellToVertex.get( jTarget ); if( jtEdge.getSource() == jtSource && jtEdge.getTarget() == jtTarget ) { // no change in edge's endpoints -- nothing to do. } else { // edge's end-points have changed -- need to refresh the // JGraphT edge. Refresh by faking as if the edge has been // removed from JGraph and then added again. // ALSO HERE: consider an alternative that maintains user data handleJGraphRemovedEdge( jEdge ); handleJGraphInsertedEdge( jEdge ); } } else { // a new edge handleJGraphInsertedEdge( jEdge ); } } } /** * Adds to the underlying JGraphT graph an edge that corresponds to the * specified JGraph edge. If the specified JGraph edge is a dangling edge, * it is NOT added to the underlying JGraphT graph. * * <p>This method is to be called only for edges that have already been * added to the JGraph graph.</p> * * @param jEdge the JGraph edge that has been added. */ void handleJGraphInsertedEdge( org.jgraph.graph.Edge jEdge ) { if( isDangling( jEdge ) ) { // JGraphT forbid dangling edges so we cannot add the edge yet. // If later the edge becomes connected, we will add it. } else { Object jSource = getSourceVertex( this, jEdge ); Object jTarget = getTargetVertex( this, jEdge ); Object jtSource = m_cellToVertex.get( jSource ); Object jtTarget = m_cellToVertex.get( jTarget ); org._3pq.jgrapht.Edge jtEdge = m_jtGraph.getEdgeFactory().createEdge( jtSource, jtTarget ); boolean added = m_jtGraph.addEdge( jtEdge ); if( added ) { m_cellToEdge.put( jEdge, jtEdge ); m_edgeToCell.put( jtEdge, jEdge ); } else { // Adding failed because user is using a JGraphT graph the // forbids parallel edges. // For consistency, we remove the edge from the JGraph too. internalRemoveCell( jEdge ); System.err.println( "Warning: a parallel edge was deleted because " + "the underlying JGraphT forbids parallel edges. " + "If you need parallel edges, use a suitable " + "underlying JGraphT instead." ); } } } /** * Adds to the underlying JGraphT graph a vertex corresponding to the * specified JGraph vertex. In JGraph, two vertices with the same user * object are in principle allowed; in JGraphT, this would lead to duplicate * vertices, which is not allowed. So if such vertex already exists, the * specified vertex is REMOVED from the JGraph graph and a a warning is * printed. * * <p>This method is to be called only for vertices that have already been * added to the JGraph graph.</p> * * @param jVertex the JGraph vertex that has been added. */ void handleJGraphInsertedVertex( GraphCell jVertex ) { Object jtVertex; if( jVertex instanceof DefaultGraphCell ) { jtVertex = ( ( DefaultGraphCell )jVertex ).getUserObject(); } else { // FIXME: Why toString? Explain if for a good reason otherwise fix. jtVertex = jVertex.toString(); } if( m_vertexToCell.containsKey( jtVertex ) ) { // We have to remove the new vertex, because it would lead to // duplicate vertices. We can't use ShieldedGraph.removeVertex for // that, because it would remove the wrong (existing) vertex. System.err.println( "Warning: detected two JGraph vertices with " + "the same JGraphT vertex as user object. It is an " + "indication for a faulty situation that should NOT happen." + "Removing vertex: " + jVertex ); internalRemoveCell( jVertex ); } else { m_jtGraph.addVertex( jtVertex ); m_cellToVertex.put( jVertex, jtVertex ); m_vertexToCell.put( jtVertex, jVertex ); } } /** * Removes the edge corresponding to the specified JGraph edge from the * JGraphT graph. If the specified edge is not contained in * {@link #m_cellToEdge}, it is silently ignored. * * <p>This method is to be called only for edges that have already been * removed from the JGraph graph.</p> * * @param jEdge the JGraph edge that has been removed. */ void handleJGraphRemovedEdge( org.jgraph.graph.Edge jEdge ) { if( m_cellToEdge.containsKey( jEdge ) ) { org._3pq.jgrapht.Edge jtEdge = ( org._3pq.jgrapht.Edge )m_cellToEdge.get( jEdge ); m_jtGraph.removeEdge( jtEdge ); m_cellToEdge.remove( jEdge ); m_edgeToCell.remove( jtEdge ); } } /** * Removes the vertex corresponding to the specified JGraph vertex from the * JGraphT graph. If the specified vertex is not contained in * {@link #m_cellToVertex}, it is silently ignored. * * <p>If any edges are incident with this vertex, we first remove them from * the both graphs, because otherwise the JGraph graph would leave them * intact and the JGraphT graph would throw them out. TODO: Revise this * behavior now that we gracefully tolerate dangling edges. It might be * possible to remove just the JGraphT edges. The JGraph edges will be left * dangling, as a result.</p> * * <p>This method is to be called only for vertices that have already been * removed from the JGraph graph.</p> * * @param jVertex the JGraph vertex that has been removed. */ void handleJGraphRemovedVertex( GraphCell jVertex ) { if( m_cellToVertex.containsKey( jVertex ) ) { Object jtVertex = m_cellToVertex.get( jVertex ); List jtIncidentEdges = m_jtGraph.edgesOf( jtVertex ); if( !jtIncidentEdges.isEmpty() ) { // We can't just call removeAllEdges with this list: that // would throw a ConcurrentModificationException. So we create // a shallow copy. // This also triggers removal of the corresponding JGraph edges. m_jtGraph.removeAllEdges( new ArrayList( jtIncidentEdges ) ); } m_jtGraph.removeVertex( jtVertex ); m_cellToVertex.remove( jVertex ); m_vertexToCell.remove( jtVertex ); } } /** * Adds the specified JGraphT edge to be reflected by this graph model. To * be called only for edges that already exist in the JGraphT graph. * * @param jtEdge a JGraphT edge to be reflected by this graph model. */ void handleJGraphTAddedEdge( org._3pq.jgrapht.Edge jtEdge ) { DefaultEdge edgeCell = m_cellFactory.createEdgeCell( jtEdge ); m_edgeToCell.put( jtEdge, edgeCell ); m_cellToEdge.put( edgeCell, jtEdge ); ConnectionSet cs = new ConnectionSet(); cs.connect( edgeCell, getVertexPort( jtEdge.getSource() ), getVertexPort( jtEdge.getTarget() ) ); internalInsertCell( edgeCell, createEdgeAttributeMap( edgeCell ), cs ); } /** * Adds the specified JGraphT vertex to be reflected by this graph model. To * be called only for edges that already exist in the JGraphT graph. * * @param jtVertex a JGraphT vertex to be reflected by this graph model. */ void handleJGraphTAddedVertex( Object jtVertex ) { DefaultGraphCell vertexCell = m_cellFactory.createVertexCell( jtVertex ); vertexCell.add( new DefaultPort() ); m_vertexToCell.put( jtVertex, vertexCell ); m_cellToVertex.put( vertexCell, jtVertex ); internalInsertCell( vertexCell, createVertexAttributeMap( vertexCell ), null ); } /** * Removes the specified JGraphT edge from being reflected by this graph * model. To be called only for edges that have already been removed from * the JGraphT graph. * * @param jtEdge a JGraphT edge to be removed from being reflected by this * graph model. */ void handleJGraphTRemovedEdge( org._3pq.jgrapht.Edge jtEdge ) { DefaultEdge edgeCell = ( DefaultEdge )m_edgeToCell.remove( jtEdge ); m_cellToEdge.remove( edgeCell ); internalRemoveCell( edgeCell ); } /** * Removes the specified JGraphT vertex from being reflected by this graph * model. To be called only for vertices that have already been removed from * the JGraphT graph. * * @param jtVertex a JGraphT vertex to be removed from being reflected by * this graph model. */ void handleJGraphTRemoveVertex( Object jtVertex ) { DefaultGraphCell vertexCell = ( DefaultGraphCell )m_vertexToCell.remove( jtVertex ); m_cellToVertex.remove( vertexCell ); internalRemoveCell( vertexCell ); // FIXME: Why remove childAt(0)? Explain if correct, otherwise fix. remove( new Object[] { vertexCell.getChildAt( 0 ) } ); } private AttributeMap createEdgeAttributeMap( DefaultEdge edgeCell ) { AttributeMap attrs = new AttributeMap(); attrs.put( edgeCell, m_defaultEdgeAttributes.clone() ); return attrs; } private AttributeMap createVertexAttributeMap( GraphCell vertexCell ) { AttributeMap attrs = new AttributeMap(); attrs.put( vertexCell, m_defaultVertexAttributes.clone() ); return attrs; } /** * Inserts the specified cell into the JGraph graph model. * * @param cell * @param attrs * @param cs */ private void internalInsertCell( GraphCell cell, AttributeMap attrs, ConnectionSet cs ) { m_jCellsBeingAdded.add( cell ); insert( new Object[] { cell }, attrs, cs, null, null ); m_jCellsBeingAdded.remove( cell ); } /** * Removed the specified cell from the JGraph graph model. * * @param cell */ private void internalRemoveCell( GraphCell cell ) { m_jCellsBeingRemoved.add( cell ); remove( new Object[] { cell } ); m_jCellsBeingRemoved.remove( cell ); } /** * Tests if the specified JGraph edge is 'dangling', that is having at least * one endpoint which is not connected to a vertex. * * @param jEdge the JGraph edge to be tested for being dangling. * * @return <code>true</code> if the specified edge is dangling, otherwise * <code>false</code>. */ private boolean isDangling( org.jgraph.graph.Edge jEdge ) { Object jSource = getSourceVertex( this, jEdge ); Object jTarget = getTargetVertex( this, jEdge ); return !m_cellToVertex.containsKey( jSource ) || !m_cellToVertex.containsKey( jTarget ); } /** * Creates the JGraph cells that reflect the respective JGraphT elements. * * @author Barak Naveh * @since Dec 12, 2003 */ public static interface CellFactory { /** * Creates an edge cell that contains its respective JGraphT edge. * * @param jGraphTEdge a JGraphT edge to be contained. * * @return an edge cell that contains its respective JGraphT edge. */ public DefaultEdge createEdgeCell( org._3pq.jgrapht.Edge jGraphTEdge ); /** * Creates a vertex cell that contains its respective JGraphT vertex. * * @param jGraphTVertex a JGraphT vertex to be contained. * * @return a vertex cell that contains its respective JGraphT vertex. */ public DefaultGraphCell createVertexCell( Object jGraphTVertex ); } /** * A simple default cell factory. * * @author Barak Naveh * @since Dec 12, 2003 */ public static class DefaultCellFactory implements CellFactory, Serializable { private static final long serialVersionUID = 3690194343461861173L; /** * @see org._3pq.jgrapht.ext.JGraphModelAdapter.CellFactory#createEdgeCell(org._3pq.jgrapht.Edge) */ public DefaultEdge createEdgeCell( org._3pq.jgrapht.Edge jGraphTEdge ) { return new DefaultEdge( jGraphTEdge ); } /** * @see org._3pq.jgrapht.ext.JGraphModelAdapter.CellFactory#createVertexCell(Object) */ public DefaultGraphCell createVertexCell( Object jGraphTVertex ) { return new DefaultGraphCell( jGraphTVertex ); } } private class JGraphListener implements GraphModelListener, Serializable { private static final long serialVersionUID = 3544673988098865209L; /** * This method is called for all JGraph changes. * * @param e */ public void graphChanged( GraphModelEvent e ) { // We first remove edges that have to be removed, then we // remove vertices, then we add vertices and finally we add // edges. Otherwise, things might go wrong: for example, if we // would first remove vertices and then edges, removal of the // vertices might induce 'automatic' removal of edges. If we // later attempt to re-remove these edges, we get confused. GraphModelChange change = e.getChange(); Object[] removedCells = change.getRemoved(); if( removedCells != null ) { handleRemovedEdges( filterEdges( removedCells ) ); handleRemovedVertices( filterVertices( removedCells ) ); } Object[] insertedCells = change.getInserted(); if( insertedCells != null ) { handleInsertedVertices( filterVertices( insertedCells ) ); handleInsertedEdges( filterEdges( insertedCells ) ); } // Now handle edges that became 'dangling' or became connected. Object[] changedCells = change.getChanged(); if( changedCells != null ) { handleChangedEdges( filterEdges( changedCells ) ); } } /** * Filters a list of edges out of an array of JGraph GraphCell objects. * Other objects are thrown away. * * @param cells Array of cells to be filtered. * * @return a list of edges. */ private List filterEdges( Object[] cells ) { List jEdges = new ArrayList(); for( int i = 0; i < cells.length; i++ ) { if( cells[ i ] instanceof org.jgraph.graph.Edge ) { jEdges.add( cells[ i ] ); } } return jEdges; } /** * Filters a list of vertices out of an array of JGraph GraphCell * objects. Other objects are thrown away. * * @param cells Array of cells to be filtered. * * @return a list of vertices. */ private List filterVertices( Object[] cells ) { List jVertices = new ArrayList(); for( int i = 0; i < cells.length; i++ ) { Object cell = cells[ i ]; if( cell instanceof org.jgraph.graph.Edge ) { // ignore -- we don't care about edges. } else if( cell instanceof Port ) { // ignore -- we don't care about ports. } else if( cell instanceof DefaultGraphCell ) { DefaultGraphCell graphCell = ( DefaultGraphCell )cell; // If a DefaultGraphCell has a Port as a child, it is a vertex. // Note: do not change the order of following conditions; // the code uses the short-circuit evaluation of ||. if( graphCell.isLeaf() || graphCell.getFirstChild() instanceof Port ) { jVertices.add( cell ); } } else if( cell instanceof GraphCell ) { // If it is not a DefaultGraphCell, it doesn't have // children. jVertices.add( cell ); } } return jVertices; } private void handleChangedEdges( List jEdges ) { for( Iterator i = jEdges.iterator(); i.hasNext(); ) { org.jgraph.graph.Edge jEdge = ( org.jgraph.graph.Edge )i.next(); handleJGraphChangedEdge( jEdge ); } } private void handleInsertedEdges( List jEdges ) { for( Iterator i = jEdges.iterator(); i.hasNext(); ) { org.jgraph.graph.Edge jEdge = ( org.jgraph.graph.Edge )i.next(); if( !m_jCellsBeingAdded.remove( jEdge ) ) { handleJGraphInsertedEdge( jEdge ); } } } private void handleInsertedVertices( List jVertices ) { for( Iterator i = jVertices.iterator(); i.hasNext(); ) { GraphCell jVertex = ( GraphCell )i.next(); if( !m_jCellsBeingAdded.remove( jVertex ) ) { handleJGraphInsertedVertex( jVertex ); } } } private void handleRemovedEdges( List jEdges ) { for( Iterator i = jEdges.iterator(); i.hasNext(); ) { org.jgraph.graph.Edge jEdge = ( org.jgraph.graph.Edge )i.next(); if( !m_jCellsBeingRemoved.remove( jEdge ) ) { handleJGraphRemovedEdge( jEdge ); } } } private void handleRemovedVertices( List jVertices ) { for( Iterator i = jVertices.iterator(); i.hasNext(); ) { GraphCell jVertex = ( GraphCell )i.next(); if( !m_jCellsBeingRemoved.remove( jVertex ) ) { handleJGraphRemovedVertex( jVertex ); } } } } /** * A listener on the underlying JGraphT graph. This listener is used to keep * the JGraph model in sync. Whenever one of the event handlers is called, * it first checks whether the change is due to a previous change in the * JGraph model. If it is, then no action is taken. * * @author Barak Naveh * @since Aug 2, 2003 */ private class JGraphTListener implements GraphListener, Serializable { private static final long serialVersionUID = 3616724963609360440L; /** * @see GraphListener#edgeAdded(GraphEdgeChangeEvent) */ public void edgeAdded( GraphEdgeChangeEvent e ) { org._3pq.jgrapht.Edge jtEdge = e.getEdge(); if( !m_jtElementsBeingAdded.remove( jtEdge ) ) { handleJGraphTAddedEdge( jtEdge ); } } /** * @see GraphListener#edgeRemoved(GraphEdgeChangeEvent) */ public void edgeRemoved( GraphEdgeChangeEvent e ) { org._3pq.jgrapht.Edge jtEdge = e.getEdge(); if( !m_jtElementsBeingRemoved.remove( jtEdge ) ) { handleJGraphTRemovedEdge( jtEdge ); } } /** * @see org._3pq.jgrapht.event.VertexSetListener#vertexAdded(GraphVertexChangeEvent) */ public void vertexAdded( GraphVertexChangeEvent e ) { Object jtVertex = e.getVertex(); if( !m_jtElementsBeingAdded.remove( jtVertex ) ) { handleJGraphTAddedVertex( jtVertex ); } } /** * @see org._3pq.jgrapht.event.VertexSetListener#vertexRemoved(GraphVertexChangeEvent) */ public void vertexRemoved( GraphVertexChangeEvent e ) { Object jtVertex = e.getVertex(); if( !m_jtElementsBeingRemoved.remove( jtVertex ) ) { handleJGraphTRemoveVertex( jtVertex ); } } } /** * A wrapper around a JGraphT graph that ensures a few atomic operations. */ private class ShieldedGraph { private final Graph m_graph; ShieldedGraph( Graph graph ) { m_graph = graph; } boolean addEdge( org._3pq.jgrapht.Edge jtEdge ) { m_jtElementsBeingAdded.add( jtEdge ); boolean added = m_graph.addEdge( jtEdge ); m_jtElementsBeingAdded.remove( jtEdge ); return added; } void addVertex( Object jtVertex ) { m_jtElementsBeingAdded.add( jtVertex ); m_graph.addVertex( jtVertex ); m_jtElementsBeingAdded.remove( jtVertex ); } List edgesOf( Object vertex ) { return m_graph.edgesOf( vertex ); } EdgeFactory getEdgeFactory() { return m_graph.getEdgeFactory(); } boolean removeAllEdges( Collection edges ) { return m_graph.removeAllEdges( edges ); } void removeEdge( org._3pq.jgrapht.Edge jtEdge ) { m_jtElementsBeingRemoved.add( jtEdge ); m_graph.removeEdge( jtEdge ); m_jtElementsBeingRemoved.remove( jtEdge ); } void removeVertex( Object jtVertex ) { m_jtElementsBeingRemoved.add( jtVertex ); m_graph.removeVertex( jtVertex ); m_jtElementsBeingRemoved.remove( jtVertex ); } } }
package org.adligo.i.util.client; public class HashCollection implements I_Collection { //Math.abs(Integer.MIN_VALUE) = 2147483648 // but java wouln't compute it :( public static final long INT_SPAN = (long) (21474836.48 * 100) + 1 + Integer.MAX_VALUE; private int max = Integer.MAX_VALUE; private int min = Integer.MIN_VALUE; /** * this turns into the maximum number of b tree lookups */ private short max_depth = 25; /** * this is the depth of the current HashCollection * depth starts at 0 and moves tword max_depth */ private short depth = 0; private long span = INT_SPAN; /** * this is the limit of objects in non max_depth HashCollection.splits */ private int chunkSize = 100; /** * the number of buckets that are created from a split */ private int bucketsFromSplit = 16; /** * if true the object array collection contains objects * if false the objects are in the splits (HashContainers) */ private boolean containsObjects = true; /** * HashLocation's */ private ArrayCollection hashToLocations; private ArrayCollection objects; /** * HashContainers */ private HashCollection[] splits; public synchronized boolean add(Object p) { if (p == null) { return false; } //System.out.println(this.getClass().getName() + " adding" + p); return putOrAdd(p, false); } public synchronized boolean put(Object p) { return putOrAdd(p, true); } private boolean putOrAdd(Object p, boolean put) { if (p == null) { return false; } if (hashToLocations == null) { hashToLocations = new ArrayCollection(); objects = new ArrayCollection(); } int hash = p.hashCode(); if (containsObjects) { if (objects.size() < chunkSize) { return forceAddOrPut(hash, p, put); } else { if (depth < max_depth) { split(hash, p, put); return true; } else { return forceAddOrPut(hash, p, put); } } } else { int chunckSpan = getSpan(span, bucketsFromSplit); Integer bucket = getBucket(p.hashCode(), min, max, chunckSpan); HashCollection hc = (HashCollection) splits[bucket.intValue()]; //System.out.println(this.getClass().getName() + " adding" + p + " to " + hc); if (put) { return hc.put(p); } else { return hc.add(p); } } } private boolean forceAddOrPut(int hash, Object p, boolean put) { HashLocation hl = getHashLocation(hash); if (put) { if (hl != null) { hashToLocations.remove(hl); objects.remove(hl.getLocation()); } Integer loc = objects.addInternal(p); hashToLocations.add(new HashLocation(hash, loc.intValue())); return true; } else { if (hl != null) { return false; } Integer loc = objects.addInternal(p); hashToLocations.add(new HashLocation(hash, loc.intValue())); return true; } } private HashLocation getHashLocation(int hash) { I_Iterator it = hashToLocations.getIterator(); while (it.hasNext()) { HashLocation hl = (HashLocation) it.next(); if (hl.getHash() == hash) { return hl; } } return null; } private void split(int hash, Object p, boolean put) { //System.out.println(this.getClass().getName() + " splitting " + this); containsObjects = false; int chunckSpan = getSpan(span, bucketsFromSplit); /** * the child hash containers will be in order */ int bucket = 0; long next = min; splits = new HashCollection[bucketsFromSplit]; for (int i = 0; i < bucketsFromSplit; i++) { if (next <= Integer.MAX_VALUE) { HashCollection hc = new HashCollection(); hc.min = new Long(next).intValue(); long nextMax = new Long(hc.min).longValue() + new Long(chunckSpan).longValue(); if (nextMax >= Integer.MAX_VALUE) { hc.max = Integer.MAX_VALUE; } else { hc.max = new Long(nextMax).intValue(); } hc.depth = (short) (depth + 1); hc.max_depth = max_depth; hc.span = chunckSpan; /* System.out.println(this.getClass().getName() + " in split adding " + hc + " nextMax was " + nextMax); */ //System.out.println(this.getClass().getName() + " in split adding bucket " + hc); splits[bucket] = hc; bucket++; next = hc.max + 1; } } I_Iterator it = objects.getIterator(); int counter = 0; while (it.hasNext()) { Object obj = it.next(); HashLocation objHash = (HashLocation) hashToLocations.get(counter); putObjectInternal(chunckSpan, obj, objHash.getHash(), put); counter++; } //add the new one putObjectInternal(chunckSpan, p, hash, put); } private void putObjectInternal(int chunckSpan, Object obj, int objHash, boolean put) { Integer bucket = getBucket(objHash, min, max, chunckSpan); HashCollection hc = (HashCollection) splits[bucket.intValue()]; if (hc == null) { throw new NullPointerException("No HashContainer found for bucket " + bucket); } if (put) { hc.put(obj); } else { hc.add(obj); } } public static int getSpan(long p_totalSpan, long p_chunckSize) { double d = p_totalSpan / p_chunckSize; /* System.out.println(HashContainer.class.getClass().getName() + " " + p_totalSpan + "/" + p_chunckSize + " is " + d); */ return new Double(d).intValue(); } /** * this should return the hash bucket * * @param hashCode the hash code * @param min the min hash code for the container * @param max the max hash code for the container * @param span the numbers(size) of a hashBucket * @return */ public static Integer getBucket(int hashCode, int min, int max, int span) { if (hashCode < min) { return null; } if (hashCode > max) { return null; } int currentBucket = 0; long currentLong = min; while (currentLong < max) { long next = currentLong + span; /* System.out.println(HashContainer.class + " in getBucket hashCode = " + hashCode + " min = " + min + " next = " + next ); */ if (hashCode <= next) { return new Integer(currentBucket); } currentLong = currentLong + span + 1; currentBucket++; /* System.out.println(HashContainer.class + " in getBucket currentBucket = " + currentBucket + " currentLong = " + currentLong); */ } return null; } public Object get(int hash) { if (containsObjects) { if (hashToLocations == null) { return null; } I_Iterator it = hashToLocations.getIterator(); while (it.hasNext()) { HashLocation hl = (HashLocation) it.next(); if (hash == hl.getHash()) { return objects.get(hl.getLocation()); } } } else { int chunckSpan = getSpan(span, bucketsFromSplit); Integer bucket = getBucket(hash, min, max, chunckSpan); HashCollection hc = (HashCollection) splits[bucket.intValue()]; return hc.get(hash); } return null; } public synchronized boolean remove(int hash) { if (containsObjects) { I_Iterator it = hashToLocations.getIterator(); while (it.hasNext()) { HashLocation hl = (HashLocation) it.next(); if (hash == hl.getHash()) { Object obj = objects.get(hl.getLocation()); objects.remove(obj); hashToLocations.clear(); //rehash I_Iterator itRH = objects.getIterator(); int locationCounter = 0; while (itRH.hasNext()) { Object o = itRH.next(); hashToLocations.add(new HashLocation(o.hashCode(), locationCounter)); locationCounter++; } return true; } } } else { int chunckSpan = getSpan(span, bucketsFromSplit); Integer bucket = getBucket(hash, min, max, chunckSpan); HashCollection hc = (HashCollection) splits[bucket.intValue()]; return hc.remove(hash); } return false; } public void clear() { containsObjects = true; hashToLocations = new ArrayCollection(); objects = new ArrayCollection(); splits = null; } public String toString() { StringBuffer sb = new StringBuffer(); for (int i = 0; i < depth; i++) { sb.append("\t"); } sb.append(super.toString()); sb.append("[min="); sb.append(min); sb.append(",max="); sb.append(max); if (containsObjects) { sb.append(",objects="); sb.append(objects); sb.append(",hashToLocations="); sb.append(hashToLocations); } else { sb.append(",splits;\n"); for (int i = 0; i < splits.length; i++) { //null should only happen during debugging if (splits[i] != null) { if (splits[i].size() > 0) { sb.append(splits[i]); sb.append("\n"); } } } } sb.append("]"); return sb.toString(); } public boolean contains(Object other) { if (other == null) { return false; } Object mine = get(other.hashCode()); if (other.equals(mine)) { return true; } return false; } public I_Iterator getIterator() { Object[] objs = getObjects(); return new ArrayIterator(objs); } private Object[] getObjects() { Object[] objs = new Object[size()]; if (containsObjects) { objs = objects.toArray(); } else { int counter = 0; for (int i = 0; i < splits.length; i++) { Object[] child = splits[i].getObjects(); for (int j = 0; j < child.length; j++) { objs[counter] = child[j]; counter++; } } } return objs; } public boolean remove(Object o) { return remove(((Integer) o).intValue()); } public int size() { if (containsObjects) { if (objects == null) { return 0; } return objects.size(); } else { int total = 0; for (int i = 0; i < splits.length; i++) { total = total + splits[i].size(); } return total; } } public Object getWrapped() { return this; } }
package org.appwork.storage; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.Map.Entry; import java.util.logging.Level; import org.appwork.utils.logging.Log; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.JsonMappingException; public class JacksonStorageChest extends Storage { private final HashMap<String, Object> map; private final String name; private String filename = null; private final boolean plain; public JacksonStorageChest(final String name) throws StorageException { this(name, false); } /** * @param name2 * @param b */ public JacksonStorageChest(final String name, final boolean plain) { this.map = new HashMap<String, Object>(); this.name = name; this.plain = plain; this.filename = "cfg/" + name + (plain ? ".json" : ".ejs"); synchronized (JSonStorage.LOCK) { final HashMap<String, Object> load = JSonStorage.restoreFrom(this.filename, null, new HashMap<String, Object>()); this.map.putAll(load); } } @Override public void clear() throws StorageException { Entry<String, Object> next; for (final Iterator<Entry<String, Object>> it = this.map.entrySet().iterator(); it.hasNext();) { next = it.next(); this.getEventSender().fireEvent(StorageEvent.createChangeEvent(this, next.getKey(), next.getValue(), null)); } this.map.clear(); } /* * (non-Javadoc) * * @see org.appwork.storage.Storage#decrease(java.lang.String) */ @Override public long decrease(final String key) { long ret = this.get(key, 0l).intValue(); this.put(key, --ret); return ret; } @SuppressWarnings("unchecked") @Override public <E> E get(final String key, final E def) throws StorageException { final boolean contains = this.map.containsKey(key); Object ret = contains ? this.map.get(key) : null; if (ret != null && def != null && ret.getClass() != def.getClass()) { // Housten we have... // ... to convert if (def instanceof Long) { if (ret instanceof Integer) { // this is normal, because jackson converts tiny longs to // ints automatically // Log.exception(Level.FINE, new // Exception("Had to convert integer to long for storage " + // this.name + "." + key + "=" + ret)); ret = new Long(((Integer) ret).longValue()); } } else if (def instanceof Integer) { if (ret instanceof Long) { Log.exception(Level.FINE, new Exception("Had to convert long to integer for storage " + this.name + "." + key + "=" + ret)); ret = new Integer(((Long) ret).intValue()); } } } // put entry if we have no entry if (!contains) { ret = def; if (def instanceof Boolean) { this.put(key, (Boolean) def); } else if (def instanceof Long) { this.put(key, (Long) def); } else if (def instanceof Integer) { this.put(key, (Integer) def); } else if (def instanceof Byte) { this.put(key, (Byte) def); } else if (def instanceof String) { this.put(key, (String) def); } else if (def instanceof Enum<?>) { this.put(key, (Enum<?>) def); } else if (def instanceof Double) { this.put(key, (Double) def); } else { throw new StorageException("Invalid datatype: " + def.getClass()); } } if (def instanceof Enum<?> && ret instanceof String) { try { ret = Enum.valueOf(((Enum<?>) def).getDeclaringClass(), (String) ret); } catch (final Throwable e) { Log.exception(e); this.put(key, (Enum<?>) def); ret = def; } } return (E) ret; } public String getFilename() { return this.filename; } public String getName() { return this.name; } /* * (non-Javadoc) * * @see org.appwork.storage.Storage#increase(java.lang.String) */ @Override public long increase(final String key) { long ret = this.get(key, 0).intValue(); this.put(key, ++ret); return ret; } public boolean isPlain() { return this.plain; } @Override public void put(final String key, final Boolean value) throws StorageException { final Boolean old = this.map.containsKey(key) ? this.get(key, value) : null; this.map.put(key, value); this.getEventSender().fireEvent(StorageEvent.createChangeEvent(this, key, old, value)); } @Override public void put(final String key, final Byte value) throws StorageException { final Byte old = this.map.containsKey(key) ? this.get(key, value) : null; this.map.put(key, value); this.getEventSender().fireEvent(StorageEvent.createChangeEvent(this, key, old, value)); } @Override public void put(final String key, final Double value) throws StorageException { final Double old = this.map.containsKey(key) ? this.get(key, value) : null; this.map.put(key, value); this.getEventSender().fireEvent(StorageEvent.createChangeEvent(this, key, old, value)); } @Override public void put(final String key, final Enum<?> value) throws StorageException { final Enum<?> old = this.map.containsKey(key) ? this.get(key, value) : null; this.map.put(key, value); this.getEventSender().fireEvent(StorageEvent.createChangeEvent(this, key, old, value)); } @Override public void put(final String key, final Float value) throws StorageException { final Float old = this.map.containsKey(key) ? this.get(key, value) : null; this.map.put(key, value); this.getEventSender().fireEvent(StorageEvent.createChangeEvent(this, key, old, value)); } @Override public void put(final String key, final Integer value) throws StorageException { final Integer old = this.map.containsKey(key) ? this.get(key, value) : null; this.map.put(key, value); this.getEventSender().fireEvent(StorageEvent.createChangeEvent(this, key, old, value)); } @Override public void put(final String key, final Long value) throws StorageException { final Long old = this.map.containsKey(key) ? this.get(key, value) : null; this.map.put(key, value); this.getEventSender().fireEvent(StorageEvent.createChangeEvent(this, key, old, value)); } @Override public void put(final String key, final String value) throws StorageException { final String old = this.map.containsKey(key) ? this.get(key, value) : null; this.map.put(key, value); this.getEventSender().fireEvent(StorageEvent.createChangeEvent(this, key, old, value)); } /* * (non-Javadoc) * * @see org.appwork.storage.Storage#remove(java.lang.String) */ @Override public Object remove(final String key) { // TODO Auto-generated method stub return this.map.remove(key); } @Override public void save() throws StorageException { synchronized (JSonStorage.LOCK) { try { String json = null; json = JSonStorage.getMapper().writeValueAsString(this.map); JSonStorage.saveTo(this.filename, json); } catch (final JsonGenerationException e) { Log.exception(e); } catch (final JsonMappingException e) { Log.exception(e); } catch (final IOException e) { Log.exception(e); } } } }
package org.biojava.bio.symbol; import java.util.*; import java.io.*; import org.biojava.bio.*; import org.biojava.utils.*; import org.biojava.bio.seq.*; import org.biojava.bio.seq.io.*; /** * Basic implementation of SymbolList. This * is currently backed by a normal Java array. * <p> * SimpleSymbolList is now editable. edit() has been implemented * in a way that edits are relatively inefficient, but symbolAt() is * very efficient. * </p> * <p> * A new constructor SimpleSymbolList(SymbolParser,String) has * been added so you can now simply turn a String into a SymbolList. * This is mostly to provide a simple way to create a SymbolList for * people just trying to get their feet wet. So here is an example. * </p> * <code> * String seqString = "gaattc"; * FiniteAlphabet dna = (FiniteAlphabet) AlphabetManager.alphabetForName("DNA"); * SymbolParser parser = dna.getParser("token"); * SymbolList mySl = new SimpleSymbolList (parser,seqString); * System.out.println("Look at my sequence " + mySl.seqString()); * </code> * <p> * with the right parser you should be able to make a protein sequence * from the String "AspAlaValIleAsp" * </p> * <p> * subList() is implemented such that subLists are views of the original until * such time as the underlying SymbolList is edited in a way that would modify * the subList, at which point the subList gets its own array of Symbols and * does not reflect the edit to the original. When subList() is called on another * subList (which is a veiw SimpleSymbolList) the new SimpleSymbolList is a view * of the original, not the subList. * </p> * * @author Thomas Down * @author David Waring */ public class SimpleSymbolList extends AbstractSymbolList implements ChangeListener, Serializable { private static final int INCREMENT = 100; private Alphabet alphabet; private Symbol[] symbols; private int length; private boolean isView; // this is for subList which returns a view onto a SimpleSymbolList until either is edited private int viewOffset; // offset of the veiw to the original private SymbolList referenceSymbolList; // the original SymbolList subLists of views become sublists of original private void addListener() { alphabet.addChangeListener(ChangeListener.ALWAYS_VETO, Alphabet.SYMBOLS); } protected void finalize() throws Throwable { super.finalize(); alphabet.removeChangeListener(ChangeListener.ALWAYS_VETO, Alphabet.SYMBOLS); if (isView){ referenceSymbolList.removeChangeListener(this); } } public SimpleSymbolList(Alphabet alpha) { this.alphabet = alpha; this.length = 0; this.symbols = new Symbol[INCREMENT]; this.isView = false; this.viewOffset = 0; addListener(); } public SimpleSymbolList(Alphabet alpha, List rList) throws IllegalSymbolException { this.alphabet = alpha; this.length = rList.size(); symbols = new Symbol[length]; int pos = 0; for (Iterator i = rList.iterator(); i.hasNext(); ) { symbols[pos] = (Symbol) i.next(); alphabet.validate(symbols[pos]); pos++; } this.isView = false; this.viewOffset = 0; addListener(); } public SimpleSymbolList(SymbolTokenization parser, String seqString) throws IllegalSymbolException { if (parser.getTokenType() == SymbolTokenization.CHARACTER) { symbols = new Symbol[seqString.length()]; } else { symbols = new Symbol[INCREMENT]; } char[] charArray = new char[1024]; int segLength = seqString.length(); StreamParser stParser = parser.parseStream(new SSLIOListener()); int charCount = 0; int bcnt = 0; int chunkLength; while (charCount < segLength) { chunkLength = Math.min(charArray.length, segLength - charCount); seqString.getChars(charCount, charCount + chunkLength, charArray, 0); stParser.characters(charArray, 0, chunkLength); charCount += chunkLength; } stParser.close(); this.alphabet = parser.getAlphabet(); this.isView = false; this.viewOffset = 0; addListener(); } /** * Construct a copy of an existing SymbolList. * * @param The list to copy. */ public SimpleSymbolList(SymbolList sl) { this.alphabet = sl.getAlphabet(); this.length = sl.length(); symbols = new Symbol[length]; for (int i = 0; i < length; ++i) { symbols[i] = sl.symbolAt(i + 1); } this.isView = false; this.viewOffset = 0; addListener(); } /** * Construct construct a SimpleSymbolList that is a veiw of the original. * this is used by subList(); * * @param orig -- the original SimpleSymbolList that this is a view of. * @param start -- first base in new SymbolList * @param end -- last base in new SymbolList */ private SimpleSymbolList(SimpleSymbolList orig, int start, int end) { this.alphabet = orig.alphabet; this.symbols = orig.symbols; this.length = end - start + 1; this.isView = true; this.viewOffset = start -1; this.referenceSymbolList = orig; addListener(); } /** * Get the alphabet of this SymbolList. */ public Alphabet getAlphabet() { return alphabet; } /** * Get the length of this SymbolList. */ public int length() { return length; } /** * Find a symbol at a specified offset in the SymbolList. * * @param pos Position in biological coordinates (1..length) */ public Symbol symbolAt(int pos) { // if (pos > length || pos < 1) { // throw new IndexOutOfBoundsException( // "Can't access " + pos + // " as it is not within 1.." + length return symbols[viewOffset + pos - 1]; } /** * create a subList of the original, this will be a view until * either the original symbolList or the sublist is edited */ public SymbolList subList(int start, int end){ SimpleSymbolList sl = new SimpleSymbolList(this,viewOffset+start,viewOffset+end); if (isView){ referenceSymbolList.addChangeListener(sl); }else{ this.addChangeListener(sl); } return sl; } /** * Apply and edit to the SymbolList as specified by Edit. * <p> * edit() is now supported using the ChangeEvent system. SubLists do NOT reflect edits. * </p> */ public synchronized void edit(Edit edit)throws IndexOutOfBoundsException, IllegalAlphabetException,ChangeVetoException { ChangeSupport cs; ChangeEvent cevt; Symbol[] dest; int newLength; // first make sure that it is in bounds if ((edit.pos + edit.length > length +1 ) || (edit.pos <= 0) || edit.length < 0){ throw new IndexOutOfBoundsException(); } // make sure that the symbolList is of the correct alphabet if (( edit.replacement.getAlphabet() != alphabet) && (edit.replacement != SymbolList.EMPTY_LIST)){ throw new IllegalAlphabetException(); } // give the listeners a change to veto this // create a new change event ->the EDIT is a static final variable of type ChangeType in SymbolList interface cevt = new ChangeEvent(this, SymbolList.EDIT, edit); cs = getChangeSupport(SymbolList.EDIT); // let the listeners know what we want to do cs.firePreChangeEvent(cevt); // if nobody complained lets continue // if we are a view we convert to a real SimpleSymbolList if (isView){ makeReal(); } // now for the edit int posRightFragInSourceArray5 = edit.pos + edit.length - 1; int rightFragLength = length - posRightFragInSourceArray5; int posRightFragInDestArray5 = posRightFragInSourceArray5 + edit.replacement.length() - edit.length; int posReplaceFragInDestArray5 = edit.pos - 1; int replaceFragLength = edit.replacement.length(); if ((length + replaceFragLength - edit.length) > symbols.length){ // extend the array dest = new Symbol[(length + replaceFragLength - edit.length + INCREMENT)]; // copy symbols before the edit no need to do this if we didn't have to build a new array System.arraycopy(symbols,0,dest,0,(edit.pos -1)); }else{ dest = symbols; // array copy works when copying from an array to itself } // copy the symbols after the edit if (rightFragLength > 0){ System.arraycopy(symbols, posRightFragInSourceArray5, dest, posRightFragInDestArray5,rightFragLength); } // copy the symbols within the edit for (int i = 1; i <= replaceFragLength; i++){ dest[posReplaceFragInDestArray5 + i - 1] = edit.replacement.symbolAt(i); } // if there was a net deletion we have to get rid of the remaining symbols newLength = length + replaceFragLength - edit.length; for (int j = newLength; j < length; j++){ dest[j] = null; } length = newLength; symbols = dest; cs.firePostChangeEvent(cevt); } /** * On preChange() we convert the SymolList to a non-veiw version, giving it its own copy of symbols */ public void preChange(ChangeEvent cev) throws ChangeVetoException{ // let the listeners know that they have to be converted or veto the change; ChangeSupport cs = getChangeSupport(SymbolList.EDIT); // lets not bother making any changes if the edit would not effect us or our children Object change = cev.getChange(); if( (change != null) && (change instanceof Edit) ) { Edit e = (Edit)change; if (e.pos > (viewOffset + length)){ return; } if ((e.pos < viewOffset) && (e.length - e.replacement.length() == 0)){ return; } // subLists of views are listeners to the original so we don't have to forward the message makeReal(); } } // we don't do anything on the postChange we don't want to reflect the changes public void postChange(ChangeEvent cev){ } /** * Converts a view symbolList to a real one * that means it gets its own copy of the symbols array */ private void makeReal(){ if(isView){ Symbol[] newSymbols = new Symbol[length]; System.arraycopy (symbols,viewOffset,newSymbols, 0, length); this.symbols = newSymbols; this.isView = false; this.viewOffset = 0; referenceSymbolList.removeChangeListener(this); referenceSymbolList = null; } } public void addSymbol(Symbol sym) throws IllegalSymbolException, ChangeVetoException { try { SymbolList extraSymbol = new SimpleSymbolList(getAlphabet(), Collections.nCopies(1, sym)); edit(new Edit(length() + 1, 0, extraSymbol)); } catch (IllegalAlphabetException ex) { throw new IllegalSymbolException(ex, sym, "Couldn't add symbol"); } catch (IndexOutOfBoundsException ex) { throw new BioError("Assertion failure: couldn't add symbol at end of list"); } } /** * Simple inner class for channelling sequence notifications from * a StreamParser. */ private class SSLIOListener extends SeqIOAdapter { public void addSymbols(Alphabet alpha,Symbol[] syms,int start, int length){ if(symbols.length < SimpleSymbolList.this.length + length) { Symbol[] dest; dest = new Symbol [((int) (1.5 * SimpleSymbolList.this.length)) + length]; System.arraycopy(symbols, 0, dest, 0, SimpleSymbolList.this.length); System.arraycopy(syms, start, dest, SimpleSymbolList.this.length, length); symbols = dest; }else{ System.arraycopy(syms, start, symbols, SimpleSymbolList.this.length, length); } SimpleSymbolList.this.length += length; } } }
package org.encog.neural.prune; import java.util.ArrayList; import java.util.List; import org.encog.StatusReportable; import org.encog.neural.data.Indexable; import org.encog.neural.data.NeuralDataSet; import org.encog.neural.data.buffer.BufferedNeuralDataSet; import org.encog.neural.networks.BasicNetwork; import org.encog.neural.networks.layers.Layer; import org.encog.neural.networks.training.propagation.Propagation; import org.encog.neural.networks.training.propagation.resilient.ResilientPropagation; import org.encog.neural.networks.training.strategy.StopTrainingStrategy; import org.encog.neural.pattern.NeuralNetworkPattern; import org.encog.util.concurrency.job.ConcurrentJob; import org.encog.util.concurrency.job.JobUnitContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class is used to help determine the optimal configuration for the hidden * layers of a neural network. It can accept a pattern, which specifies the type * of neural network to create, and a list of the maximum and minimum hidden * layer neurons. It will then attempt to train the neural network at all * configurations and see which hidden neuron counts work the best. * * This method does not simply choose the network with the lowest error rate. A * specifiable number of best networks are kept, which represent the networks * with the lowest error rates. From this collection of networks, the best * network is defined to be the one with the fewest number of connections. * * Not all starting random weights are created equal. Because of this, an option * is provided to allow you to choose how many attempts you want the process to * make, with different weights. All random weights are created using the * default Nguyen-Widrow method normally used by Encog. * */ public class PruneIncremental extends ConcurrentJob { /** * Format the network as a human readable string that lists the hidden * layers. * * @param network * The network to format. * @return A human readable string. */ public static String networkToString(final BasicNetwork network) { final StringBuilder result = new StringBuilder(); int num = 1; Layer layer = network.getLayer(BasicNetwork.TAG_INPUT); // display only hidden layers while (layer.getNext().size() > 0) { layer = layer.getNext().get(0).getToLayer(); if (layer.getNext().size() > 0) { if (result.length() > 0) { result.append(","); } result.append("H"); result.append(num++); result.append("="); result.append(layer.getNeuronCount()); } } return result.toString(); } /** * Are we done? */ private boolean done = false; /** * The logging object. */ @SuppressWarnings("unused") private final Logger logger = LoggerFactory.getLogger(this.getClass()); /** * The training set to use as different neural networks are evaluated. */ private final NeuralDataSet training; /** * The pattern for which type of neural network we would like to create. */ private final NeuralNetworkPattern pattern; /** * The ranges for the hidden layers. */ private final List<HiddenLayerParams> hidden = new ArrayList<HiddenLayerParams>(); /** * The number if training iterations that should be tried for each network. */ private final int iterations; /** * An array of the top networks. */ private final BasicNetwork[] topNetworks; /** * An array of the top errors. */ private final double[] topErrors; /** * The best network found so far. */ private BasicNetwork bestNetwork; /** * How many networks have been tried so far? */ private int currentTry; /** * The object that status should be reported to. */ @SuppressWarnings("unused") private final StatusReportable report; /** * Keeps track of how many neurons in each hidden layer as training the * evaluation progresses. */ private int[] hiddenCounts; /** * The current highest error. */ private double high; /** * The current lowest error. */ private double low; /** * The results in a 2d array. */ private double[][] results; /** * The size of the first hidden layer. */ private int hidden1Size; /** * The size of the second hidden layer. */ private int hidden2Size; /** * The number of tries with random weights. */ private final int weightTries; /** * Construct an object to determine the optimal number of hidden layers and * neurons for the specified training data and pattern. * * @param training * The training data to use. * @param pattern * The network pattern to use to solve this data. * @param iterations * How many iterations to try per network. * @param weightTries * The number of random weights to use. * @param numTopResults * The number of "top networks" to choose the most simple "best * network" from. * @param report * Object used to report status to. */ public PruneIncremental(final NeuralDataSet training, final NeuralNetworkPattern pattern, final int iterations, final int weightTries, final int numTopResults, final StatusReportable report) { super(report); this.training = training; this.pattern = pattern; this.iterations = iterations; this.report = report; this.weightTries = weightTries; this.topNetworks = new BasicNetwork[numTopResults]; this.topErrors = new double[numTopResults]; } /** * Add a hidden layer's min and max. Call this once per hidden layer. * Specify a zero min if it is possible to remove this hidden layer. * * @param min * The minimum number of neurons for this layer. * @param max * The maximum number of neurons for this layer. */ public void addHiddenLayer(final int min, final int max) { final HiddenLayerParams param = new HiddenLayerParams(min, max); this.hidden.add(param); } /** * Generate a network according to the current hidden layer counts. * * @return The network based on current hidden layer counts. */ private BasicNetwork generateNetwork() { this.pattern.clear(); for (final int element : this.hiddenCounts) { if (element > 0) { this.pattern.addHiddenLayer(element); } } return this.pattern.generate(); } /** * @return The network being processed. */ public BasicNetwork getBestNetwork() { return this.bestNetwork; } /** * @return The hidden layer max and min. */ public List<HiddenLayerParams> getHidden() { return this.hidden; } /** * @return The size of the first hidden layer. */ public int getHidden1Size() { return this.hidden1Size; } /** * @return The size of the second hidden layer. */ public int getHidden2Size() { return this.hidden2Size; } /** * @return The higest error so far. */ public double getHigh() { return this.high; } /** * @return The number of training iterations to try for each network. */ public int getIterations() { return this.iterations; } /** * @return The lowest error so far. */ public double getLow() { return this.low; } /** * @return The network pattern to use. */ public NeuralNetworkPattern getPattern() { return this.pattern; } /** * @return The error results. */ public double[][] getResults() { return this.results; } /** * @return the topErrors */ public double[] getTopErrors() { return this.topErrors; } /** * @return the topNetworks */ public BasicNetwork[] getTopNetworks() { return this.topNetworks; } /** * @return The training set to use. */ public NeuralDataSet getTraining() { return this.training; } /** * Increase the hidden layer counts according to the hidden layer * parameters. Increase the first hidden layer count by one, if it is maxed * out, then set it to zero and increase the next hidden layer. * * @return False if no more increases can be done, true otherwise. */ private boolean increaseHiddenCounts() { int i = 0; do { final HiddenLayerParams param = this.hidden.get(i); this.hiddenCounts[i]++; // is this hidden layer still within the range? if (this.hiddenCounts[i] <= param.getMax()) { return true; } // increase the next layer if we've maxed out this one this.hiddenCounts[i] = param.getMin(); i++; } while (i < this.hiddenCounts.length); // can't increase anymore, we're done! return false; } /** * Init for prune. */ public void init() { // handle display for one layer if (this.hidden.size() == 1) { this.hidden1Size = (this.hidden.get(0).getMax() - this.hidden .get(0).getMin()) + 1; this.hidden2Size = 0; this.results = new double[this.hidden1Size][1]; } else if (this.hidden.size() == 2) { // handle display for two layers this.hidden1Size = (this.hidden.get(0).getMax() - this.hidden .get(0).getMin()) + 1; this.hidden2Size = (this.hidden.get(1).getMax() - this.hidden .get(1).getMin()) + 1; this.results = new double[this.hidden1Size][this.hidden2Size]; } else { // we don't handle displays for more than two layers this.hidden1Size = 0; this.hidden2Size = 0; this.results = null; } // reset min and max this.high = Double.NEGATIVE_INFINITY; this.low = Double.POSITIVE_INFINITY; } /** * Get the next workload. This is the number of hidden neurons. This is the * total amount of work to be processed. * * @return The amount of work to be processed by this. */ @Override public int loadWorkload() { int result = 1; for (final HiddenLayerParams param : this.hidden) { result *= (param.getMax() - param.getMin()) + 1; } init(); return result; } /** * Perform an individual job unit, which is a single network to train and * evaluate. * * @param context * Contains information about the job unit. */ @Override public void performJobUnit(final JobUnitContext context) { final BasicNetwork network = (BasicNetwork) context.getJobUnit(); BufferedNeuralDataSet buffer = null; NeuralDataSet useTraining = this.training; if( this.training instanceof BufferedNeuralDataSet ) { buffer = (BufferedNeuralDataSet)this.training; useTraining = buffer.openAdditional(); } // train the neural network double error = Double.POSITIVE_INFINITY; for (int z = 0; z < this.weightTries; z++) { network.reset(); final Propagation train = new ResilientPropagation(network, useTraining); final StopTrainingStrategy strat = new StopTrainingStrategy(0.001, 5); train.addStrategy(strat); train.setNumThreads(1); // force single thread mode for (int i = 0; (i < this.iterations) && !getShouldStop() && !strat.shouldStop(); i++) { train.iteration(); } error = Math.min(error, train.getError()); } if( buffer!=null ) buffer.close(); if (!getShouldStop()) { // update min and max this.high = Math.max(this.high, error); this.low = Math.min(this.low, error); if (this.hidden1Size > 0) { int networkHidden1Count; int networkHidden2Count; if (network.getStructure().getLayers().size() > 3) { networkHidden2Count = network.getStructure().getLayers() .get(1).getNeuronCount(); networkHidden1Count = network.getStructure().getLayers() .get(2).getNeuronCount(); } else { networkHidden2Count = 0; networkHidden1Count = network.getStructure().getLayers() .get(1).getNeuronCount(); } int row, col; if (this.hidden2Size == 0) { row = networkHidden1Count - this.hidden.get(0).getMin(); col = 0; } else { row = networkHidden1Count - this.hidden.get(0).getMin(); col = networkHidden2Count - this.hidden.get(1).getMin(); } this.results[row][col] = error; } // report status this.currentTry++; updateBest(network, error); reportStatus(context, "Current: " + PruneIncremental.networkToString(network) + "; Best: " + PruneIncremental.networkToString(this.bestNetwork)); } } /** * Begin the prune process. */ @Override public void process() { if (this.hidden.size() == 0) { final String str = "To calculate the optimal hidden size, at least " + "one hidden layer must be defined."; if (this.logger.isErrorEnabled()) { this.logger.error(str); } } this.hiddenCounts = new int[this.hidden.size()]; // set the best network this.bestNetwork = null; // set to minimums int i = 0; for (final HiddenLayerParams parm : this.hidden) { this.hiddenCounts[i++] = parm.getMin(); } // make sure hidden layer 1 has at least one neuron if (this.hiddenCounts[0] == 0) { final String str = "To calculate the optimal hidden size, at least " + "one neuron must be the minimum for the first hidden layer."; if (this.logger.isErrorEnabled()) { this.logger.error(str); } } super.process(); } /** * Request the next task. This is the next network to attempt to train. * * @return The next network to train. */ @Override public Object requestNextTask() { if (this.done || getShouldStop()) { return null; } final BasicNetwork network = generateNetwork(); if (!increaseHiddenCounts()) { this.done = true; } return network; } /** * Update the best network. * @param network The network to consider. * @param error The error for this network. */ private synchronized void updateBest(final BasicNetwork network, final double error) { this.high = Math.max(this.high, error); this.low = Math.min(this.low, error); int selectedIndex = -1; // find a place for this in the top networks, if it is a top network for (int i = 0; i < this.topNetworks.length; i++) { if (this.topNetworks[i] == null) { selectedIndex = i; break; } else if (this.topErrors[i] > error) { // this network might be worth replacing, see if the one // already selected is a better option. if ((selectedIndex == -1) || (this.topErrors[selectedIndex] < this.topErrors[i])) { selectedIndex = i; } } } // replace the selected index if (selectedIndex != -1) { this.topErrors[selectedIndex] = error; this.topNetworks[selectedIndex] = network; } // now select the best network, which is the most simple of the // top networks. BasicNetwork choice = null; for (final BasicNetwork n : this.topNetworks) { if (n == null) { continue; } if (choice == null) { choice = n; } else { if (n.getStructure().calculateSize() < choice.getStructure() .calculateSize()) { choice = n; } } } if (choice != this.bestNetwork) { if (this.logger.isDebugEnabled()) { this.logger.debug("Prune found new best network: error=" + error + ", network=" + choice); } this.bestNetwork = choice; } } }
package net.fortuna.ical4j.data; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.text.ParseException; import net.fortuna.ical4j.model.Calendar; import net.fortuna.ical4j.model.Component; import net.fortuna.ical4j.model.ComponentFactory; import net.fortuna.ical4j.model.Parameter; import net.fortuna.ical4j.model.ParameterFactoryImpl; import net.fortuna.ical4j.model.Property; import net.fortuna.ical4j.model.PropertyFactoryImpl; import net.fortuna.ical4j.model.TimeZone; import net.fortuna.ical4j.model.TimeZoneRegistry; import net.fortuna.ical4j.model.TimeZoneRegistryFactory; import net.fortuna.ical4j.model.component.VEvent; import net.fortuna.ical4j.model.component.VTimeZone; import net.fortuna.ical4j.model.component.VToDo; import net.fortuna.ical4j.model.parameter.TzId; import net.fortuna.ical4j.model.property.DateListProperty; import net.fortuna.ical4j.model.property.DateProperty; import net.fortuna.ical4j.util.Constants; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Parses and builds an iCalendar model from an input stream. * Note that this class is not thread-safe. * * @version 2.0 * @author Ben Fortuna */ public class CalendarBuilder implements ContentHandler { private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); private static Log log = LogFactory.getLog(CalendarBuilder.class); private CalendarParser parser; private TimeZoneRegistry registry; protected Calendar calendar; protected Component component; protected Component subComponent; protected Property property; /** * Default constructor. */ public CalendarBuilder() { this(new CalendarParserImpl(), TimeZoneRegistryFactory.getInstance().createRegistry()); } /** * Constructs a new calendar builder using the specified * calendar parser. * @param parser a calendar parser used to parse calendar files */ public CalendarBuilder(final CalendarParser parser) { this(parser, TimeZoneRegistryFactory.getInstance().createRegistry()); } /** * Constructs a new calendar builder using the specified * timezone registry. * @param parser a calendar parser used to parse calendar files */ public CalendarBuilder(final TimeZoneRegistry registry) { this(new CalendarParserImpl(), registry); } /** * Constructs a new instance using the specified parser and registry. * @param parser a calendar parser used to construct the calendar * @param registry a timezone registry used to retrieve timezones and * register additional timezone information found in the calendar */ public CalendarBuilder(final CalendarParser parser, final TimeZoneRegistry registry) { this.parser = parser; this.registry = registry; } /** * Builds an iCalendar model from the specified input stream. * * @param in * @return a calendar * @throws IOException * @throws ParserException */ public Calendar build(final InputStream in) throws IOException, ParserException { return build(new InputStreamReader(in, DEFAULT_CHARSET)); } /** * Builds an iCalendar model from the specified reader. * An <code>UnfoldingReader</code> is applied to the specified * reader to ensure the data stream is correctly unfolded where * appropriate. * * @param in * @return a calendar * @throws IOException * @throws ParserException */ public Calendar build(final Reader in) throws IOException, ParserException { return build(new UnfoldingReader(in)); } /** * Build an iCalendar model by parsing data from the specified reader. * @param uin an unfolding reader to read data from * @return a calendar model * @throws IOException * @throws ParserException */ public Calendar build(final UnfoldingReader uin) throws IOException, ParserException { // re-initialise.. calendar = null; component = null; subComponent = null; property = null; parser.parse(uin, this); return calendar; } /* (non-Javadoc) * @see net.fortuna.ical4j.data.ContentHandler#endCalendar() */ public void endCalendar() { // do nothing.. } /* (non-Javadoc) * @see net.fortuna.ical4j.data.ContentHandler#endComponent(java.lang.String) */ public void endComponent(final String name) { if (component != null) { if (subComponent != null) { if (component instanceof VTimeZone) { ((VTimeZone) component).getObservances().add(subComponent); } else if (component instanceof VEvent) { ((VEvent) component).getAlarms().add(subComponent); } else if (component instanceof VToDo) { ((VToDo) component).getAlarms().add(subComponent); } subComponent = null; } else { calendar.getComponents().add(component); if (component instanceof VTimeZone && registry != null) { // register the timezone for use with iCalendar objects.. registry.register(new TimeZone((VTimeZone) component)); } component = null; } } } /* (non-Javadoc) * @see net.fortuna.ical4j.data.ContentHandler#endProperty(java.lang.String) */ public void endProperty(final String name) { if (property != null) { // replace with a constant instance if applicable.. property = Constants.forProperty(property); if (component != null) { if (subComponent != null) { subComponent.getProperties().add(property); } else { component.getProperties().add(property); } } else if (calendar != null) { calendar.getProperties().add(property); } property = null; } } /* (non-Javadoc) * @see net.fortuna.ical4j.data.ContentHandler#parameter(java.lang.String, java.lang.String) */ public void parameter(final String name, final String value) throws URISyntaxException { if (property != null) { // parameter names are case-insensitive, but convert to upper case to simplify further processing Parameter param = ParameterFactoryImpl.getInstance().createParameter(name.toUpperCase(), value); property.getParameters().add(param); if (param instanceof TzId && registry != null) { TimeZone timezone = registry.getTimeZone(param.getValue()); if (timezone != null) { try { ((DateProperty) property).setTimeZone(timezone); } catch (Exception e) { try { ((DateListProperty) property).setTimeZone(timezone); } catch (Exception e2) { log.warn("Error setting timezone [" + param + "] on property [" + property.getName() + "]", e); } } } } } } /* (non-Javadoc) * @see net.fortuna.ical4j.data.ContentHandler#propertyValue(java.lang.String) */ public void propertyValue(final String value) throws URISyntaxException, ParseException, IOException { if (property != null) { property.setValue(value); } } /* (non-Javadoc) * @see net.fortuna.ical4j.data.ContentHandler#startCalendar() */ public void startCalendar() { calendar = new Calendar(); } /* (non-Javadoc) * @see net.fortuna.ical4j.data.ContentHandler#startComponent(java.lang.String) */ public void startComponent(final String name) { if (component != null) { subComponent = ComponentFactory.getInstance().createComponent(name); } else { component = ComponentFactory.getInstance().createComponent(name); } } /* (non-Javadoc) * @see net.fortuna.ical4j.data.ContentHandler#startProperty(java.lang.String) */ public void startProperty(final String name) { // property names are case-insensitive, but convert to upper case to simplify further processing property = PropertyFactoryImpl.getInstance().createProperty(name.toUpperCase()); } /** * Returns the timezone registry used in the construction of calendars. * @return a timezone registry */ public final TimeZoneRegistry getRegistry() { return registry; } }
package org.exist.storage.journal; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.exist.storage.DBBroker; import javax.annotation.Nullable; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.SeekableByteChannel; import java.nio.file.Files; import java.nio.file.Path; import static java.nio.file.StandardOpenOption.READ; import static org.exist.storage.journal.Journal.LOG_ENTRY_BACK_LINK_LEN; import static org.exist.storage.journal.Journal.LOG_ENTRY_BASE_LEN; import static org.exist.storage.journal.Journal.LOG_ENTRY_HEADER_LEN; /** * Read log entries from the journal file. This class is used during recovery to scan the * last journal file. It uses a memory-mapped byte buffer on the file. * Journal entries can be read forward (during redo) or backward (during undo). * * @author wolf */ public class JournalReader implements AutoCloseable { private static final Logger LOG = LogManager.getLogger(JournalReader.class); private final DBBroker broker; private final int fileNumber; private final ByteBuffer header = ByteBuffer.allocateDirect(LOG_ENTRY_HEADER_LEN); private ByteBuffer payload = ByteBuffer.allocateDirect(8192); // 8 KB @Nullable private SeekableByteChannel fc; /** * Opens the specified file for reading. * * @param broker the database broker * @param file the journal file * @param fileNumber the number of the journal file * @throws LogException if the journal cannot be opened */ public JournalReader(final DBBroker broker, final Path file, final int fileNumber) throws LogException { this.broker = broker; this.fileNumber = fileNumber; try { this.fc = Files.newByteChannel(file, READ); } catch (final IOException e) { close(); throw new LogException("Failed to read journal file " + file.toAbsolutePath().toString(), e); } } /** * Returns the next entry found from the current position. * * @return the next entry, or null if there are no more entries. * @throws LogException if an entry could not be read due to an inconsistency on disk. */ public @Nullable Loggable nextEntry() throws LogException { try { checkOpen(); // are we at the end of the journal? if (fc.position() + LOG_ENTRY_BASE_LEN > fc.size()) { return null; } } catch (final IOException e) { throw new LogException("Unable to check journal position and size: " + e.getMessage(), e); } return readEntry(); } /** * Returns the previous entry found by scanning backwards from the current position. * * @return the previous entry, or null of there was no previous entry. * @throws LogException if an entry could not be read due to an inconsistency on disk. */ public @Nullable Loggable previousEntry() throws LogException { try { checkOpen(); // are we at the start of the journal? if (fc.position() == 0) { return null; } // go back two bytes and read the back-link of the last entry fc.position(fc.position() - LOG_ENTRY_BACK_LINK_LEN); header.clear().limit(LOG_ENTRY_BACK_LINK_LEN); final int bytes = fc.read(header); if (bytes < LOG_ENTRY_BACK_LINK_LEN) { throw new LogException("Unable to read journal entry back-link!"); } header.flip(); final short prevLink = header.getShort(); // position the channel to the start of the previous entry and mark it final long prevStart = fc.position() - LOG_ENTRY_BACK_LINK_LEN - prevLink; fc.position(prevStart); final Loggable loggable = readEntry(); // reset to the mark fc.position(prevStart); return loggable; } catch (final IOException e) { throw new LogException("Fatal error while reading previous journal entry: " + e.getMessage(), e); } } /** * Returns the last entry in the journal. * * @return the last entry in the journal, or null if there are no entries in the journal. * @throws LogException if an entry could not be read due to an inconsistency on disk. */ public @Nullable Loggable lastEntry() throws LogException { try { checkOpen(); fc.position(fc.size()); return previousEntry(); } catch (final IOException e) { throw new LogException("Fatal error while reading last journal entry: " + e.getMessage(), e); } } /** * Read the current entry from the journal. * * @return The entry, or null if there is no entry. * @throws LogException if an entry could not be read due to an inconsistency on disk. */ private @Nullable Loggable readEntry() throws LogException { try { final long lsn = Lsn.create(fileNumber, (int) fc.position() + 1); // read the entry header header.clear(); int bytes = fc.read(header); if (bytes <= 0) { return null; } if (bytes < LOG_ENTRY_HEADER_LEN) { throw new LogException("Incomplete journal entry header found, expected " + LOG_ENTRY_HEADER_LEN + " bytes, but found " + bytes + " bytes"); } header.flip(); final byte entryType = header.get(); final long transactId = header.getLong(); final short size = header.getShort(); if (fc.position() + size > fc.size()) { throw new LogException("Invalid length"); } final Loggable loggable = LogEntryTypes.create(entryType, broker, transactId); if (loggable == null) { throw new LogException("Invalid log entry: " + entryType + "; size: " + size + "; id: " + transactId + "; at: " + Lsn.dump(lsn)); } loggable.setLsn(lsn); if (size + LOG_ENTRY_BACK_LINK_LEN > payload.capacity()) { // resize the payload buffer payload = ByteBuffer.allocate(size + LOG_ENTRY_BACK_LINK_LEN); } payload.clear().limit(size + LOG_ENTRY_BACK_LINK_LEN); bytes = fc.read(payload); if (bytes < size + LOG_ENTRY_BACK_LINK_LEN) { throw new LogException("Incomplete log entry found!"); } payload.flip(); loggable.read(payload); final short prevLink = payload.getShort(); if (prevLink != size + LOG_ENTRY_HEADER_LEN) { LOG.error("Bad pointer to previous: prevLink = " + prevLink + "; size = " + size + "; transactId = " + transactId); throw new LogException("Bad pointer to previous in entry: " + loggable.dump()); } return loggable; } catch (final IOException e) { throw new LogException(e.getMessage(), e); } } /** * Re-position the file position so it points to the start of the entry * with the given LSN. * * @param lsn the log sequence number * @throws LogException if the journal file cannot be re-positioned */ public void position(final long lsn) throws LogException { try { checkOpen(); fc.position((int) Lsn.getOffset(lsn) - 1); } catch (final IOException e) { throw new LogException("Fatal error while seeking journal: " + e.getMessage(), e); } } private void checkOpen() throws IOException { if (fc == null) { throw new IOException("Journal file is closed"); } } @Override public void close() { try { if (fc != null) { fc.close(); } } catch (final IOException e) { LOG.warn(e.getMessage(), e); } fc = null; } }
package net.fortuna.ical4j.data; import java.io.IOException; import java.io.PushbackReader; import java.io.Reader; import java.util.Arrays; import net.fortuna.ical4j.util.CompatibilityHints; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * A reader which performs iCalendar unfolding as it reads. Note that unfolding rules may be "relaxed" to allow * unfolding of non-conformant *.ics files. By specifying the system property "ical4j.unfolding.relaxed=true" iCalendar * files created with Mozilla Calendar/Sunbird may be correctly unfolded. * @author Ben Fortuna */ public class UnfoldingReader extends PushbackReader { private Log log = LogFactory.getLog(UnfoldingReader.class); /** * The pattern used to identify a fold in an iCalendar data stream. */ private static final char[] DEFAULT_FOLD_PATTERN = { '\r', '\n', ' ' }; /** * The pattern used to identify a fold in Mozilla Calendar/Sunbird and KOrganizer. */ private static final char[] RELAXED_FOLD_PATTERN_1 = { '\n', ' ' }; /** * The pattern used to identify a fold in Microsoft Outlook 2007. */ private static final char[] RELAXED_FOLD_PATTERN_2 = { '\r', '\n', '\t' }; /** * The pattern used to identify a fold in Microsoft Outlook 2007. */ private static final char[] RELAXED_FOLD_PATTERN_3 = { '\n', '\t' }; private char[][] patterns; private char[][] buffers; private int linesUnfolded; /** * Creates a new unfolding reader instance. Relaxed unfolding flag is read from system property. * @param in the reader to unfold from */ public UnfoldingReader(final Reader in) { this(in, CompatibilityHints .isHintEnabled(CompatibilityHints.KEY_RELAXED_UNFOLDING)); } /** * Creates a new unfolding reader instance. * @param in a reader to read from * @param relaxed specifies whether unfolding is relaxed */ public UnfoldingReader(final Reader in, final boolean relaxed) { super(in, DEFAULT_FOLD_PATTERN.length); if (relaxed) { patterns = new char[4][]; patterns[0] = DEFAULT_FOLD_PATTERN; patterns[1] = RELAXED_FOLD_PATTERN_1; patterns[2] = RELAXED_FOLD_PATTERN_2; patterns[3] = RELAXED_FOLD_PATTERN_3; } else { patterns = new char[1][]; patterns[0] = DEFAULT_FOLD_PATTERN; } buffers = new char[patterns.length][]; for (int i = 0; i < patterns.length; i++) { buffers[i] = new char[patterns[i].length]; } } /** * @return number of lines unfolded so far while reading */ public final int getLinesUnfolded() { return linesUnfolded; } /** * @see java.io.PushbackReader#read() */ public final int read() throws IOException { int c = super.read(); boolean doUnfold = false; for (int i = 0; i < patterns.length; i++) { if (c == patterns[i][0]) { doUnfold = true; } } if (!doUnfold) { return c; } else { unread(c); } boolean didUnfold; // need to loop since one line fold might be directly followed by another do { didUnfold = false; for (int i = 0; i < buffers.length; i++) { int read = super.read(buffers[i]); if (read > 0) { if (!Arrays.equals(patterns[i], buffers[i])) { unread(buffers[i], 0, read); } else { if (log.isTraceEnabled()) { log.trace("Unfolding..."); } linesUnfolded++; didUnfold = true; } } else { return read; } } } while (didUnfold); return super.read(); } }
package com.lotsofun.farkle; import java.awt.Color; import java.awt.Dialog.ModalityType; import java.awt.Dimension; import java.awt.Font; import java.awt.GridLayout; import java.awt.Image; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Random; import javax.imageio.ImageIO; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.UnsupportedAudioFileException; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollBar; import javax.swing.JScrollPane; import javax.swing.ScrollPaneConstants; import javax.swing.SwingConstants; import javax.swing.event.MenuEvent; import javax.swing.event.MenuListener; public class FarkleUI extends JFrame { private static final long serialVersionUID = 1L; private Die[] dice = new Die[6]; private JButton rollBtn = new JButton("Roll Dice"); private JButton bankBtn = new JButton("Bank Score"); private JButton selectAllBtn = new JButton("Select All"); private FarkleController controller; private JLabel player1NameLabel = new JLabel("Player 1: "); private JLabel player1Name = new JLabel(""); private JLabel player2NameLabel = new JLabel("Player 2: "); private JLabel player2Name = new JLabel(""); private ArrayList<JLabel> player1ScoreLabels = new ArrayList<JLabel>(); private ArrayList<JLabel> player2ScoreLabels = new ArrayList<JLabel>(); private ArrayList<JLabel> player1Scores = new ArrayList<JLabel>(); private ArrayList<JLabel> player2Scores = new ArrayList<JLabel>(); private JLabel player1GameScoreLabel = new JLabel("Total Score: "); private JLabel player1GameScore = new JLabel("0"); private JLabel player2GameScoreLabel = new JLabel("Total Score: "); private JLabel player2GameScore = new JLabel("0"); private JLabel highScoreTitle = new JLabel("High Score: "); private JLabel highScore = new JLabel(); private JLabel runningScore = new JLabel("0"); private JLabel rollScore = new JLabel("0"); private ArrayList<URL> rollSounds = new ArrayList<URL>(); private ArrayList<URL> bankSounds = new ArrayList<URL>(); private URL bonusSound; private AudioInputStream audioStream = null; private Color greenBackground = new Color(35, 119, 34); private JDialog farkleMessage = new FarkleMessage(); private JPanel player1ScorePanel = null; private JScrollBar player1ScrollBar = null; private JPanel player2ScorePanel = null; private JScrollBar player2ScrollBar = null; private boolean isFirstRun = true; /** * Constructor Get a reference to the controller object and fire up the UI * * @param f */ public FarkleUI(FarkleController f) { controller = f; initUI(); } /** * Build the UI base */ public void initUI() { // Pass a reference to the controller if (isFirstRun) { isFirstRun = false; controller.setUI(this); // Instatiate necessary sounds getSounds(); // Create and set up the main Window this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setPreferredSize(new Dimension(1024, 768)); this.setResizable(false); this.pack(); // Center and display the window this.setLocationRelativeTo(null); } // Clear the content if this isn't the first init call this.getContentPane().removeAll(); GridLayout layout = new GridLayout(1, 3, 10, 10); // Hide the gridlines layout.setHgap(0); layout.setVgap(0); this.setLayout(layout); this.getContentPane().setBackground(greenBackground); this.setVisible(true); this.setEnabled(true); this.setVisible(true); // Add the menu bar this.setJMenuBar(createFarkleMenuBar()); // Call to create dice panel buildDicePanel(); // Call to create score panel createScoreGuidePanel(); // Tell the controller we're done controller.newGame(); pack(); } /** * Create a JPanel which contains two buttons and attach a Listener to each * * @return */ public JPanel[] createButtonPanel() { JPanel buttonPanels[] = { new JPanel(), new JPanel(), new JPanel() }; if (rollBtn.getActionListeners().length == 0) { rollBtn.addActionListener(controller); } buttonPanels[0].add(rollBtn); buttonPanels[0].setBackground(greenBackground); if (selectAllBtn.getActionListeners().length == 0) { selectAllBtn.addActionListener(controller); } buttonPanels[1].add(selectAllBtn); selectAllBtn.setEnabled(false); buttonPanels[1].setBackground(greenBackground); if (bankBtn.getActionListeners().length == 0) { bankBtn.addActionListener(controller); } buttonPanels[2].add(bankBtn); buttonPanels[2].setBackground(greenBackground); getBankBtn().setEnabled(false); return buttonPanels; } /** * Combine the diceHeader and diceGrid panels in to a single panel which can * be added to the frame * * @param diceHeaderPanel * @param diceGridPanel * @return */ public void buildDicePanel() { JPanel diceHeaderPanel = createDiceHeaderPanel(); JPanel diceGridPanel = createDiceGridPanel(); JPanel dicePanel = new JPanel(); dicePanel.setLayout(new BoxLayout(dicePanel, BoxLayout.Y_AXIS)); diceHeaderPanel.setBorder(BorderFactory .createLineBorder(Color.WHITE, 3)); dicePanel.add(diceHeaderPanel); diceGridPanel.setPreferredSize(diceGridPanel.getMaximumSize()); dicePanel.add(diceGridPanel); this.add(dicePanel); } /** * Create a JPanel to hold the Turn Score and Roll Score labels and their * corresponding values * * @return */ public JPanel createDiceHeaderPanel() { JPanel diceHeaderPanel = new JPanel(new GridLayout(0, 2, 0, 0)); JLabel turnScore = new JLabel("<html>Turn Score: </html>"); JLabel rollScoreLabel = new JLabel("<html>Roll Score: </html>"); turnScore.setForeground(Color.WHITE); turnScore.setFont(new Font("Arial Black", Font.BOLD, 14)); turnScore.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createMatteBorder(0, 0, 1, 0, Color.WHITE), BorderFactory.createEmptyBorder(15, 3, 15, 0))); diceHeaderPanel.add(turnScore); runningScore.setForeground(Color.WHITE); runningScore.setFont(new Font("Arial Black", Font.BOLD, 14)); runningScore.setHorizontalAlignment(SwingConstants.CENTER); runningScore.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createMatteBorder(0, 0, 1, 0, Color.WHITE), BorderFactory.createEmptyBorder(15, 0, 15, 3))); diceHeaderPanel.add(runningScore); rollScoreLabel.setForeground(Color.WHITE); rollScoreLabel.setFont(new Font("Arial Black", Font.BOLD, 14)); rollScoreLabel.setBorder(BorderFactory.createMatteBorder(0, 3, 0, 0, Color.WHITE)); rollScoreLabel.setBorder(BorderFactory.createEmptyBorder(15, 3, 15, 0)); diceHeaderPanel.add(rollScoreLabel); rollScore.setForeground(Color.WHITE); rollScore.setFont(new Font("Arial Black", Font.BOLD, 14)); rollScore.setHorizontalAlignment(SwingConstants.CENTER); rollScore.setBorder(BorderFactory.createMatteBorder(0, 0, 0, 3, Color.WHITE)); rollScore.setBorder(BorderFactory.createEmptyBorder(15, 0, 15, 3)); diceHeaderPanel.add(rollScore); diceHeaderPanel.setBackground(greenBackground); return diceHeaderPanel; } /** * Create a JPanel with six Dice, the running score JLabels and the Roll and * Bank buttons * * @return */ public JPanel createDiceGridPanel() { // Create the panel JPanel dicePanel = new JPanel(new GridLayout(0, 3, 0, 0)); // Initialize the dice and add to panel for (int i = 0; i < dice.length; i++) { dice[i] = new Die(controller); dicePanel.add(new JLabel(" ")); dicePanel.add(dice[i]); dice[i].setHorizontalAlignment(SwingConstants.CENTER); dicePanel.add(new JLabel(" ")); } dicePanel.add(new JLabel(" ")); dicePanel.add(new JLabel(" ")); dicePanel.add(new JLabel(" ")); // Call to add buttons and satisfy // requirements 1.3.4 and 1.3.5 JPanel btns[] = createButtonPanel(); dicePanel.add(btns[0]); dicePanel.add(btns[1]); dicePanel.add(btns[2]); dicePanel.setBackground(greenBackground); dicePanel.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createLineBorder(Color.WHITE, 3), BorderFactory.createEmptyBorder(3, 17, 3, 17))); return dicePanel; } public void buildPlayerPanel(GameMode gameMode) { JPanel playersPanel = new JPanel(); playersPanel.setLayout(new BoxLayout(playersPanel, BoxLayout.Y_AXIS)); playersPanel.setBorder(BorderFactory.createLineBorder(Color.WHITE, 3)); if (null != gameMode && gameMode == GameMode.SINGLEPLAYER) { // Create and add the name and score panels for player 1 JScrollPane player1ScrollPanel = createPlayerScorePanel(1, 10); player1ScrollBar = player1ScrollPanel.getVerticalScrollBar(); player1ScrollPanel.setBorder(BorderFactory.createEmptyBorder()); playersPanel.add(createPlayerNamePanel(1)); player1ScrollPanel.setPreferredSize(new Dimension(350, 568)); playersPanel.add(player1ScrollPanel); } else if (null != gameMode && gameMode == GameMode.MULTIPLAYER) { // Create and add the name and score panels for player 1 JScrollPane player1ScrollPanel = createPlayerScorePanel(1, 5); player1ScrollBar = player1ScrollPanel.getVerticalScrollBar(); player1ScrollPanel.setBorder(BorderFactory.createEmptyBorder()); player1ScrollPanel.setPreferredSize(new Dimension(350, 249)); playersPanel.add(createPlayerNamePanel(1)); playersPanel.add(player1ScrollPanel); // Create and add the name and score panels for player 2 JScrollPane player2ScrollPanel = createPlayerScorePanel(2, 5); player2ScrollBar = player2ScrollPanel.getVerticalScrollBar(); player2ScrollPanel.setBorder(BorderFactory.createEmptyBorder()); player2ScrollPanel.setPreferredSize(new Dimension(350, 249)); playersPanel.add(createPlayerNamePanel(2)); playersPanel.add(player2ScrollPanel); playersPanel.setBackground(greenBackground); } addHighScore(playersPanel); playersPanel.setBackground(greenBackground); this.add(playersPanel, 0); } private JPanel createPlayerNamePanel(int playerNumber) { JPanel playerNamePanel = new JPanel(new GridLayout(0, 2, 0, 0)); JLabel playerNameLabel = (playerNumber == 1) ? player1NameLabel : player2NameLabel; JLabel playerName = (playerNumber == 1) ? player1Name : player2Name; JLabel playerGameScoreLabel = (playerNumber == 1) ? player1GameScoreLabel : player2GameScoreLabel; JLabel playerGameScore = (playerNumber == 1) ? player1GameScore : player2GameScore; playerNameLabel.setForeground(Color.WHITE); playerNameLabel.setFont(new Font("Arial Black", Font.BOLD, 14)); if (playerNumber == 1) { playerNameLabel.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createMatteBorder(0, 0, 1, 0, Color.WHITE), BorderFactory.createEmptyBorder(12, 3, 15, 0))); } else { playerNameLabel.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createMatteBorder(6, 0, 1, 0, Color.WHITE), BorderFactory.createEmptyBorder(12, 3, 15, 0))); } playerNamePanel.add(playerNameLabel); playerName.setForeground(Color.WHITE); playerName.setFont(new Font("Arial Black", Font.BOLD, 14)); if (playerNumber == 1) { playerName.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createMatteBorder(0, 0, 1, 0, Color.WHITE), BorderFactory.createEmptyBorder(17, 3, 15, 3))); } else { playerName.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createMatteBorder(6, 0, 1, 0, Color.WHITE), BorderFactory.createEmptyBorder(17, 3, 15, 3))); } playerNamePanel.add(playerName); playerGameScoreLabel.setForeground(Color.WHITE); playerGameScoreLabel.setFont(new Font("Arial Black", Font.BOLD, 14)); playerGameScoreLabel.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createMatteBorder(0, 0, 6, 0, Color.WHITE), BorderFactory.createEmptyBorder(15, 3, 15, 3))); playerNamePanel.add(playerGameScoreLabel); playerGameScore.setForeground(Color.WHITE); playerGameScore.setFont(new Font("Arial Black", Font.BOLD, 14)); playerGameScore.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createMatteBorder(0, 0, 6, 0, Color.WHITE), BorderFactory.createEmptyBorder(15, 3, 15, 3))); playerNamePanel.add(playerGameScore); playerNamePanel.setBackground(greenBackground); playerNamePanel.setPreferredSize(new Dimension(350, 110)); playerNamePanel.setMaximumSize(new Dimension(350, 110)); return playerNamePanel; } /** * Create a new JPanel that contains all the JLabels necessary to represent * a player with 10 turns * * @param playerName * @param playerNumber * @return */ private JScrollPane createPlayerScorePanel(int playerNumber, int scoreLabelCount) { JPanel playerPanel = new JPanel(new GridLayout(0, 2, 0, 2)); if (playerNumber == 1) { player1ScorePanel = playerPanel; } else { player2ScorePanel = playerPanel; } for (int i = 0; i < scoreLabelCount; i++) { addTurnScore(playerNumber, i + 1); } playerPanel.setBackground(greenBackground); playerPanel.setBorder(BorderFactory.createEmptyBorder(3, 17, 3, 17)); JScrollPane playerScrollPane = new JScrollPane(playerPanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); return playerScrollPane; } public void addHighScore(JPanel panel) { JPanel highScorePanel = new JPanel(new GridLayout(0, 2, 0, 0)); highScoreTitle.setForeground(Color.WHITE); highScoreTitle.setFont(new Font("Arial Black", Font.BOLD, 14)); highScorePanel.add(highScoreTitle); highScore.setForeground(Color.WHITE); highScore.setFont(new Font("Arial Black", Font.BOLD, 14)); highScorePanel.add(highScore); highScorePanel.setBackground(greenBackground); highScorePanel.setMaximumSize(new Dimension(350, 50)); highScorePanel.setBorder(BorderFactory.createMatteBorder(6, 0, 0, 0, Color.WHITE)); panel.add(highScorePanel); } public void addTurnScore(int playerNumber, int turnNumber) { ArrayList<JLabel> playerScoreLabels = (playerNumber == 1) ? player1ScoreLabels : player2ScoreLabels; ArrayList<JLabel> playerScores = (playerNumber == 1) ? player1Scores : player2Scores; JPanel playerPanel = (playerNumber == 1) ? player1ScorePanel : player2ScorePanel; // Add the labels for each turn JLabel turnLabel = new JLabel("Roll " + (turnNumber) + ": "); turnLabel.setForeground(Color.WHITE); turnLabel.setFont(new Font("Arial Black", Font.BOLD, 14)); turnLabel.setMaximumSize(new Dimension(175, 20)); turnLabel.setPreferredSize(new Dimension(175, 20)); playerScoreLabels.add(turnLabel); playerPanel.add(playerScoreLabels.get(turnNumber - 1)); // Add the score label for each turn JLabel turnScoreLabel = new JLabel(); turnScoreLabel.setForeground(Color.WHITE); turnScoreLabel.setFont(new Font("Arial Black", Font.BOLD, 14)); turnLabel.setMaximumSize(new Dimension(175, 20)); turnLabel.setPreferredSize(new Dimension(175, 20)); playerScores.add(turnScoreLabel); playerPanel.add(playerScores.get(turnNumber - 1)); } /** * Create a new JPanel that displays the score guide image * * @return JLabel */ private void createScoreGuidePanel() { JPanel scorePanel = new JPanel(); try { Image scoreGuide = ImageIO.read(getClass().getResource( "/images/FarkleScores.png")); scoreGuide = scoreGuide.getScaledInstance(200, 680, Image.SCALE_SMOOTH); JLabel scoreLabel = new JLabel(new ImageIcon(scoreGuide)); scorePanel.add(scoreLabel); scorePanel.setBackground(greenBackground); } catch (IOException e) { e.printStackTrace(); System.exit(0); } scorePanel.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createLineBorder(Color.WHITE, 3), BorderFactory.createEmptyBorder(3, 17, 3, 17))); this.add(scorePanel); } public JButton getRollBtn() { return rollBtn; } public JButton getBankBtn() { return bankBtn; } public JButton getSelectAllBtn() { return selectAllBtn; } public void setGameScore(int playerNumber, int score) { JLabel gameScore = (playerNumber == 1) ? player1GameScore : player2GameScore; gameScore.setText("" + score); } public void setHighScore(int score) { this.highScore.setText("" + score); } public int getRunningScore() { try { return Integer.valueOf(runningScore.getText()); } catch(NumberFormatException e) { e.printStackTrace(); throw e; } } public void rollDice() { // Test farkle roll /*dice[0].setValue('f'); dice[1].setValue('a'); dice[2].setValue('r'); dice[3].setValue('k'); dice[4].setValue('l'); dice[5].setValue('e');*/ // Roll all the dice for (Die d : dice) { d.roll(); } } /** * Get the dice with the specified DieStates * * @param dieState * One or more DieState types * @return the dice with the specified DieStates */ public ArrayList<Die> getDice(DieState... dieState) { ArrayList<DieState> dieStates = new ArrayList<DieState>(); for (DieState state : dieState) { dieStates.add(state); } ArrayList<Die> retDice = new ArrayList<Die>(); for (Die d : dice) { if (dieStates.contains(d.getState())) { retDice.add(d); } } return retDice; } /** * Get the values from the dice with the specified DieStates * * @param dieState * One or more DieState types * @return List<Integer> values from the dice with the specified DieStates */ public List<Integer> getDieValues(DieState... dieState) { List<Integer> retVals = new ArrayList<Integer>(); ArrayList<Die> diceToCheck = getDice(dieState); for (Die d : diceToCheck) { retVals.add(d.getValue()); } return retVals; } /** * Set all six dice back to 0 and their states back to UNHELD */ public void resetDice() { for (Die d : dice) { d.setState(DieState.UNHELD); } } /** * Prevents dice from being selected */ public void disableDice() { for (Die d : dice) { d.setState(DieState.DISABLED); } } public void resetDicePanel() { resetDice(); this.rollBtn.setEnabled(true); this.selectAllBtn.setEnabled(false); this.bankBtn.setEnabled(false); } public void diceFirstRun() { dice[0].setValue('f'); dice[1].setValue('a'); dice[2].setValue('r'); dice[3].setValue('k'); dice[4].setValue('l'); dice[5].setValue('e'); } public void resetScores(int playerNumber) { ArrayList<JLabel> scores = getPlayerScores(playerNumber); for (JLabel score : scores) { score.setText(""); } } /** * Update all dice with a HELD state to a SCORED state */ public void lockScoredDice() { for (Die d : dice) { if (d.getState() == DieState.HELD) { d.setState(DieState.SCORED); } } } /** * Update the turn label for the specified player with the specified score * TODO: Is turn an index here or not? * * @param int player * @param int turn * @param int score */ public void setTurnScore(int player, int turn, int score) { ArrayList<JLabel> scores = getPlayerScores(player); scores.get(turn - 1).setText("" + score); } /** * Update the running score label with the specified score * * @param int score */ public void setRunningScore(int score) { runningScore.setText("" + score); } public void setRollScore(int score) { rollScore.setText("" + score); } /** * Randomly return one of the four dice roll sounds * * @return */ public void playRollSound() { try { audioStream = AudioSystem.getAudioInputStream(rollSounds .get(new Random().nextInt(3))); Clip clip = AudioSystem.getClip(); clip.open(audioStream); clip.start(); } catch (UnsupportedAudioFileException e) { e.printStackTrace(); } catch (LineUnavailableException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public void playBonusSound() { try { audioStream = AudioSystem.getAudioInputStream(bonusSound); Clip clip = AudioSystem.getClip(); clip.open(audioStream); clip.start(); } catch (UnsupportedAudioFileException e) { e.printStackTrace(); } catch (LineUnavailableException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public void playBankSound() { try { audioStream = AudioSystem.getAudioInputStream(bankSounds .get(new Random().nextInt(3))); Clip clip = AudioSystem.getClip(); clip.open(audioStream); clip.start(); } catch (UnsupportedAudioFileException e) { e.printStackTrace(); } catch (LineUnavailableException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * Display a message to the user via JOptionPane * * @param message * - Message to be displayed in the main box. * @param title * - Title of the JOptionPane window. * */ @SuppressWarnings("deprecation") public void displayMessage(String message, String title) { JOptionPane pane = new JOptionPane(message); JDialog dialog = pane.createDialog(title); dialog.setModalityType(ModalityType.APPLICATION_MODAL); dialog.show(); } public boolean displayYesNoMessage(String message, String title) { boolean retVal; int dialogResult = JOptionPane.showConfirmDialog(this, message, title, JOptionPane.YES_NO_OPTION); if (dialogResult == JOptionPane.YES_OPTION) { retVal = true; } else { retVal = false; } return retVal; } @Override public void dispose() { super.dispose(); System.exit(0); } public void selectDice(List<Integer> valuesNeeded) throws InterruptedException { List<Die> dice = getDice(DieState.UNHELD); for (Die d : dice) { for (Integer i : valuesNeeded) { if (d.getValue() == i) { Thread.sleep(500); d.dispatchEvent(new MouseEvent(d, MouseEvent.MOUSE_PRESSED, System.currentTimeMillis(), MouseEvent.BUTTON1, d .getX(), d.getY(), 1, false)); valuesNeeded.remove(i); break; } } } Thread.sleep(1500); } /** * If no dice are held, selects all unheld dice If no dice are unheld, * selects all held dice */ public void selectAllDice() { if (getDice(DieState.HELD).size() == 0) { ArrayList<Die> dice = getDice(DieState.UNHELD); for (Die d : dice) { d.dispatchEvent(new MouseEvent(d, MouseEvent.MOUSE_PRESSED, System.currentTimeMillis(), MouseEvent.BUTTON1, d .getX(), d.getY(), 1, false)); } } else { ArrayList<Die> dice = getDice(DieState.HELD); for (Die d : dice) { d.dispatchEvent(new MouseEvent(d, MouseEvent.MOUSE_PRESSED, System.currentTimeMillis(), MouseEvent.BUTTON1, d .getX(), d.getY(), 1, false)); } } } public void setPlayerName(int playerNumber, String name) { if (null != name && playerNumber >= 1 && playerNumber <= 2) { if (playerNumber == 1) { this.player1Name.setText(name); } else { this.player2Name.setText(name); } } } public void unHighlightAllTurnScores(int playerNumber) { // Get the labels and their scores for the given player ArrayList<JLabel> scoreLabels = getPlayerScoreLabels(playerNumber); ArrayList<JLabel> scores = getPlayerScores(playerNumber); // Make sure it's a 1:1 relationship assert (scoreLabels.size() == scores.size()); // Unhighlight each set for (int i = 0; i < scoreLabels.size(); i++) { unHighlightTurn(scoreLabels.get(i), scores.get(i)); } } public void highlightTurnScore(int playerNumber, int turn, boolean isBonusTurn) { // Unhighlight all turns unHighlightAllTurnScores(playerNumber); // Get the labels and their scores for the given player ArrayList<JLabel> scoreLabels = getPlayerScoreLabels(playerNumber); ArrayList<JLabel> scores = getPlayerScores(playerNumber); if (turn > 0 && turn > scoreLabels.size()) { addTurnScore(playerNumber, turn); } // Highlight the desired turn highlightTurn(scoreLabels.get(turn - 1), scores.get(turn - 1), isBonusTurn); // Scroll to the bottom of the panel; JScrollBar playerScrollBar = (playerNumber == 1) ? player1ScrollBar : player2ScrollBar; if (null != playerScrollBar) { playerScrollBar.getParent().validate(); playerScrollBar.setValue(playerScrollBar.getMaximum()); } } public void unHighlightTurn(JLabel scoreLabel, JLabel score) { scoreLabel.setOpaque(false); scoreLabel.setForeground(Color.WHITE); score.setOpaque(false); score.setForeground(Color.WHITE); } public void highlightTurn(JLabel scoreLabel, JLabel score, boolean isBonusTurn) { // Highlight given turn in white if it's not a bonus turn if (!isBonusTurn) { scoreLabel.setOpaque(true); scoreLabel.setBackground(Color.WHITE); scoreLabel.setForeground(Color.BLACK); score.setOpaque(true); score.setBackground(Color.WHITE); score.setText(""); score.setForeground(Color.BLACK); } else { // Else highlight given turn yellow for bonus turn scoreLabel.setOpaque(true); scoreLabel.setBackground(Color.YELLOW); scoreLabel.setForeground(Color.BLACK); score.setOpaque(true); score.setText("BONUS ROLL!"); score.setBackground(Color.YELLOW); score.setForeground(Color.BLACK); } } public ArrayList<JLabel> getPlayerScoreLabels(int playerNumber) { ArrayList<JLabel> scoreLabels = (playerNumber == 1) ? player1ScoreLabels : player2ScoreLabels; return scoreLabels; } public ArrayList<JLabel> getPlayerScores(int playerNumber) { ArrayList<JLabel> scores = (playerNumber == 1) ? player1Scores : player2Scores; return scores; } private void getSounds() { // Initialize the sounds rollSounds.add(getClass().getResource("/sounds/roll1.wav")); rollSounds.add(getClass().getResource("/sounds/roll2.wav")); rollSounds.add(getClass().getResource("/sounds/roll3.wav")); rollSounds.add(getClass().getResource("/sounds/roll4.wav")); bankSounds.add(getClass().getResource("/sounds/bank1.wav")); bankSounds.add(getClass().getResource("/sounds/bank2.wav")); bankSounds.add(getClass().getResource("/sounds/bank3.wav")); bankSounds.add(getClass().getResource("/sounds/bank4.wav")); bonusSound = getClass().getResource("/sounds/bonus.wav"); } public JMenuBar createFarkleMenuBar() { // Menu Bar JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenu fileMenu = new JMenu("File"); menuBar.add(fileMenu); final JMenuItem hintAction = new JMenuItem("Hint"); final JMenuItem newAction = new JMenuItem("New Game"); final JMenuItem resetAction = new JMenuItem("Reset Game"); final JMenuItem resetHighScoreAction = new JMenuItem("Reset High Score"); final JMenuItem exitAction = new JMenuItem("Exit"); fileMenu.add(hintAction); fileMenu.add(newAction); fileMenu.add(resetAction); fileMenu.add(resetHighScoreAction); fileMenu.add(exitAction); fileMenu.addMenuListener(new MenuListener() { @Override public void menuSelected(MenuEvent e) { hintAction.setEnabled(controller.isHintAvailable()); } @Override public void menuDeselected(MenuEvent e) { } @Override public void menuCanceled(MenuEvent e) { } }); if (newAction.getActionListeners().length == 0) { newAction.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { controller.endGame(false, true); } }); } if (resetAction.getActionListeners().length == 0) { resetAction.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { controller.endGame(true, false); } }); } if(resetHighScoreAction.getActionListeners().length == 0) { resetHighScoreAction.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { controller.resetHighScore(); } }); } if (exitAction.getActionListeners().length == 0) { exitAction.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { FarkleUI.this.dispose(); } }); } if (hintAction.getActionListeners().length == 0) { hintAction.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { List<Integer> highestScoringDieValues = controller.getHighestScoringDieValues(); if (highestScoringDieValues.size() != 0) { displayMessage("Select " + highestScoringDieValues + " to score " + controller.getHighestPossibleScore() + " points.", "Hint"); } } }); } return menuBar; } public JDialog getFarkleMessage() { return farkleMessage; } public String getRollBtnText() { return this.rollBtn.getText(); } }
package am.app.ontology; import java.util.ArrayList; import java.util.HashMap; import am.GlobalStaticVariables; import am.app.mappingEngine.AbstractMatcher.alignType; import am.app.mappingEngine.qualityEvaluation.JoslynStructuralQuality; import am.userInterface.sidebar.vertex.Vertex; import com.hp.hpl.jena.ontology.DatatypeProperty; import com.hp.hpl.jena.ontology.ObjectProperty; import com.hp.hpl.jena.ontology.OntModel; import com.hp.hpl.jena.ontology.OntResource; /** * This class contains all information about one of the two ontologies to be compared * You get access to it via the Core instance * */ public class Ontology { public static final int ID_NONE = -1; // used when there is no ontology id. /** * <p>It may be SOURCE or TARGET. Use the final static int values in GSV to set this. (GlobalStaticVariables.SOURCENODE or GlobalStaticVariables.TARGETNODE)</p> * <p>TODO: Change this to an enum.</p> * */ private int sourceOrTarget; private String filename;//file name with all the path private String title;//usually is the name of the file without the path and is the name of the root vertex /**It may be XML, OWL, RDF*/ private String language; /**For example RDF/XML for OWL language, in XML lanaguage is null*/ private String format; /**reference to the Jena model class, for an OWL ontology it may be an OntModel, right now we don't use this element, in XML lanaguage is null*/ private OntModel model; /**List of class nodes to be aligned, IN THE CASE OF AN XML OR RDF ONTOLOGY ALL NODES ARE KEPT IN THIS STRUCTURE, so there will be only classes and no properties*/ private ArrayList<Node> classesList = new ArrayList<Node>(); /**List of property nodes to be aligned, IN THE CASE OF AN XML OR RDF ONTOLOGY there are no properties*/ private ArrayList<Node> propertiesList = new ArrayList<Node>(); /**The root of the classes hierarchy, is not the root of the whole tree but is the second node, the root vertex itself is fake doesn't refers to any node to be aligned, all sons of this node are classes to be aligned*/ private Vertex classesTree;//in a XML or RDF ontology this will be the only tree /**The root of the properties hierarchy, is not the root of the whole tree but is the third node, the root vertex itself is fake doesn't refers to any node to be aligned, all sons of this node are classes to be aligned*/ private Vertex propertiesTree;//in a XML or RDF ontology this will be null, while in a OWL ontology it contains at least the fake root "prop hierarchy" private Vertex deepRoot; // for the Canvas private boolean skipOtherNamespaces; private String URI; private ArrayList<DatatypeProperty> dataProperties; public ArrayList<DatatypeProperty> getDataProperties() { return dataProperties; } public void setDataProperties(ArrayList<DatatypeProperty> dtps) { dataProperties = dtps; } private ArrayList<ObjectProperty> objectProperties; public ArrayList<ObjectProperty> getObjectProperties() { return objectProperties; } public void setObjectProperties(ArrayList<ObjectProperty> ops) { objectProperties = ops; } //END Instance related fields and functions /** * This value is not used in the AM system right now, it is only used in the Conference Track when more than two ontologies are involved in the process. */ private int Index = 0; // TODO: Maybe get rid of index, and work only with ID? private int ontID = 0; // Index is used in the conference track, ID is used system wide. private int treeCount; public int getIndex() { return Index; } public void setIndex(int index) { Index = index; } public int getID() { return ontID; } public void setID(int id) { ontID = id; } public String getURI() { return URI; } public void setURI(String uri) { URI = uri; } public String getFilename() { return filename; } public void setFilename(String filename) { this.filename = filename; } public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } public String getFormat() { return format; } public void setFormat(String format) { this.format = format; } public OntModel getModel() { return model; } public void setModel(OntModel model) { this.model = model; } public ArrayList<Node> getClassesList() { return classesList; } public void setClassesList(ArrayList<Node> classesList) { this.classesList = classesList; } public ArrayList<Node> getPropertiesList() { return propertiesList; } public void setPropertiesList(ArrayList<Node> propertiesList) { this.propertiesList = propertiesList; } public boolean isSource() { return sourceOrTarget == GlobalStaticVariables.SOURCENODE; } public boolean isTarget() { return sourceOrTarget == GlobalStaticVariables.TARGETNODE; } public void setSourceOrTarget(int s) { sourceOrTarget = s; } public Vertex getClassesTree() { return classesTree; } public void setClassesTree(Vertex classesTree) { this.classesTree = classesTree; } public Vertex getDeepRoot() { return deepRoot; } public void setDeepRoot(Vertex root) { this.deepRoot = root; } public Vertex getPropertiesTree() { return propertiesTree; } public void setPropertiesTree(Vertex propertiesTree) { this.propertiesTree = propertiesTree; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } //used in UImenu.ontologyDetails() public String getClassDetails() { return getDetails(classesList, classesTree); } //used in getClassDetails and getPropDetails private String getDetails(ArrayList<Node> list, Vertex tree) { TreeToDagConverter conv = new TreeToDagConverter(tree); int concepts = list.size(); int depth = tree.getDepth()-1; int roots = conv.getRoots().size(); int leaves = conv.getLeaves().size(); JoslynStructuralQuality q = new JoslynStructuralQuality(true, true, false); //the first two boolean dont matter here double LCdiameter = q.getDiameter(list, conv); JoslynStructuralQuality q2 = new JoslynStructuralQuality(true, true, true); //the first two boolean dont matter here double UCdiameter = q2.getDiameter(list, conv); return concepts+"\t"+depth+"\t"+UCdiameter+"\t"+LCdiameter+"\t"+roots+"\t"+leaves+"\n"; } //used in UImenu.ontologyDetails() public String getPropDetails() { return getDetails(propertiesList, propertiesTree); } public boolean isSkipOtherNamespaces() { return skipOtherNamespaces; } public void setSkipOtherNamespaces(boolean skipOtherNamespaces) { this.skipOtherNamespaces = skipOtherNamespaces; } public int getSourceOrTarget() { return sourceOrTarget; } public void setTreeCount(int treeCount) { this.treeCount = treeCount; } public int getTreeCount() { return treeCount; } // used for mapping from OntResource to Nodes private HashMap<OntResource, Node> mapOntResource2Node_Classes = null; private HashMap<OntResource, Node> mapOntResource2Node_Properties = null; public void setOntResource2NodeMap(HashMap<OntResource, Node> processedSubs, alignType atype) { if( atype == alignType.aligningClasses ) { mapOntResource2Node_Classes = processedSubs; } else if( atype == alignType.aligningProperties ) { mapOntResource2Node_Properties = processedSubs; } } public Node getNodefromOntResource( OntResource r, alignType nodeType ) throws Exception { if( r == null ) { throw new Exception("Cannot search for a NULL resource."); } if( nodeType == alignType.aligningClasses ) { if( mapOntResource2Node_Classes.containsKey( r ) ){ return mapOntResource2Node_Classes.get(r); } else { throw new Exception("OntResource (" + r.toString() + ") is not a class in Ontology " + ontID + " (" + title + ")."); } } else if( nodeType == alignType.aligningProperties ) { if( mapOntResource2Node_Properties.containsKey( r ) ){ return mapOntResource2Node_Properties.get(r); } else { throw new Exception("OntResource (" + r.toString() + ") is not a property in Ontology " + ontID + " (" + title + ")."); } } throw new Exception("Cannot search for nodeType == " + nodeType.toString() ); } public Node getNodefromIndex( int index, alignType aType ) throws Exception { if( aType == alignType.aligningClasses ) { if( index < classesList.size() ){ return classesList.get(index); } } else if( aType == alignType.aligningProperties ) { if( index < propertiesList.size() ){ return propertiesList.get(index); } } throw new Exception("Cannot search for nodeType == " + aType.toString() ); } }
package ch.ntb.inf.deep.eclipse.ui.wizard; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.FileWriter; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.net.MalformedURLException; import java.net.URL; import java.util.Calendar; import java.util.GregorianCalendar; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IProjectDescription; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.ProjectScope; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.core.runtime.preferences.IEclipsePreferences; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.wizard.Wizard; import org.eclipse.ui.INewWizard; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.actions.WorkspaceModifyOperation; import org.osgi.service.prefs.BackingStoreException; import ch.ntb.inf.deep.eclipse.DeepPlugin; public class StartWizard extends Wizard implements INewWizard{ private WizPage1 wizPage1; private WizPage2 wizPage2; private IProject project; /* * (non-Javadoc) * * @see org.eclipse.jface.wizard.Wizard#performFinish() */ @Override public boolean performFinish() { try { getContainer().run(false, true, new WorkspaceModifyOperation() { @Override protected void execute(IProgressMonitor monitor) { createProject(monitor != null ? monitor : new NullProgressMonitor()); } }); } catch (InvocationTargetException x) { reportError(x); return false; } catch (InterruptedException x) { reportError(x); return false; } save(); dispose(); return true; } /* * (non-Javadoc) * * @see org.eclipse.ui.IWorkbenchWizard#init(org.eclipse.ui.IWorkbench, * org.eclipse.jface.viewers.IStructuredSelection) */ @Override public void init(IWorkbench workbench, IStructuredSelection selection) { setWindowTitle("NTB Project Wizard"); setDefaultPageImageDescriptor(getImageDescriptor("deep.gif")); setNeedsProgressMonitor(true); } public void addPages() { wizPage1 = new WizPage1("Start Page"); wizPage1.setTitle("Target configuration"); wizPage1.setDescription("Please choose your processor"); addPage(wizPage1); wizPage2 = new WizPage2("Second Page"); wizPage2.setTitle("Projectname"); wizPage2.setDescription("Please define your projectname"); addPage(wizPage2); } private ImageDescriptor getImageDescriptor(String relativePath) { String iconPath = "icons/full/obj16/"; try { DeepPlugin plugin = DeepPlugin.getDefault(); URL installURL = plugin.getBundle().getEntry("/"); URL url; url = new URL(installURL, iconPath + relativePath); return ImageDescriptor.createFromURL(url); } catch (MalformedURLException e) { e.printStackTrace(); return null; } } private InputStream getFileContent() { String libpath; if(wizPage1.useDefaultLibPath()){ libpath = wizPage1.getDefaultLibPath(); }else{ libpath = wizPage1.getChosenLibPath(); } StringBuffer sb = new StringBuffer(); sb.append("<?xml version=\"1.0\" encoding =\"UTF-8\"?>\n"); sb.append("<classpath>\n"); sb.append("\t<classpathentry kind=\"src\" path=\"src\"/>\n"); sb.append("\t<classpathentry kind=\"con\" path=\"org.eclipse.jdt.launching.JRE_CONTAINER\"/>\n"); sb.append("\t<classpathentry kind=\"lib\" path=\"" + libpath + "/bin\"/>\n"); sb.append("\t<classpathentry kind=\"output\" path=\"bin\"/>\n"); sb.append("</classpath>\n"); return new ByteArrayInputStream(sb.toString().getBytes()); } private void createClassPath(IProject project) { IFile file = project.getFile(".classpath"); try { file.create(getFileContent(), true, null); } catch (CoreException e) { e.printStackTrace(); } } private void createDeepFile(){ IFile file = project.getFile(project.getName() +".deep"); try{ file.create(getDeepFileContent(), false, null); } catch(CoreException e){ e.printStackTrace(); } } private InputStream getDeepFileContent(){ String board, processor, rts; GregorianCalendar cal = new GregorianCalendar(); StringBuffer sb = new StringBuffer(); sb.append("#deep-0\n\nmeta {\n\tversion = \"" + cal.getTime() +"\";\n"); sb.append("\tdescription = \"Deep project file for " + project.getName() + "\";\n"); sb.append("\timport = "); processor = wizPage1.getProcessorValue(); board = wizPage1.getBoardValue(); rts = wizPage1.getRunTimeSystemValue(); if(processor.equals("MPC555")){ if(board.equals("NTB MPC555 Headerboard")){ sb.append("\"config/ntbMpc555HB.deep\""); if(rts.equals("Simple tasking system")){ sb.append(", \"config/ntbMpc555STS.deep\""); }else if(rts.equals("uCos")){ sb.append(", \"config/ntbMpc555uCOS.deep\""); } }else if(board.equals("phyCORE-mpc555")){ sb.append("\"config/phyMpc555Core.deep\""); if(rts.equals("Simple tasking system")){ sb.append(", \"config/ntbMpc555STS.deep\""); }else if(rts.equals("uCos")){ sb.append(", \"config/ntbMpc555uCOS.deep\""); } } sb.append(";\n}\n\n"); }else{ sb.append("\"\";\n}\n\n"); } sb.append("project {\n\tlibpath = "); if(wizPage1.useDefaultLibPath()){ sb.append("\"" + wizPage1.getDefaultLibPath() + "\";\n"); }else{ sb.append("\"" + wizPage1.getChosenLibPath() + "\";\n"); } sb.append("\trootclasses = \"\";\n}\n"); return new ByteArrayInputStream(sb.toString().getBytes()); } private void createFolders(IProject project) { IFolder scrFolder = project.getFolder("src"); IFolder binFolder = project.getFolder("bin"); try { scrFolder.create(true, true, null); binFolder.create(true, true, null); } catch (CoreException e) { e.printStackTrace(); } } private void createProject(IProgressMonitor monitor) { monitor.beginTask("Creating project", 20); IWorkspace workspace = ResourcesPlugin.getWorkspace(); project = wizPage2.getProjectHandle(); IProjectDescription description = workspace.newProjectDescription(project.getName()); if (!Platform.getLocation().equals(wizPage2.getLocationPath())) { description.setLocation(wizPage2.getLocationPath()); } try { project.create(description, monitor); monitor.worked(10); if (project.exists()) { project.open(monitor); project.refreshLocal(IResource.DEPTH_INFINITE, monitor); } else { return; } description = project.getDescription(); description.setNatureIds(new String[] {"ch.ntb.inf.deep.nature.DeepNature", "org.eclipse.jdt.core.javanature" }); project.setDescription(description, new SubProgressMonitor(monitor, 10)); } catch (CoreException e) { System.out.println("CoreException: " + e.getLocalizedMessage()); e.printStackTrace(); }finally{ createFolders(project); createClassPath(project); createDeepFile(); monitor.done(); } } private void save(){ ProjectScope scope = new ProjectScope(project); IEclipsePreferences pref = scope.getNode("deepStart");//TODO berprfen ob es diesen Node gibt pref.put("proc", wizPage1.getProcessorValue()); pref.put("board", wizPage1.getBoardValue()); pref.put("rts", wizPage1.getRunTimeSystemValue()); if(wizPage1.useDefaultLibPath()){ pref.putBoolean("useDefault", true); pref.put("libPath", wizPage1.getDefaultLibPath()); }else{ pref.putBoolean("useDefault", false); pref.put("libPath", wizPage1.getChosenLibPath()); } try { pref.flush(); } catch (BackingStoreException e) { e.printStackTrace(); } } /** * Displays an error that occured during the project creation. * * @param x * details on the error */ private void reportError(Exception x) { ErrorDialog.openError(getShell(), "Error", "Project creation error", makeStatus(x)); } public static IStatus makeStatus(Exception x) { if (x instanceof CoreException) { return ((CoreException) x).getStatus(); } else { return new Status(IStatus.ERROR, "ch.ntb.inf.deep", IStatus.ERROR, x.getMessage() != null ? x.getMessage() : x.toString(), x); } } }
package org.jasig.portal; import org.jasig.portal.services.LogService; import org.jasig.portal.utils.SmartCache; import org.w3c.dom.Document; import java.sql.SQLException; /** * Manages the channel registry which is a listing of published channels * that one can subscribe to (add to their layout). * Also currently manages the channel types data. (maybe this should be managed * by another class -Ken) * @author Ken Weiner, kweiner@interactivebusiness.com * @version $Revision$ */ public class ChannelRegistryManager { protected static final IChannelRegistryStore chanRegStore = RdbmServices.getChannelRegistryStoreImpl(); protected static final int registryCacheTimeout = PropertiesManager.getPropertyAsInt("org.jasig.portal.ChannelRegistryManager.channel_registry_cache_timeout"); protected static final int chanTypesCacheTimeout = PropertiesManager.getPropertyAsInt("org.jasig.portal.ChannelRegistryManager.channel_types_cache_timeout"); protected static final SmartCache channelRegistryCache = new SmartCache(registryCacheTimeout); protected static final SmartCache channelTypesCache = new SmartCache(chanTypesCacheTimeout); /** * Returns the channel registry as a Document. This list is not filtered by roles. * @return the channel registry as a Document */ public static Document getChannelRegistry() throws PortalException { Document channelRegistry = (Document)channelRegistryCache.get("channelRegistry"); if (channelRegistry == null) { // Channel registry has expired, so get it and cache it try { channelRegistry = chanRegStore.getChannelRegistryXML(); } catch (Exception e) { throw new GeneralRenderingException(e.getMessage()); } if (channelRegistry != null) { channelRegistryCache.put("channelRegistry", channelRegistry); LogService.instance().log(LogService.INFO, "Caching channel registry."); } } return channelRegistry; } /** * Returns the publishable channel types as a Document. * @return a list of channel types as a Document */ public static Document getChannelTypes() throws PortalException { String key = "channelTypes"; Document channelTypes = (Document)channelTypesCache.get(key); if (channelTypes == null) { // Channel types doc has expired, so get it and cache it try { channelTypes = chanRegStore.getChannelTypesXML(); } catch (Exception e) { throw new GeneralRenderingException(e.getMessage()); } if (channelTypes != null) { channelTypesCache.put(key, channelTypes); LogService.instance().log(LogService.INFO, "Caching channel types."); } } return channelTypes; } }
import java.util.concurrent.CyclicBarrier; public class TestCyclicBarrier { private static CyclicBarrier barrier = new CyclicBarrier(2, ()-> {System.out.println("All threads have arrived");}); public static void main(String[] args) throws Exception{ new Thread(()-> { try { System.out.println("Thread 1, awaiting to complete"); Thread.sleep(10000); barrier.await(); System.out.println("Thread 1, awaite complete"); }catch(Exception e) { e.printStackTrace(); } }).start(); new Thread(()-> { try { System.out.println("Thread 2, awaiting to complete"); Thread.sleep(5000); barrier.await(); System.out.println("Thread 2, awaite complete"); }catch(Exception e) { e.printStackTrace(); } }).start(); System.out.println("Done"); } }
package org.fcrepo.api; import static javax.ws.rs.core.MediaType.TEXT_HTML; import static javax.ws.rs.core.Response.created; import static javax.ws.rs.core.Response.noContent; import static javax.ws.rs.core.Response.status; import static org.apache.jena.riot.WebContent.contentTypeSPARQLUpdate; import static org.fcrepo.http.RDFMediaType.N3; import static org.fcrepo.http.RDFMediaType.N3_ALT1; import static org.fcrepo.http.RDFMediaType.N3_ALT2; import static org.fcrepo.http.RDFMediaType.NTRIPLES; import static org.fcrepo.http.RDFMediaType.RDF_JSON; import static org.fcrepo.http.RDFMediaType.RDF_XML; import static org.fcrepo.http.RDFMediaType.TURTLE; import static org.slf4j.LoggerFactory.getLogger; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.List; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.CacheControl; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.PathSegment; import javax.ws.rs.core.Request; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.UriInfo; import org.apache.commons.io.IOUtils; import org.apache.http.HttpStatus; import org.fcrepo.AbstractResource; import org.fcrepo.FedoraResource; import org.fcrepo.api.rdf.HttpGraphSubjects; import org.fcrepo.exception.InvalidChecksumException; import org.fcrepo.services.DatastreamService; import org.fcrepo.services.LowLevelStorageService; import org.fcrepo.services.ObjectService; import org.fcrepo.utils.FedoraJcrTypes; import org.modeshape.common.collection.Problems; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.codahale.metrics.annotation.Timed; import com.hp.hpl.jena.query.Dataset; import com.hp.hpl.jena.update.UpdateAction; @Component @Path("/rest/{path: .*}") public class FedoraNodes extends AbstractResource { private static final Logger logger = getLogger(FedoraNodes.class); @Autowired private LowLevelStorageService llStoreService; @GET @Produces({N3, N3_ALT1, N3_ALT2, TURTLE, RDF_XML, RDF_JSON, NTRIPLES, TEXT_HTML}) public Dataset describe(@PathParam("path") final List<PathSegment> pathList, @Context final Request request) throws RepositoryException, IOException { final String path = toPath(pathList); logger.trace("Getting profile for {}", path); final Session session = getAuthenticatedSession(); try { final FedoraResource resource = nodeService.getObject(session, path); final Date date = resource.getLastModifiedDate(); final Date roundedDate = new Date(); if (date != null) { roundedDate.setTime(date.getTime() - date.getTime() % 1000); } final ResponseBuilder builder = request.evaluatePreconditions(roundedDate); if (builder != null) { final CacheControl cc = new CacheControl(); cc.setMaxAge(0); cc.setMustRevalidate(true); // here we are implicitly emitting a 304 // the exception is not an error, it's genuinely // an exceptional condition throw new WebApplicationException(builder.cacheControl(cc) .lastModified(date).build()); } return resource.getGraphStore().toDataset(); } finally { session.logout(); } } /** * Does nothing (good) yet -- just runs SPARQL-UPDATE statements * @param pathList * @param requestBodyStream * @return 201 * @throws RepositoryException */ @PUT @Consumes({contentTypeSPARQLUpdate}) @Timed public Response modifyObject(@PathParam("path") final List<PathSegment> pathList, @Context final UriInfo uriInfo, final InputStream requestBodyStream) throws RepositoryException, IOException { final Session session = getAuthenticatedSession(); final String path = toPath(pathList); logger.debug("Modifying object with path: {}", path); try { final FedoraResource result = nodeService.getObject(session, path); if (requestBodyStream != null) { UpdateAction.parseExecute(IOUtils.toString(requestBodyStream), result.getGraphStore(new HttpGraphSubjects( FedoraNodes.class, uriInfo))); } session.save(); return Response.status(HttpStatus.SC_NO_CONTENT).build(); } finally { session.logout(); } } /** * Update an object using SPARQL-UPDATE * * @param pathList * @return 201 * @throws RepositoryException * @throws org.fcrepo.exception.InvalidChecksumException * @throws IOException */ @POST @Consumes({contentTypeSPARQLUpdate}) @Timed public Response updateSparql(@PathParam("path") final List<PathSegment> pathList, @Context final UriInfo uriInfo, final InputStream requestBodyStream) throws RepositoryException, IOException { final String path = toPath(pathList); logger.debug("Attempting to ingest with path: {}", path); final Session session = getAuthenticatedSession(); try { if (requestBodyStream != null) { final FedoraResource result = nodeService.getObject(session, path); result.updateGraph(new HttpGraphSubjects(FedoraNodes.class, uriInfo), IOUtils.toString(requestBodyStream)); final Problems problems = result.getGraphProblems(); if (problems != null && problems.hasProblems()) { logger.info( "Found these problems updating the properties for {}: {}", path, problems.toString()); return status(Response.Status.FORBIDDEN).entity( problems.toString()).build(); } session.save(); return Response.status(HttpStatus.SC_NO_CONTENT).build(); } else { return Response.status(HttpStatus.SC_BAD_REQUEST).entity( "SPARQL-UPDATE requests must have content ").build(); } } finally { session.logout(); } } /** * Creates a new object. * * @param pathList * @return 201 * @throws RepositoryException * @throws InvalidChecksumException * @throws IOException */ @POST @Timed public Response createObject(@PathParam("path") final List<PathSegment> pathList, @QueryParam("mixin") @DefaultValue(FedoraJcrTypes.FEDORA_OBJECT) final String mixin, @QueryParam("checksumType") final String checksumType, @QueryParam("checksum") final String checksum, @HeaderParam("Content-Type") final MediaType requestContentType, @Context final UriInfo uriInfo, final InputStream requestBodyStream) throws RepositoryException, IOException, InvalidChecksumException { final String path = toPath(pathList); logger.debug("Attempting to ingest with path: {}", path); final Session session = getAuthenticatedSession(); try { if (nodeService.exists(session, path)) { return Response.status(HttpStatus.SC_CONFLICT).entity( path + " is an existing resource").build(); } createObjectOrDatastreamFromRequestContent(FedoraNodes.class, session, path, mixin, uriInfo, requestBodyStream, requestContentType, checksumType, checksum); session.save(); logger.debug("Finished creating {} with path: {}", mixin, path); return created(uriInfo.getRequestUri()).entity(path).build(); } finally { session.logout(); } } /** * Deletes an object. * * @param path * @return * @throws RepositoryException */ @DELETE @Timed public Response deleteObject(@PathParam("path") final List<PathSegment> path) throws RepositoryException { final Session session = getAuthenticatedSession(); try { nodeService.deleteObject(session, toPath(path)); session.save(); return noContent().build(); } finally { session.logout(); } } public ObjectService getObjectService() { return objectService; } @Override public void setObjectService(final ObjectService objectService) { this.objectService = objectService; } public DatastreamService getDatastreamService() { return datastreamService; } public void setDatastreamService(final DatastreamService datastreamService) { this.datastreamService = datastreamService; } public LowLevelStorageService getLlStoreService() { return llStoreService; } public void setLlStoreService(final LowLevelStorageService llStoreService) { this.llStoreService = llStoreService; } }
package org.jlib.core.collections.matrix; import java.util.AbstractCollection; import java.util.Collection; import java.util.Iterator; import org.jlib.core.collections.ListIndexOutOfBoundsException; import org.jlib.core.collections.array.Array; /** * <p> * Fixed sized matrix. Replacement for two-dimensional arrays with special features. * </p> * <p> * The only syntactical difference to two-dimensinal arrays lies in the syntax of setting and * getting objects: * </p> * * <pre> * {@literal * // good(?) old two-dimensional array // cool(!) new jlib Matrix class * String[][] stringMatrix = new String[10][5]; Matrix<String> stringMatrix = new Matrix<String>(10, 5); * stringMatrix[2][3] = "Too old!"; stringMatrix.set(2, 3, "Brandnew!"); * String s = stringMatrix[2][3]; String s = stringMatrix.get(2, 3); } * </pre> * * <p> * Special features: * </p> * <ul> * <li> Minimum and maximum width and height:<br/> On instantiation, you can specify the minimum * and the maximum width and height of the Matrix. Thus, no offset is necessary for matrices * starting at other indexes than 0. The following example illustrates how a (4x2)-Matrix with * indexes starting at 1, in which every entry is the product of the column and row number: * * <pre> * {@literal * // good(?) old two-dimensional array // cool(!) new jlib Matrix class * Integer[][] integerMatrix = new Integer[4][2]; Matrix<Integer> integerMatrix = new Matrix<Integer>(4, 2); * for (int row = 1; row <= 2; row ++) for (int row = 1; row <= 2; row ++) * for (int col = 1; col <= 4; col ++) for (int col = 1; col <= 4; col ++) * integerMatrix[col - 1][row - 1] = col * row; integerMatrix.set(col, row, col * row); } * </pre> * * </li> * <li>Conformance to the Java Collections Framework <br/> The class implements the * {@code java.util.Collection} interface and thus behaves like all Java Collections.</li> * <br /> * <li>Full support for generics:<br/> The Java arrays do not support generic classes. For * example, you cannot create an array of String Lists: * * <pre> * {@literal * // FORBIDDEN! * Set<String>[][] stringSetMatrix = new Set<String>[4][2]; * * // PERMITTED! * Matrix<Set<String>> stringSetMatrix = new Matrix<Set<String>>(4, 2);} * </pre> * * </li> * </ul> * <p> * A default iteration order can be defined specifying how this Matrix is traversed by the Iterator * returned by {@link #iterator()}. * <ul> * <li> Horizontal iteration. That is, the traversal algorithm is as follows: * * <pre>{@literal * foreach row * foreach column * process element at (column, row)} * </pre> * * </li> * <li> Vertical iteration. That is, the traversal algorithm is as follows: * * <pre>{@literal * foreach column * foreach row * process element at (column, row)} * </pre> * * </li> * </ul> * </p> * <p> * A Matrix has a fixed size, thus no Elements can be added to or removed from it. The corresponding * methods for adding and removing Elements all throw an {@link UnsupportedOperationException}. * </p> * * @param <Element> * type of the elements held in the Matrix * @author Igor Akkerman */ public class Matrix<Element> extends AbstractCollection<Element> { /** default iteration order */ public static final MatrixIterationOrder DEFAULTITERATIONORDER = MatrixIterationOrder.HORIZONTAL; /** number of columns */ private int width; /** number of rows */ private int height; /** minimum column index */ private int minColumnIndex; /** maximum column index */ private int maxColumnIndex; /** minimum row index */ private int minRowIndex; /** maximum row index */ private int maxRowIndex; /** order in which this Matrix is iterated */ private MatrixIterationOrder iterationOrder; /** Matrix data */ private Array<Array<Element>> matrixData; /** * Creates a new empty Matrix. */ public Matrix() { this(0, 0); } public Matrix(int width, int height) { super(); if (width != 0 && height != 0) { construct(0, width - 1, 0, height - 1, DEFAULTITERATIONORDER); } else { minRowIndex = -1; maxRowIndex = -1; minColumnIndex = -1; maxColumnIndex = -1; this.width = width; this.height = height; matrixData = new Array<Array<Element>>(); } } public Matrix(int minColumnIndex, int maxColumnIndex, int minRowIndex, int maxRowIndex) { super(); construct(minColumnIndex, maxColumnIndex, minRowIndex, maxRowIndex, DEFAULTITERATIONORDER); } public Matrix(int width, int height, MatrixIterationOrder iterationOrder) { super(); if (width != 0 && height != 0) { construct(0, width - 1, 0, height - 1, iterationOrder); } else { minRowIndex = -1; maxRowIndex = -1; minColumnIndex = -1; maxColumnIndex = -1; this.width = width; this.height = height; matrixData = new Array<Array<Element>>(); } } public Matrix(int minColumnIndex, int maxColumnIndex, int minRowIndex, int maxRowIndex, MatrixIterationOrder iterationOrder) { super(); construct(minColumnIndex, maxColumnIndex, minRowIndex, maxRowIndex, iterationOrder); } @SuppressWarnings("hiding") private void construct(int minColumnIndex, int maxColumnIndex, int minRowIndex, int maxRowIndex, MatrixIterationOrder iterationOrder) { if (minColumnIndex < 0 || maxColumnIndex < minColumnIndex || minRowIndex < 0 || maxRowIndex < minRowIndex) { throw new IllegalArgumentException(); } this.minColumnIndex = minColumnIndex; this.maxColumnIndex = maxColumnIndex; this.minRowIndex = minRowIndex; this.maxRowIndex = maxRowIndex; this.width = maxColumnIndex - minColumnIndex + 1; this.height = maxRowIndex - minRowIndex + 1; matrixData = new Array<Array<Element>>(minRowIndex, maxRowIndex); for (int row = minRowIndex; row <= maxRowIndex; row ++) { matrixData.set(row, new Array<Element>(minColumnIndex, maxColumnIndex)); } this.iterationOrder = iterationOrder; } /** * Returns the Element stored at the specified column and row in this Matrix. * * @param columnIndex * integer specifying the column of the stored Element * @param rowIndex * integer specifying the row of the stored Element * @return Element stored at the specified position in this Matrix * @throws ListIndexOutOfBoundsException * if * {@code columnIndex < getMinColumnIndex() || columnIndex > getMaxColumnIndex() || rowIndex < getMinRowIndex || rowIndex > getMaxRowIndex()} */ public Element get(int columnIndex, int rowIndex) throws ListIndexOutOfBoundsException { return matrixData.get(rowIndex).get(columnIndex); } /** * Registers the Element to store at the specified column and row in this Matrix. * * @param columnIndex * integer specifying the column of the Element to store * @param rowIndex * integer specifying the row of the Element to store * @param element * Element to store. {@code null} is a valid Element. * @throws ListIndexOutOfBoundsException * if * {@code columnIndex < getMinColumnIndex() || columnIndex > getMaxColumnIndex() || rowIndex < getMinRowIndex || rowIndex > getMaxRowIndex()} */ public void set(int columnIndex, int rowIndex, Element element) { matrixData.get(rowIndex).set(columnIndex, element); } /** * Returns a MatrixColumn representing the specified column of this Matrix. * * @param columnIndex * integer specifying the index of the column * @return MatrixColumn representing the column with {@code columnIndex} */ public MatrixColumn getColumn(int columnIndex) { return new MatrixColumn<Element>(this, columnIndex); } /** * Returns a MatrixColumn representing the specified portion of the specified column of this * Matrix. * * @param columnIndex * integer specifying the index of the column * @param minRowIndex * integer specifying the minimum row index of the portion of the column * @param maxRowIndex * integer specifying the maximum row index of the portion of the column * @return MatrixColumn representing the column with {@code columnIndex} */ @SuppressWarnings("hiding") public MatrixColumn getColumn(int columnIndex, int minRowIndex, int maxRowIndex) { return new MatrixColumn<Element>(this, columnIndex, minRowIndex, maxRowIndex); } /** * Returns a MatrixRow representing the specified row of this Matrix. * * @param rowIndex * integer specifying the index of the row * @return MatrixRow representing the row with {@code rowIndex} */ public MatrixRow getRow(int rowIndex) { return new MatrixRow<Element>(this, rowIndex); } /** * Returns a MatrixRow representing the specified portion of the specified row of this Matrix. * * @param rowIndex * integer specifying the index of the row * @param minColumnIndex * integer specifying the minimum column index of the portion of the row * @param maxColumnIndex * integer specifying the maximum column index of the portion of the row * @return MatrixRow representing the row with {@code rowIndex} */ @SuppressWarnings("hiding") public MatrixRow getRow(int rowIndex, int minColumnIndex, int maxColumnIndex) { return new MatrixRow<Element>(this, rowIndex, minColumnIndex, maxColumnIndex); } /** * Returns the minimum column index of this Matrix. * * @return integer specifying the minimum column of this Matrix */ public int getMinColumnIndex() { return minColumnIndex; } /** * Returns the maximum column index of this Matrix. * * @return integer specifying the maximum column of this Matrix */ public int getMaxColumnIndex() { return maxColumnIndex; } /** * Returns the minimum row index of this Matrix. * * @return integer specifying the minimum row of this Matrix */ public int getMinRowIndex() { return minRowIndex; } /** * Returns the maximum row index of this Matrix. * * @return integer specifying the maximum row of this Matrix */ public int getMaxRowIndex() { return maxRowIndex; } /** * Returns the width of this Matrix. * * @return integer specifying the width */ public int getWidth() { return width; } /** * Returns the height of this Matrix. * * @return integer specifying the height */ public int getHeight() { return height; } /** * Returns the number of fields in this Matrix. The size is equal to * {@code getWidth() * getHeight()}. * * @return integer specifying the number of fields */ public int size() { return width * height; } /** * Returns an Iterator of the Elements of this Matrix traversing it horizontally. That is, the * traversal algorithm is as follows: * * <pre>{@literal * for each row * for each column * process element at (column, row)} * </pre> * * The {@link #newHorizontalIterator()} method has the same functionality as this method. * * @return a new Iterator for this Matrix */ public Iterator<Element> iterator() { switch (iterationOrder) { case HORIZONTAL: return newHorizontalIterator(); case VERTICAL: return newVerticalIterator(); default: // impossible to occur throw new RuntimeException(); } } /** * Returns an Iterator of the Elements of this Matrix traversing it horizontally. That is, the * traversal algorithm is as follows: * * <pre>{@literal * for each row * for each column * process element at (column, row)} * </pre> * * The {@link #iterator()} method has the same functionality as this method. * * @return a new rows Iterator for this Matrix */ public Iterator<Element> newHorizontalIterator() { return new VerticalMatrixIterator<Element>(this); } /** * Returns an Iterator of the Elements of this Matrix traversing it vertically. That is, the * traversal algorithm is as follows: * * <pre>{@literal * for each column * for each row * process element at (column, row)} * </pre> * * @return a new columns Iterator for this Matrix */ public Iterator<Element> newVerticalIterator() { return new HorizontalMatrixIterator<Element>(this); } /** * Returns an Iterator of the Elements in a single column of this Matrix. * * @param columnIndex * integer specifying the index of the column to traverse * @return a new column Iterator for this Matrix */ public Iterator<Element> newColumnIterator(int columnIndex) { return new MatrixColumnIterator<Element>(this, columnIndex); } /** * Returns an Iterator of the Elements in a single row of this Matrix. * * @param rowIndex * integer specifying the index of the row to traverse * @return a new row Iterator for this Matrix */ public Iterator<Element> newRowIterator(int rowIndex) { return new MatrixRowIterator<Element>(this, rowIndex); } // @see java.util.Collection#contains(java.lang.Object) public boolean contains(Object element) { for (Array<Element> columnArray : matrixData) if (columnArray.contains(element)) return true; return false; } // @see java.util.Collection#containsAll(java.util.Collection) public boolean containsAll(Collection<?> collection) { for (Object object : collection) if (!contains(object)) return false; return true; } }
package org.jfree.data.general; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.jfree.chart.util.ArrayUtilities; import org.jfree.data.DomainInfo; import org.jfree.data.KeyToGroupMap; import org.jfree.data.KeyedValues; import org.jfree.data.Range; import org.jfree.data.RangeInfo; import org.jfree.data.category.CategoryDataset; import org.jfree.data.category.CategoryRangeInfo; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.category.IntervalCategoryDataset; import org.jfree.data.function.Function2D; import org.jfree.data.statistics.BoxAndWhiskerXYDataset; import org.jfree.data.statistics.StatisticalCategoryDataset; import org.jfree.data.xy.IntervalXYDataset; import org.jfree.data.xy.OHLCDataset; import org.jfree.data.xy.TableXYDataset; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYDomainInfo; import org.jfree.data.xy.XYRangeInfo; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; /** * A collection of useful static methods relating to datasets. */ public final class DatasetUtilities { /** * Private constructor for non-instanceability. */ private DatasetUtilities() { // now try to instantiate this ;-) } /** * Calculates the total of all the values in a {@link PieDataset}. If * the dataset contains negative or <code>null</code> values, they are * ignored. * * @param dataset the dataset (<code>null</code> not permitted). * * @return The total. */ public static double calculatePieDatasetTotal(PieDataset dataset) { if (dataset == null) { throw new IllegalArgumentException("Null 'dataset' argument."); } List keys = dataset.getKeys(); double totalValue = 0; Iterator iterator = keys.iterator(); while (iterator.hasNext()) { Comparable current = (Comparable) iterator.next(); if (current != null) { Number value = dataset.getValue(current); double v = 0.0; if (value != null) { v = value.doubleValue(); } if (v > 0) { totalValue = totalValue + v; } } } return totalValue; } /** * Creates a pie dataset from a table dataset by taking all the values * for a single row. * * @param dataset the dataset (<code>null</code> not permitted). * @param rowKey the row key. * * @return A pie dataset. */ public static PieDataset createPieDatasetForRow(CategoryDataset dataset, Comparable rowKey) { int row = dataset.getRowIndex(rowKey); return createPieDatasetForRow(dataset, row); } /** * Creates a pie dataset from a table dataset by taking all the values * for a single row. * * @param dataset the dataset (<code>null</code> not permitted). * @param row the row (zero-based index). * * @return A pie dataset. */ public static PieDataset createPieDatasetForRow(CategoryDataset dataset, int row) { DefaultPieDataset result = new DefaultPieDataset(); int columnCount = dataset.getColumnCount(); for (int current = 0; current < columnCount; current++) { Comparable columnKey = dataset.getColumnKey(current); result.setValue(columnKey, dataset.getValue(row, current)); } return result; } /** * Creates a pie dataset from a table dataset by taking all the values * for a single column. * * @param dataset the dataset (<code>null</code> not permitted). * @param columnKey the column key. * * @return A pie dataset. */ public static PieDataset createPieDatasetForColumn(CategoryDataset dataset, Comparable columnKey) { int column = dataset.getColumnIndex(columnKey); return createPieDatasetForColumn(dataset, column); } /** * Creates a pie dataset from a {@link CategoryDataset} by taking all the * values for a single column. * * @param dataset the dataset (<code>null</code> not permitted). * @param column the column (zero-based index). * * @return A pie dataset. */ public static PieDataset createPieDatasetForColumn(CategoryDataset dataset, int column) { DefaultPieDataset result = new DefaultPieDataset(); int rowCount = dataset.getRowCount(); for (int i = 0; i < rowCount; i++) { Comparable rowKey = dataset.getRowKey(i); result.setValue(rowKey, dataset.getValue(i, column)); } return result; } /** * Creates a new pie dataset based on the supplied dataset, but modified * by aggregating all the low value items (those whose value is lower * than the <code>percentThreshold</code>) into a single item with the * key "Other". * * @param source the source dataset (<code>null</code> not permitted). * @param key a new key for the aggregated items (<code>null</code> not * permitted). * @param minimumPercent the percent threshold. * * @return The pie dataset with (possibly) aggregated items. */ public static PieDataset createConsolidatedPieDataset(PieDataset source, Comparable key, double minimumPercent) { return DatasetUtilities.createConsolidatedPieDataset(source, key, minimumPercent, 2); } /** * Creates a new pie dataset based on the supplied dataset, but modified * by aggregating all the low value items (those whose value is lower * than the <code>percentThreshold</code>) into a single item. The * aggregated items are assigned the specified key. Aggregation only * occurs if there are at least <code>minItems</code> items to aggregate. * * @param source the source dataset (<code>null</code> not permitted). * @param key the key to represent the aggregated items. * @param minimumPercent the percent threshold (ten percent is 0.10). * @param minItems only aggregate low values if there are at least this * many. * * @return The pie dataset with (possibly) aggregated items. */ public static PieDataset createConsolidatedPieDataset(PieDataset source, Comparable key, double minimumPercent, int minItems) { DefaultPieDataset result = new DefaultPieDataset(); double total = DatasetUtilities.calculatePieDatasetTotal(source); // Iterate and find all keys below threshold percentThreshold List keys = source.getKeys(); ArrayList otherKeys = new ArrayList(); Iterator iterator = keys.iterator(); while (iterator.hasNext()) { Comparable currentKey = (Comparable) iterator.next(); Number dataValue = source.getValue(currentKey); if (dataValue != null) { double value = dataValue.doubleValue(); if (value / total < minimumPercent) { otherKeys.add(currentKey); } } } // Create new dataset with keys above threshold percentThreshold iterator = keys.iterator(); double otherValue = 0; while (iterator.hasNext()) { Comparable currentKey = (Comparable) iterator.next(); Number dataValue = source.getValue(currentKey); if (dataValue != null) { if (otherKeys.contains(currentKey) && otherKeys.size() >= minItems) { // Do not add key to dataset otherValue += dataValue.doubleValue(); } else { // Add key to dataset result.setValue(currentKey, dataValue); } } } // Add other category if applicable if (otherKeys.size() >= minItems) { result.setValue(key, otherValue); } return result; } public static CategoryDataset createCategoryDataset(String rowKeyPrefix, String columnKeyPrefix, double[][] data) { DefaultCategoryDataset result = new DefaultCategoryDataset(); for (int r = 0; r < data.length; r++) { String rowKey = rowKeyPrefix + (r + 1); for (int c = 0; c < data[r].length; c++) { String columnKey = columnKeyPrefix + (c + 1); result.addValue(new Double(data[r][c]), rowKey, columnKey); } } return result; } public static CategoryDataset createCategoryDataset(String rowKeyPrefix, String columnKeyPrefix, Number[][] data) { DefaultCategoryDataset result = new DefaultCategoryDataset(); for (int r = 0; r < data.length; r++) { String rowKey = rowKeyPrefix + (r + 1); for (int c = 0; c < data[r].length; c++) { String columnKey = columnKeyPrefix + (c + 1); result.addValue(data[r][c], rowKey, columnKey); } } return result; } /** * Creates a {@link CategoryDataset} that contains a copy of the data in * an array (instances of <code>Double</code> are created to represent the * data items). * <p> * Row and column keys are taken from the supplied arrays. * * @param rowKeys the row keys (<code>null</code> not permitted). * @param columnKeys the column keys (<code>null</code> not permitted). * @param data the data. * * @return The dataset. */ public static CategoryDataset createCategoryDataset(Comparable[] rowKeys, Comparable[] columnKeys, double[][] data) { // check arguments... if (rowKeys == null) { throw new IllegalArgumentException("Null 'rowKeys' argument."); } if (columnKeys == null) { throw new IllegalArgumentException("Null 'columnKeys' argument."); } if (ArrayUtilities.hasDuplicateItems(rowKeys)) { throw new IllegalArgumentException("Duplicate items in 'rowKeys'."); } if (ArrayUtilities.hasDuplicateItems(columnKeys)) { throw new IllegalArgumentException( "Duplicate items in 'columnKeys'."); } if (rowKeys.length != data.length) { throw new IllegalArgumentException( "The number of row keys does not match the number of rows in " + "the data array."); } int columnCount = 0; for (int r = 0; r < data.length; r++) { columnCount = Math.max(columnCount, data[r].length); } if (columnKeys.length != columnCount) { throw new IllegalArgumentException( "The number of column keys does not match the number of " + "columns in the data array."); } // now do the work... DefaultCategoryDataset result = new DefaultCategoryDataset(); for (int r = 0; r < data.length; r++) { Comparable rowKey = rowKeys[r]; for (int c = 0; c < data[r].length; c++) { Comparable columnKey = columnKeys[c]; result.addValue(new Double(data[r][c]), rowKey, columnKey); } } return result; } /** * Creates a {@link CategoryDataset} by copying the data from the supplied * {@link KeyedValues} instance. * * @param rowKey the row key (<code>null</code> not permitted). * @param rowData the row data (<code>null</code> not permitted). * * @return A dataset. */ public static CategoryDataset createCategoryDataset(Comparable rowKey, KeyedValues rowData) { if (rowKey == null) { throw new IllegalArgumentException("Null 'rowKey' argument."); } if (rowData == null) { throw new IllegalArgumentException("Null 'rowData' argument."); } DefaultCategoryDataset result = new DefaultCategoryDataset(); for (int i = 0; i < rowData.getItemCount(); i++) { result.addValue(rowData.getValue(i), rowKey, rowData.getKey(i)); } return result; } /** * Creates an {@link XYDataset} by sampling the specified function over a * fixed range. * * @param f the function (<code>null</code> not permitted). * @param start the start value for the range. * @param end the end value for the range. * @param samples the number of sample points (must be > 1). * @param seriesKey the key to give the resulting series * (<code>null</code> not permitted). * * @return A dataset. */ public static XYDataset sampleFunction2D(Function2D f, double start, double end, int samples, Comparable seriesKey) { // defer argument checking XYSeries series = sampleFunction2DToSeries(f, start, end, samples, seriesKey); XYSeriesCollection collection = new XYSeriesCollection(series); return collection; } /** * Creates an {@link XYSeries} by sampling the specified function over a * fixed range. * * @param f the function (<code>null</code> not permitted). * @param start the start value for the range. * @param end the end value for the range. * @param samples the number of sample points (must be > 1). * @param seriesKey the key to give the resulting series * (<code>null</code> not permitted). * * @return A series. * * @since 1.0.13 */ public static XYSeries sampleFunction2DToSeries(Function2D f, double start, double end, int samples, Comparable seriesKey) { if (f == null) { throw new IllegalArgumentException("Null 'f' argument."); } if (seriesKey == null) { throw new IllegalArgumentException("Null 'seriesKey' argument."); } if (start >= end) { throw new IllegalArgumentException("Requires 'start' < 'end'."); } if (samples < 2) { throw new IllegalArgumentException("Requires 'samples' > 1"); } XYSeries series = new XYSeries(seriesKey); double step = (end - start) / (samples - 1); for (int i = 0; i < samples; i++) { double x = start + (step * i); series.add(x, f.getValue(x)); } return series; } /** * Returns <code>true</code> if the dataset is empty (or <code>null</code>), * and <code>false</code> otherwise. * * @param dataset the dataset (<code>null</code> permitted). * * @return A boolean. */ public static boolean isEmptyOrNull(PieDataset dataset) { if (dataset == null) { return true; } int itemCount = dataset.getItemCount(); if (itemCount == 0) { return true; } for (int item = 0; item < itemCount; item++) { Number y = dataset.getValue(item); if (y != null) { double yy = y.doubleValue(); if (yy > 0.0) { return false; } } } return true; } /** * Returns <code>true</code> if the dataset is empty (or <code>null</code>), * and <code>false</code> otherwise. * * @param dataset the dataset (<code>null</code> permitted). * * @return A boolean. */ public static boolean isEmptyOrNull(CategoryDataset dataset) { if (dataset == null) { return true; } int rowCount = dataset.getRowCount(); int columnCount = dataset.getColumnCount(); if (rowCount == 0 || columnCount == 0) { return true; } for (int r = 0; r < rowCount; r++) { for (int c = 0; c < columnCount; c++) { if (dataset.getValue(r, c) != null) { return false; } } } return true; } /** * Returns <code>true</code> if the dataset is empty (or <code>null</code>), * and <code>false</code> otherwise. * * @param dataset the dataset (<code>null</code> permitted). * * @return A boolean. */ public static boolean isEmptyOrNull(XYDataset dataset) { if (dataset != null) { for (int s = 0; s < dataset.getSeriesCount(); s++) { if (dataset.getItemCount(s) > 0) { return false; } } } return true; } /** * Returns the range of values in the domain (x-values) of a dataset. * * @param dataset the dataset (<code>null</code> not permitted). * * @return The range of values (possibly <code>null</code>). */ public static Range findDomainBounds(XYDataset dataset) { return findDomainBounds(dataset, true); } /** * Returns the range of values in the domain (x-values) of a dataset. * * @param dataset the dataset (<code>null</code> not permitted). * @param includeInterval determines whether or not the x-interval is taken * into account (only applies if the dataset is an * {@link IntervalXYDataset}). * * @return The range of values (possibly <code>null</code>). */ public static Range findDomainBounds(XYDataset dataset, boolean includeInterval) { if (dataset == null) { throw new IllegalArgumentException("Null 'dataset' argument."); } Range result = null; // if the dataset implements DomainInfo, life is easier if (dataset instanceof DomainInfo) { DomainInfo info = (DomainInfo) dataset; result = info.getDomainBounds(includeInterval); } else { result = iterateDomainBounds(dataset, includeInterval); } return result; } /** * Returns the bounds of the x-values in the specified <code>dataset</code> * taking into account only the visible series and including any x-interval * if requested. * * @param dataset the dataset (<code>null</code> not permitted). * @param visibleSeriesKeys the visible series keys (<code>null</code> * not permitted). * @param includeInterval include the x-interval (if any)? * * @return The bounds (or <code>null</code> if the dataset contains no * values. * * @since 1.0.13 */ public static Range findDomainBounds(XYDataset dataset, List visibleSeriesKeys, boolean includeInterval) { if (dataset == null) { throw new IllegalArgumentException("Null 'dataset' argument."); } Range result = null; if (dataset instanceof XYDomainInfo) { XYDomainInfo info = (XYDomainInfo) dataset; result = info.getDomainBounds(visibleSeriesKeys, includeInterval); } else { result = iterateToFindDomainBounds(dataset, visibleSeriesKeys, includeInterval); } return result; } /** * Iterates over the items in an {@link XYDataset} to find * the range of x-values. If the dataset is an instance of * {@link IntervalXYDataset}, the starting and ending x-values * will be used for the bounds calculation. * * @param dataset the dataset (<code>null</code> not permitted). * * @return The range (possibly <code>null</code>). */ public static Range iterateDomainBounds(XYDataset dataset) { return iterateDomainBounds(dataset, true); } /** * Iterates over the items in an {@link XYDataset} to find * the range of x-values. * * @param dataset the dataset (<code>null</code> not permitted). * @param includeInterval a flag that determines, for an * {@link IntervalXYDataset}, whether the x-interval or just the * x-value is used to determine the overall range. * * @return The range (possibly <code>null</code>). */ public static Range iterateDomainBounds(XYDataset dataset, boolean includeInterval) { if (dataset == null) { throw new IllegalArgumentException("Null 'dataset' argument."); } double minimum = Double.POSITIVE_INFINITY; double maximum = Double.NEGATIVE_INFINITY; int seriesCount = dataset.getSeriesCount(); double lvalue; double uvalue; if (includeInterval && dataset instanceof IntervalXYDataset) { IntervalXYDataset intervalXYData = (IntervalXYDataset) dataset; for (int series = 0; series < seriesCount; series++) { int itemCount = dataset.getItemCount(series); for (int item = 0; item < itemCount; item++) { lvalue = intervalXYData.getStartXValue(series, item); uvalue = intervalXYData.getEndXValue(series, item); if (!Double.isNaN(lvalue)) { minimum = Math.min(minimum, lvalue); } if (!Double.isNaN(uvalue)) { maximum = Math.max(maximum, uvalue); } } } } else { for (int series = 0; series < seriesCount; series++) { int itemCount = dataset.getItemCount(series); for (int item = 0; item < itemCount; item++) { lvalue = dataset.getXValue(series, item); uvalue = lvalue; if (!Double.isNaN(lvalue)) { minimum = Math.min(minimum, lvalue); maximum = Math.max(maximum, uvalue); } } } } if (minimum > maximum) { return null; } else { return new Range(minimum, maximum); } } /** * Returns the range of values in the range for the dataset. * * @param dataset the dataset (<code>null</code> not permitted). * * @return The range (possibly <code>null</code>). */ public static Range findRangeBounds(CategoryDataset dataset) { return findRangeBounds(dataset, true); } /** * Returns the range of values in the range for the dataset. * * @param dataset the dataset (<code>null</code> not permitted). * @param includeInterval a flag that determines whether or not the * y-interval is taken into account. * * @return The range (possibly <code>null</code>). */ public static Range findRangeBounds(CategoryDataset dataset, boolean includeInterval) { if (dataset == null) { throw new IllegalArgumentException("Null 'dataset' argument."); } Range result = null; if (dataset instanceof RangeInfo) { RangeInfo info = (RangeInfo) dataset; result = info.getRangeBounds(includeInterval); } else { result = iterateRangeBounds(dataset, includeInterval); } return result; } /** * Finds the bounds of the y-values in the specified dataset, including * only those series that are listed in visibleSeriesKeys. * * @param dataset the dataset (<code>null</code> not permitted). * @param visibleSeriesKeys the keys for the visible series * (<code>null</code> not permitted). * @param includeInterval include the y-interval (if the dataset has a * y-interval). * * @return The data bounds. * * @since 1.0.13 */ public static Range findRangeBounds(CategoryDataset dataset, List visibleSeriesKeys, boolean includeInterval) { if (dataset == null) { throw new IllegalArgumentException("Null 'dataset' argument."); } Range result = null; if (dataset instanceof CategoryRangeInfo) { CategoryRangeInfo info = (CategoryRangeInfo) dataset; result = info.getRangeBounds(visibleSeriesKeys, includeInterval); } else { result = iterateToFindRangeBounds(dataset, visibleSeriesKeys, includeInterval); } return result; } /** * Returns the range of values in the range for the dataset. This method * is the partner for the {@link #findDomainBounds(XYDataset)} method. * * @param dataset the dataset (<code>null</code> not permitted). * * @return The range (possibly <code>null</code>). */ public static Range findRangeBounds(XYDataset dataset) { return findRangeBounds(dataset, true); } /** * Returns the range of values in the range for the dataset. This method * is the partner for the {@link #findDomainBounds(XYDataset, boolean)} * method. * * @param dataset the dataset (<code>null</code> not permitted). * @param includeInterval a flag that determines whether or not the * y-interval is taken into account. * * @return The range (possibly <code>null</code>). */ public static Range findRangeBounds(XYDataset dataset, boolean includeInterval) { if (dataset == null) { throw new IllegalArgumentException("Null 'dataset' argument."); } Range result = null; if (dataset instanceof RangeInfo) { RangeInfo info = (RangeInfo) dataset; result = info.getRangeBounds(includeInterval); } else { result = iterateRangeBounds(dataset, includeInterval); } return result; } /** * Finds the bounds of the y-values in the specified dataset, including * only those series that are listed in visibleSeriesKeys, and those items * whose x-values fall within the specified range. * * @param dataset the dataset (<code>null</code> not permitted). * @param visibleSeriesKeys the keys for the visible series * (<code>null</code> not permitted). * @param xRange the x-range (<code>null</code> not permitted). * @param includeInterval include the y-interval (if the dataset has a * y-interval). * * @return The data bounds. * * @since 1.0.13 */ public static Range findRangeBounds(XYDataset dataset, List visibleSeriesKeys, Range xRange, boolean includeInterval) { if (dataset == null) { throw new IllegalArgumentException("Null 'dataset' argument."); } Range result = null; if (dataset instanceof XYRangeInfo) { XYRangeInfo info = (XYRangeInfo) dataset; result = info.getRangeBounds(visibleSeriesKeys, xRange, includeInterval); } else { result = iterateToFindRangeBounds(dataset, visibleSeriesKeys, xRange, includeInterval); } return result; } /** * Iterates over the data item of the category dataset to find * the range bounds. * * @param dataset the dataset (<code>null</code> not permitted). * @param includeInterval a flag that determines whether or not the * y-interval is taken into account. * * @return The range (possibly <code>null</code>). * * @deprecated As of 1.0.10, use * {@link #iterateRangeBounds(CategoryDataset, boolean)}. */ public static Range iterateCategoryRangeBounds(CategoryDataset dataset, boolean includeInterval) { return iterateRangeBounds(dataset, includeInterval); } /** * Iterates over the data item of the category dataset to find * the range bounds. * * @param dataset the dataset (<code>null</code> not permitted). * * @return The range (possibly <code>null</code>). * * @since 1.0.10 */ public static Range iterateRangeBounds(CategoryDataset dataset) { return iterateRangeBounds(dataset, true); } /** * Iterates over the data item of the category dataset to find * the range bounds. * * @param dataset the dataset (<code>null</code> not permitted). * @param includeInterval a flag that determines whether or not the * y-interval is taken into account. * * @return The range (possibly <code>null</code>). * * @since 1.0.10 */ public static Range iterateRangeBounds(CategoryDataset dataset, boolean includeInterval) { double minimum = Double.POSITIVE_INFINITY; double maximum = Double.NEGATIVE_INFINITY; int rowCount = dataset.getRowCount(); int columnCount = dataset.getColumnCount(); if (includeInterval && dataset instanceof IntervalCategoryDataset) { // handle the special case where the dataset has y-intervals that // we want to measure IntervalCategoryDataset icd = (IntervalCategoryDataset) dataset; Number lvalue, uvalue; for (int row = 0; row < rowCount; row++) { for (int column = 0; column < columnCount; column++) { lvalue = icd.getStartValue(row, column); uvalue = icd.getEndValue(row, column); if (lvalue != null && !Double.isNaN(lvalue.doubleValue())) { minimum = Math.min(minimum, lvalue.doubleValue()); } if (uvalue != null && !Double.isNaN(uvalue.doubleValue())) { maximum = Math.max(maximum, uvalue.doubleValue()); } } } } else { // handle the standard case (plain CategoryDataset) for (int row = 0; row < rowCount; row++) { for (int column = 0; column < columnCount; column++) { Number value = dataset.getValue(row, column); if (value != null) { double v = value.doubleValue(); if (!Double.isNaN(v)) { minimum = Math.min(minimum, v); maximum = Math.max(maximum, v); } } } } } if (minimum == Double.POSITIVE_INFINITY) { return null; } else { return new Range(minimum, maximum); } } /** * Iterates over the data item of the category dataset to find * the range bounds. * * @param dataset the dataset (<code>null</code> not permitted). * @param includeInterval a flag that determines whether or not the * y-interval is taken into account. * @param visibleSeriesKeys the visible series keys. * * @return The range (possibly <code>null</code>). * * @since 1.0.13 */ public static Range iterateToFindRangeBounds(CategoryDataset dataset, List visibleSeriesKeys, boolean includeInterval) { if (dataset == null) { throw new IllegalArgumentException("Null 'dataset' argument."); } if (visibleSeriesKeys == null) { throw new IllegalArgumentException( "Null 'visibleSeriesKeys' argument."); } double minimum = Double.POSITIVE_INFINITY; double maximum = Double.NEGATIVE_INFINITY; int columnCount = dataset.getColumnCount(); if (includeInterval && dataset instanceof IntervalCategoryDataset) { // handle the special case where the dataset has y-intervals that // we want to measure IntervalCategoryDataset icd = (IntervalCategoryDataset) dataset; Number lvalue, uvalue; Iterator iterator = visibleSeriesKeys.iterator(); while (iterator.hasNext()) { Comparable seriesKey = (Comparable) iterator.next(); int series = dataset.getRowIndex(seriesKey); for (int column = 0; column < columnCount; column++) { lvalue = icd.getStartValue(series, column); uvalue = icd.getEndValue(series, column); if (lvalue != null && !Double.isNaN(lvalue.doubleValue())) { minimum = Math.min(minimum, lvalue.doubleValue()); } if (uvalue != null && !Double.isNaN(uvalue.doubleValue())) { maximum = Math.max(maximum, uvalue.doubleValue()); } } } } else if (includeInterval && dataset instanceof StatisticalCategoryDataset) { // handle the special case where the dataset has y-intervals that // we want to measure StatisticalCategoryDataset scd = (StatisticalCategoryDataset) dataset; Iterator iterator = visibleSeriesKeys.iterator(); while (iterator.hasNext()) { Comparable seriesKey = (Comparable) iterator.next(); int series = dataset.getRowIndex(seriesKey); for (int column = 0; column < columnCount; column++) { Number meanN = scd.getMeanValue(series, column); if (meanN != null) { double std = 0.0; Number stdN = scd.getStdDevValue(series, column); if (stdN != null) { std = stdN.doubleValue(); if (Double.isNaN(std)) { std = 0.0; } } double mean = meanN.doubleValue(); if (!Double.isNaN(mean)) { minimum = Math.min(minimum, mean - std); maximum = Math.max(maximum, mean + std); } } } } } else { // handle the standard case (plain CategoryDataset) Iterator iterator = visibleSeriesKeys.iterator(); while (iterator.hasNext()) { Comparable seriesKey = (Comparable) iterator.next(); int series = dataset.getRowIndex(seriesKey); for (int column = 0; column < columnCount; column++) { Number value = dataset.getValue(series, column); if (value != null) { double v = value.doubleValue(); if (!Double.isNaN(v)) { minimum = Math.min(minimum, v); maximum = Math.max(maximum, v); } } } } } if (minimum == Double.POSITIVE_INFINITY) { return null; } else { return new Range(minimum, maximum); } } /** * Iterates over the data item of the xy dataset to find * the range bounds. * * @param dataset the dataset (<code>null</code> not permitted). * * @return The range (possibly <code>null</code>). * * @deprecated As of 1.0.10, use {@link #iterateRangeBounds(XYDataset)}. */ public static Range iterateXYRangeBounds(XYDataset dataset) { return iterateRangeBounds(dataset); } /** * Iterates over the data item of the xy dataset to find * the range bounds. * * @param dataset the dataset (<code>null</code> not permitted). * * @return The range (possibly <code>null</code>). * * @since 1.0.10 */ public static Range iterateRangeBounds(XYDataset dataset) { return iterateRangeBounds(dataset, true); } /** * Iterates over the data items of the xy dataset to find * the range bounds. * * @param dataset the dataset (<code>null</code> not permitted). * @param includeInterval a flag that determines, for an * {@link IntervalXYDataset}, whether the y-interval or just the * y-value is used to determine the overall range. * * @return The range (possibly <code>null</code>). * * @since 1.0.10 */ public static Range iterateRangeBounds(XYDataset dataset, boolean includeInterval) { double minimum = Double.POSITIVE_INFINITY; double maximum = Double.NEGATIVE_INFINITY; int seriesCount = dataset.getSeriesCount(); // handle three cases by dataset type if (includeInterval && dataset instanceof IntervalXYDataset) { // handle special case of IntervalXYDataset IntervalXYDataset ixyd = (IntervalXYDataset) dataset; for (int series = 0; series < seriesCount; series++) { int itemCount = dataset.getItemCount(series); for (int item = 0; item < itemCount; item++) { double lvalue = ixyd.getStartYValue(series, item); double uvalue = ixyd.getEndYValue(series, item); if (!Double.isNaN(lvalue)) { minimum = Math.min(minimum, lvalue); } if (!Double.isNaN(uvalue)) { maximum = Math.max(maximum, uvalue); } } } } else if (includeInterval && dataset instanceof OHLCDataset) { // handle special case of OHLCDataset OHLCDataset ohlc = (OHLCDataset) dataset; for (int series = 0; series < seriesCount; series++) { int itemCount = dataset.getItemCount(series); for (int item = 0; item < itemCount; item++) { double lvalue = ohlc.getLowValue(series, item); double uvalue = ohlc.getHighValue(series, item); if (!Double.isNaN(lvalue)) { minimum = Math.min(minimum, lvalue); } if (!Double.isNaN(uvalue)) { maximum = Math.max(maximum, uvalue); } } } } else { // standard case - plain XYDataset for (int series = 0; series < seriesCount; series++) { int itemCount = dataset.getItemCount(series); for (int item = 0; item < itemCount; item++) { double value = dataset.getYValue(series, item); if (!Double.isNaN(value)) { minimum = Math.min(minimum, value); maximum = Math.max(maximum, value); } } } } if (minimum == Double.POSITIVE_INFINITY) { return null; } else { return new Range(minimum, maximum); } } /** * Returns the range of x-values in the specified dataset for the * data items belonging to the visible series. * * @param dataset the dataset (<code>null</code> not permitted). * @param visibleSeriesKeys the visible series keys (<code>null</code> not * permitted). * @param includeInterval a flag that determines whether or not the * y-interval for the dataset is included (this only applies if the * dataset is an instance of IntervalXYDataset). * * @return The x-range (possibly <code>null</code>). * * @since 1.0.13 */ public static Range iterateToFindDomainBounds(XYDataset dataset, List visibleSeriesKeys, boolean includeInterval) { if (dataset == null) { throw new IllegalArgumentException("Null 'dataset' argument."); } if (visibleSeriesKeys == null) { throw new IllegalArgumentException( "Null 'visibleSeriesKeys' argument."); } double minimum = Double.POSITIVE_INFINITY; double maximum = Double.NEGATIVE_INFINITY; if (includeInterval && dataset instanceof IntervalXYDataset) { // handle special case of IntervalXYDataset IntervalXYDataset ixyd = (IntervalXYDataset) dataset; Iterator iterator = visibleSeriesKeys.iterator(); while (iterator.hasNext()) { Comparable seriesKey = (Comparable) iterator.next(); int series = dataset.indexOf(seriesKey); int itemCount = dataset.getItemCount(series); for (int item = 0; item < itemCount; item++) { double lvalue = ixyd.getStartXValue(series, item); double uvalue = ixyd.getEndXValue(series, item); if (!Double.isNaN(lvalue)) { minimum = Math.min(minimum, lvalue); } if (!Double.isNaN(uvalue)) { maximum = Math.max(maximum, uvalue); } } } } else { // standard case - plain XYDataset Iterator iterator = visibleSeriesKeys.iterator(); while (iterator.hasNext()) { Comparable seriesKey = (Comparable) iterator.next(); int series = dataset.indexOf(seriesKey); int itemCount = dataset.getItemCount(series); for (int item = 0; item < itemCount; item++) { double x = dataset.getXValue(series, item); if (!Double.isNaN(x)) { minimum = Math.min(minimum, x); maximum = Math.max(maximum, x); } } } } if (minimum == Double.POSITIVE_INFINITY) { return null; } else { return new Range(minimum, maximum); } } /** * Returns the range of y-values in the specified dataset for the * data items belonging to the visible series and with x-values in the * given range. * * @param dataset the dataset (<code>null</code> not permitted). * @param visibleSeriesKeys the visible series keys (<code>null</code> not * permitted). * @param xRange the x-range (<code>null</code> not permitted). * @param includeInterval a flag that determines whether or not the * y-interval for the dataset is included (this only applies if the * dataset is an instance of IntervalXYDataset). * * @return The y-range (possibly <code>null</code>). * * @since 1.0.13 */ public static Range iterateToFindRangeBounds(XYDataset dataset, List visibleSeriesKeys, Range xRange, boolean includeInterval) { if (dataset == null) { throw new IllegalArgumentException("Null 'dataset' argument."); } if (visibleSeriesKeys == null) { throw new IllegalArgumentException( "Null 'visibleSeriesKeys' argument."); } if (xRange == null) { throw new IllegalArgumentException("Null 'xRange' argument"); } double minimum = Double.POSITIVE_INFINITY; double maximum = Double.NEGATIVE_INFINITY; // handle three cases by dataset type if (includeInterval && dataset instanceof OHLCDataset) { // handle special case of OHLCDataset OHLCDataset ohlc = (OHLCDataset) dataset; Iterator iterator = visibleSeriesKeys.iterator(); while (iterator.hasNext()) { Comparable seriesKey = (Comparable) iterator.next(); int series = dataset.indexOf(seriesKey); int itemCount = dataset.getItemCount(series); for (int item = 0; item < itemCount; item++) { double x = ohlc.getXValue(series, item); if (xRange.contains(x)) { double lvalue = ohlc.getLowValue(series, item); double uvalue = ohlc.getHighValue(series, item); if (!Double.isNaN(lvalue)) { minimum = Math.min(minimum, lvalue); } if (!Double.isNaN(uvalue)) { maximum = Math.max(maximum, uvalue); } } } } } else if (includeInterval && dataset instanceof BoxAndWhiskerXYDataset) { // handle special case of BoxAndWhiskerXYDataset BoxAndWhiskerXYDataset bx = (BoxAndWhiskerXYDataset) dataset; Iterator iterator = visibleSeriesKeys.iterator(); while (iterator.hasNext()) { Comparable seriesKey = (Comparable) iterator.next(); int series = dataset.indexOf(seriesKey); int itemCount = dataset.getItemCount(series); for (int item = 0; item < itemCount; item++) { double x = bx.getXValue(series, item); if (xRange.contains(x)) { Number lvalue = bx.getMinRegularValue(series, item); Number uvalue = bx.getMaxRegularValue(series, item); if (lvalue != null) { minimum = Math.min(minimum, lvalue.doubleValue()); } if (uvalue != null) { maximum = Math.max(maximum, uvalue.doubleValue()); } } } } } else if (includeInterval && dataset instanceof IntervalXYDataset) { // handle special case of IntervalXYDataset IntervalXYDataset ixyd = (IntervalXYDataset) dataset; Iterator iterator = visibleSeriesKeys.iterator(); while (iterator.hasNext()) { Comparable seriesKey = (Comparable) iterator.next(); int series = dataset.indexOf(seriesKey); int itemCount = dataset.getItemCount(series); for (int item = 0; item < itemCount; item++) { double x = ixyd.getXValue(series, item); if (xRange.contains(x)) { double lvalue = ixyd.getStartYValue(series, item); double uvalue = ixyd.getEndYValue(series, item); if (!Double.isNaN(lvalue)) { minimum = Math.min(minimum, lvalue); } if (!Double.isNaN(uvalue)) { maximum = Math.max(maximum, uvalue); } } } } } else { // standard case - plain XYDataset Iterator iterator = visibleSeriesKeys.iterator(); while (iterator.hasNext()) { Comparable seriesKey = (Comparable) iterator.next(); int series = dataset.indexOf(seriesKey); int itemCount = dataset.getItemCount(series); for (int item = 0; item < itemCount; item++) { double x = dataset.getXValue(series, item); double y = dataset.getYValue(series, item); if (xRange.contains(x)) { if (!Double.isNaN(y)) { minimum = Math.min(minimum, y); maximum = Math.max(maximum, y); } } } } } if (minimum == Double.POSITIVE_INFINITY) { return null; } else { return new Range(minimum, maximum); } } /** * Finds the minimum domain (or X) value for the specified dataset. This * is easy if the dataset implements the {@link DomainInfo} interface (a * good idea if there is an efficient way to determine the minimum value). * Otherwise, it involves iterating over the entire data-set. * <p> * Returns <code>null</code> if all the data values in the dataset are * <code>null</code>. * * @param dataset the dataset (<code>null</code> not permitted). * * @return The minimum value (possibly <code>null</code>). */ public static Number findMinimumDomainValue(XYDataset dataset) { if (dataset == null) { throw new IllegalArgumentException("Null 'dataset' argument."); } Number result = null; // if the dataset implements DomainInfo, life is easy if (dataset instanceof DomainInfo) { DomainInfo info = (DomainInfo) dataset; return new Double(info.getDomainLowerBound(true)); } else { double minimum = Double.POSITIVE_INFINITY; int seriesCount = dataset.getSeriesCount(); for (int series = 0; series < seriesCount; series++) { int itemCount = dataset.getItemCount(series); for (int item = 0; item < itemCount; item++) { double value; if (dataset instanceof IntervalXYDataset) { IntervalXYDataset intervalXYData = (IntervalXYDataset) dataset; value = intervalXYData.getStartXValue(series, item); } else { value = dataset.getXValue(series, item); } if (!Double.isNaN(value)) { minimum = Math.min(minimum, value); } } } if (minimum == Double.POSITIVE_INFINITY) { result = null; } else { result = new Double(minimum); } } return result; } /** * Returns the maximum domain value for the specified dataset. This is * easy if the dataset implements the {@link DomainInfo} interface (a good * idea if there is an efficient way to determine the maximum value). * Otherwise, it involves iterating over the entire data-set. Returns * <code>null</code> if all the data values in the dataset are * <code>null</code>. * * @param dataset the dataset (<code>null</code> not permitted). * * @return The maximum value (possibly <code>null</code>). */ public static Number findMaximumDomainValue(XYDataset dataset) { if (dataset == null) { throw new IllegalArgumentException("Null 'dataset' argument."); } Number result = null; // if the dataset implements DomainInfo, life is easy if (dataset instanceof DomainInfo) { DomainInfo info = (DomainInfo) dataset; return new Double(info.getDomainUpperBound(true)); } // hasn't implemented DomainInfo, so iterate... else { double maximum = Double.NEGATIVE_INFINITY; int seriesCount = dataset.getSeriesCount(); for (int series = 0; series < seriesCount; series++) { int itemCount = dataset.getItemCount(series); for (int item = 0; item < itemCount; item++) { double value; if (dataset instanceof IntervalXYDataset) { IntervalXYDataset intervalXYData = (IntervalXYDataset) dataset; value = intervalXYData.getEndXValue(series, item); } else { value = dataset.getXValue(series, item); } if (!Double.isNaN(value)) { maximum = Math.max(maximum, value); } } } if (maximum == Double.NEGATIVE_INFINITY) { result = null; } else { result = new Double(maximum); } } return result; } /** * Returns the minimum range value for the specified dataset. This is * easy if the dataset implements the {@link RangeInfo} interface (a good * idea if there is an efficient way to determine the minimum value). * Otherwise, it involves iterating over the entire data-set. Returns * <code>null</code> if all the data values in the dataset are * <code>null</code>. * * @param dataset the dataset (<code>null</code> not permitted). * * @return The minimum value (possibly <code>null</code>). */ public static Number findMinimumRangeValue(CategoryDataset dataset) { if (dataset == null) { throw new IllegalArgumentException("Null 'dataset' argument."); } if (dataset instanceof RangeInfo) { RangeInfo info = (RangeInfo) dataset; return new Double(info.getRangeLowerBound(true)); } // hasn't implemented RangeInfo, so we'll have to iterate... else { double minimum = Double.POSITIVE_INFINITY; int seriesCount = dataset.getRowCount(); int itemCount = dataset.getColumnCount(); for (int series = 0; series < seriesCount; series++) { for (int item = 0; item < itemCount; item++) { Number value; if (dataset instanceof IntervalCategoryDataset) { IntervalCategoryDataset icd = (IntervalCategoryDataset) dataset; value = icd.getStartValue(series, item); } else { value = dataset.getValue(series, item); } if (value != null) { minimum = Math.min(minimum, value.doubleValue()); } } } if (minimum == Double.POSITIVE_INFINITY) { return null; } else { return new Double(minimum); } } } /** * Returns the minimum range value for the specified dataset. This is * easy if the dataset implements the {@link RangeInfo} interface (a good * idea if there is an efficient way to determine the minimum value). * Otherwise, it involves iterating over the entire data-set. Returns * <code>null</code> if all the data values in the dataset are * <code>null</code>. * * @param dataset the dataset (<code>null</code> not permitted). * * @return The minimum value (possibly <code>null</code>). */ public static Number findMinimumRangeValue(XYDataset dataset) { if (dataset == null) { throw new IllegalArgumentException("Null 'dataset' argument."); } // work out the minimum value... if (dataset instanceof RangeInfo) { RangeInfo info = (RangeInfo) dataset; return new Double(info.getRangeLowerBound(true)); } // hasn't implemented RangeInfo, so we'll have to iterate... else { double minimum = Double.POSITIVE_INFINITY; int seriesCount = dataset.getSeriesCount(); for (int series = 0; series < seriesCount; series++) { int itemCount = dataset.getItemCount(series); for (int item = 0; item < itemCount; item++) { double value; if (dataset instanceof IntervalXYDataset) { IntervalXYDataset intervalXYData = (IntervalXYDataset) dataset; value = intervalXYData.getStartYValue(series, item); } else if (dataset instanceof OHLCDataset) { OHLCDataset highLowData = (OHLCDataset) dataset; value = highLowData.getLowValue(series, item); } else { value = dataset.getYValue(series, item); } if (!Double.isNaN(value)) { minimum = Math.min(minimum, value); } } } if (minimum == Double.POSITIVE_INFINITY) { return null; } else { return new Double(minimum); } } } /** * Returns the maximum range value for the specified dataset. This is easy * if the dataset implements the {@link RangeInfo} interface (a good idea * if there is an efficient way to determine the maximum value). * Otherwise, it involves iterating over the entire data-set. Returns * <code>null</code> if all the data values are <code>null</code>. * * @param dataset the dataset (<code>null</code> not permitted). * * @return The maximum value (possibly <code>null</code>). */ public static Number findMaximumRangeValue(CategoryDataset dataset) { if (dataset == null) { throw new IllegalArgumentException("Null 'dataset' argument."); } // work out the minimum value... if (dataset instanceof RangeInfo) { RangeInfo info = (RangeInfo) dataset; return new Double(info.getRangeUpperBound(true)); } // hasn't implemented RangeInfo, so we'll have to iterate... else { double maximum = Double.NEGATIVE_INFINITY; int seriesCount = dataset.getRowCount(); int itemCount = dataset.getColumnCount(); for (int series = 0; series < seriesCount; series++) { for (int item = 0; item < itemCount; item++) { Number value; if (dataset instanceof IntervalCategoryDataset) { IntervalCategoryDataset icd = (IntervalCategoryDataset) dataset; value = icd.getEndValue(series, item); } else { value = dataset.getValue(series, item); } if (value != null) { maximum = Math.max(maximum, value.doubleValue()); } } } if (maximum == Double.NEGATIVE_INFINITY) { return null; } else { return new Double(maximum); } } } /** * Returns the maximum range value for the specified dataset. This is * easy if the dataset implements the {@link RangeInfo} interface (a good * idea if there is an efficient way to determine the maximum value). * Otherwise, it involves iterating over the entire data-set. Returns * <code>null</code> if all the data values are <code>null</code>. * * @param dataset the dataset (<code>null</code> not permitted). * * @return The maximum value (possibly <code>null</code>). */ public static Number findMaximumRangeValue(XYDataset dataset) { if (dataset == null) { throw new IllegalArgumentException("Null 'dataset' argument."); } // work out the minimum value... if (dataset instanceof RangeInfo) { RangeInfo info = (RangeInfo) dataset; return new Double(info.getRangeUpperBound(true)); } // hasn't implemented RangeInfo, so we'll have to iterate... else { double maximum = Double.NEGATIVE_INFINITY; int seriesCount = dataset.getSeriesCount(); for (int series = 0; series < seriesCount; series++) { int itemCount = dataset.getItemCount(series); for (int item = 0; item < itemCount; item++) { double value; if (dataset instanceof IntervalXYDataset) { IntervalXYDataset intervalXYData = (IntervalXYDataset) dataset; value = intervalXYData.getEndYValue(series, item); } else if (dataset instanceof OHLCDataset) { OHLCDataset highLowData = (OHLCDataset) dataset; value = highLowData.getHighValue(series, item); } else { value = dataset.getYValue(series, item); } if (!Double.isNaN(value)) { maximum = Math.max(maximum, value); } } } if (maximum == Double.NEGATIVE_INFINITY) { return null; } else { return new Double(maximum); } } } /** * Returns the minimum and maximum values for the dataset's range * (y-values), assuming that the series in one category are stacked. * * @param dataset the dataset (<code>null</code> not permitted). * * @return The range (<code>null</code> if the dataset contains no values). */ public static Range findStackedRangeBounds(CategoryDataset dataset) { return findStackedRangeBounds(dataset, 0.0); } /** * Returns the minimum and maximum values for the dataset's range * (y-values), assuming that the series in one category are stacked. * * @param dataset the dataset (<code>null</code> not permitted). * @param base the base value for the bars. * * @return The range (<code>null</code> if the dataset contains no values). */ public static Range findStackedRangeBounds(CategoryDataset dataset, double base) { if (dataset == null) { throw new IllegalArgumentException("Null 'dataset' argument."); } Range result = null; double minimum = Double.POSITIVE_INFINITY; double maximum = Double.NEGATIVE_INFINITY; int categoryCount = dataset.getColumnCount(); for (int item = 0; item < categoryCount; item++) { double positive = base; double negative = base; int seriesCount = dataset.getRowCount(); for (int series = 0; series < seriesCount; series++) { Number number = dataset.getValue(series, item); if (number != null) { double value = number.doubleValue(); if (value > 0.0) { positive = positive + value; } if (value < 0.0) { negative = negative + value; // '+', remember value is negative } } } minimum = Math.min(minimum, negative); maximum = Math.max(maximum, positive); } if (minimum <= maximum) { result = new Range(minimum, maximum); } return result; } /** * Returns the minimum and maximum values for the dataset's range * (y-values), assuming that the series in one category are stacked. * * @param dataset the dataset. * @param map a structure that maps series to groups. * * @return The value range (<code>null</code> if the dataset contains no * values). */ public static Range findStackedRangeBounds(CategoryDataset dataset, KeyToGroupMap map) { if (dataset == null) { throw new IllegalArgumentException("Null 'dataset' argument."); } boolean hasValidData = false; Range result = null; // create an array holding the group indices for each series... int[] groupIndex = new int[dataset.getRowCount()]; for (int i = 0; i < dataset.getRowCount(); i++) { groupIndex[i] = map.getGroupIndex(map.getGroup( dataset.getRowKey(i))); } // minimum and maximum for each group... int groupCount = map.getGroupCount(); double[] minimum = new double[groupCount]; double[] maximum = new double[groupCount]; int categoryCount = dataset.getColumnCount(); for (int item = 0; item < categoryCount; item++) { double[] positive = new double[groupCount]; double[] negative = new double[groupCount]; int seriesCount = dataset.getRowCount(); for (int series = 0; series < seriesCount; series++) { Number number = dataset.getValue(series, item); if (number != null) { hasValidData = true; double value = number.doubleValue(); if (value > 0.0) { positive[groupIndex[series]] = positive[groupIndex[series]] + value; } if (value < 0.0) { negative[groupIndex[series]] = negative[groupIndex[series]] + value; // '+', remember value is negative } } } for (int g = 0; g < groupCount; g++) { minimum[g] = Math.min(minimum[g], negative[g]); maximum[g] = Math.max(maximum[g], positive[g]); } } if (hasValidData) { for (int j = 0; j < groupCount; j++) { result = Range.combine(result, new Range(minimum[j], maximum[j])); } } return result; } /** * Returns the minimum value in the dataset range, assuming that values in * each category are "stacked". * * @param dataset the dataset (<code>null</code> not permitted). * * @return The minimum value. * * @see #findMaximumStackedRangeValue(CategoryDataset) */ public static Number findMinimumStackedRangeValue(CategoryDataset dataset) { if (dataset == null) { throw new IllegalArgumentException("Null 'dataset' argument."); } Number result = null; boolean hasValidData = false; double minimum = 0.0; int categoryCount = dataset.getColumnCount(); for (int item = 0; item < categoryCount; item++) { double total = 0.0; int seriesCount = dataset.getRowCount(); for (int series = 0; series < seriesCount; series++) { Number number = dataset.getValue(series, item); if (number != null) { hasValidData = true; double value = number.doubleValue(); if (value < 0.0) { total = total + value; // '+', remember value is negative } } } minimum = Math.min(minimum, total); } if (hasValidData) { result = new Double(minimum); } return result; } /** * Returns the maximum value in the dataset range, assuming that values in * each category are "stacked". * * @param dataset the dataset (<code>null</code> not permitted). * * @return The maximum value (possibly <code>null</code>). * * @see #findMinimumStackedRangeValue(CategoryDataset) */ public static Number findMaximumStackedRangeValue(CategoryDataset dataset) { if (dataset == null) { throw new IllegalArgumentException("Null 'dataset' argument."); } Number result = null; boolean hasValidData = false; double maximum = 0.0; int categoryCount = dataset.getColumnCount(); for (int item = 0; item < categoryCount; item++) { double total = 0.0; int seriesCount = dataset.getRowCount(); for (int series = 0; series < seriesCount; series++) { Number number = dataset.getValue(series, item); if (number != null) { hasValidData = true; double value = number.doubleValue(); if (value > 0.0) { total = total + value; } } } maximum = Math.max(maximum, total); } if (hasValidData) { result = new Double(maximum); } return result; } /** * Returns the minimum and maximum values for the dataset's range, * assuming that the series are stacked. * * @param dataset the dataset (<code>null</code> not permitted). * * @return The range ([0.0, 0.0] if the dataset contains no values). */ public static Range findStackedRangeBounds(TableXYDataset dataset) { return findStackedRangeBounds(dataset, 0.0); } /** * Returns the minimum and maximum values for the dataset's range, * assuming that the series are stacked, using the specified base value. * * @param dataset the dataset (<code>null</code> not permitted). * @param base the base value. * * @return The range (<code>null</code> if the dataset contains no values). */ public static Range findStackedRangeBounds(TableXYDataset dataset, double base) { if (dataset == null) { throw new IllegalArgumentException("Null 'dataset' argument."); } double minimum = base; double maximum = base; for (int itemNo = 0; itemNo < dataset.getItemCount(); itemNo++) { double positive = base; double negative = base; int seriesCount = dataset.getSeriesCount(); for (int seriesNo = 0; seriesNo < seriesCount; seriesNo++) { double y = dataset.getYValue(seriesNo, itemNo); if (!Double.isNaN(y)) { if (y > 0.0) { positive += y; } else { negative += y; } } } if (positive > maximum) { maximum = positive; } if (negative < minimum) { minimum = negative; } } if (minimum <= maximum) { return new Range(minimum, maximum); } else { return null; } } /** * Calculates the total for the y-values in all series for a given item * index. * * @param dataset the dataset. * @param item the item index. * * @return The total. * * @since 1.0.5 */ public static double calculateStackTotal(TableXYDataset dataset, int item) { double total = 0.0; int seriesCount = dataset.getSeriesCount(); for (int s = 0; s < seriesCount; s++) { double value = dataset.getYValue(s, item); if (!Double.isNaN(value)) { total = total + value; } } return total; } /** * Calculates the range of values for a dataset where each item is the * running total of the items for the current series. * * @param dataset the dataset (<code>null</code> not permitted). * * @return The range. * * @see #findRangeBounds(CategoryDataset) */ public static Range findCumulativeRangeBounds(CategoryDataset dataset) { if (dataset == null) { throw new IllegalArgumentException("Null 'dataset' argument."); } boolean allItemsNull = true; // we'll set this to false if there is at // least one non-null data item... double minimum = 0.0; double maximum = 0.0; for (int row = 0; row < dataset.getRowCount(); row++) { double runningTotal = 0.0; for (int column = 0; column <= dataset.getColumnCount() - 1; column++) { Number n = dataset.getValue(row, column); if (n != null) { allItemsNull = false; double value = n.doubleValue(); if (!Double.isNaN(value)) { runningTotal = runningTotal + value; minimum = Math.min(minimum, runningTotal); maximum = Math.max(maximum, runningTotal); } } } } if (!allItemsNull) { return new Range(minimum, maximum); } else { return null; } } }
package edu.umd.cs.daveho.ba; import java.util.*; // We require BCEL 5.0 or later. import org.apache.bcel.*; import org.apache.bcel.classfile.*; import org.apache.bcel.generic.*; /** * Build a control flow graph for a method. * This is an ad-hoc implementation which does not do type * analysis of the stack, and thus cannot precisely figure out * what kind of exceptions can be thrown. So, the CFGs produced * contain many infeasible exception edges. * * <p> <b>Treatment of JSR and RET instructions</b>: branches to JSR subroutines * are <em>not</em> treated as control flow. Instead, they are logically * inlined into the current stream of control. Thus, the instructions * in a JSR subroutine may appear in multiple basic blocks. * This treatment accurately captures the semantics of JSR subroutines * in a way that is not possible with control flow edges. * However, for instructions in a JSR subroutine, it makes it impossible * to know a priori what basic block they are part of, since they * may be part of several. * * <p> FIXME: this class is overdue to be rewritten. * * @see CFGBuilder * @author David Hovemeyer */ public class BasicCFGBuilder extends BaseCFGBuilder implements EdgeTypes, CFGBuilderModes { private LinkedList<WorkListItem> workList; private IdentityHashMap<InstructionHandle, List<InstructionHandle>> exceptionHandlerMap; private IdentityHashMap<InstructionHandle, CodeExceptionGen> exceptionGenMap; private HashSet<InstructionHandle> bbHandles; // all InstructionHandles assigned to BasicBlocks private IdentityHashMap<InstructionHandle, BasicBlock> firstInsToBBMap; private int mode; private static final boolean NO_RET_MERGE = Boolean.getBoolean("cfgbuilder.noRetMerge"); private static final boolean DEBUG = Boolean.getBoolean("cfgbuilder.debug"); /** * Constructor. * @param method the Method to build the CFG for * @param methodGen a MethodGen object whose InstructionHandles will be referenced by the CFG */ public BasicCFGBuilder(MethodGen methodGen) { super(methodGen); firstInsToBBMap = new IdentityHashMap<InstructionHandle, BasicBlock>(); workList = new LinkedList<WorkListItem>(); exceptionHandlerMap = new IdentityHashMap<InstructionHandle, List<InstructionHandle>>(); exceptionGenMap = new IdentityHashMap<InstructionHandle, CodeExceptionGen>(); buildExceptionHandlerMap(); bbHandles = new HashSet<InstructionHandle>(); } /** * Set mode; see the constants in {@link CFGBuilderModes}. */ public void setMode(int mode) { this.mode = mode; } private static final LinkedList<InstructionHandle> emptyStack = new LinkedList<InstructionHandle>(); /** * A worklist item. */ private static final class WorkListItem { /** First instruction in the basic block. */ public final InstructionHandle firstInstruction; /** The basic block. */ public final BasicBlock bb; /** Stack of JSR instructions. The most recently executed JSR is on top. */ public final LinkedList<InstructionHandle> jsrStack; /** * Constructor. * @param firstInstruction the first instruction in the basic block * @param bb the basic block * @param jsrStack stack of JSR instructions */ public WorkListItem(InstructionHandle firstInstruction, BasicBlock bb, LinkedList<InstructionHandle> jsrStack) { this.firstInstruction = firstInstruction; this.bb = bb; this.jsrStack = jsrStack; } } /** * Build the control-flow graph. */ public void build() { InstructionHandle first = methodGen.getInstructionList().getStart(); BasicBlock start = getBlock(first, emptyStack); // adds start block to work list addEdge(cfg.getEntry(), start, START_EDGE);// add edge from entry to start block // Keep going until worklist is empty. // This will construct basic blocks and add normal control flow and // handled exception edges. while (!workList.isEmpty()) { WorkListItem item = (WorkListItem) workList.removeFirst(); BasicBlock bb = item.bb; LinkedList<InstructionHandle> jsrStack = item.jsrStack; // Scan through instructions, adding them to the basic block, // until we get to a branch or merge (either of which ends the block). InstructionHandle handle = item.firstInstruction, next; if (DEBUG) System.out.println("START: " + handle); TargetEnumeratingVisitor visitor = null; boolean isMerge = false; boolean isPotentialThrow = false; while (true) { if (handle == null) throw new IllegalStateException(); if (DEBUG) System.out.println("ADDING: " + handle); bb.addInstruction(handle); // This variable will be assigned if control transfers to // an instruction which is not the next in the PC value sequence; // i.e., for JSR or RET instructions. next = null; // Mark the instruction as now being a member of a BasicBlock. // Note that an instruction may not be part of two basic blocks // UNLESS it is reachable by a JSR instruction. assert !bbHandles.contains(handle) || inSubroutine(jsrStack); bbHandles.add(handle); Instruction ins = handle.getInstruction(); // Handle JSRs, RETs, and branch instructions. if (ins instanceof JsrInstruction) { // JSR subroutines are inlined into the current // control flow path. jsrStack.addLast(handle); // remember where we came from JsrInstruction jsr = (JsrInstruction) ins; next = jsr.getTarget(); // transfer control to the subroutine } else if (ins instanceof RET) { // Return control to the instruction following // the most recently executed JSR. next = jsrStack.removeLast().getNext(); // return control to ins after JSR if (!NO_RET_MERGE) { isMerge = true; // conservatively assume that RET ends the basic block break; } } else { // See if the instruction is some kind of branch. // See if this instruction is a branch (thus ending the BasicBlock) visitor = new TargetEnumeratingVisitor(handle, methodGen.getConstantPool()); if (visitor.isEndOfBasicBlock()) break; } // If we're in INSTRUCTION_MODE, each instruction is a separate basic block. if (mode == INSTRUCTION_MODE) { isMerge = true; break; } if (next == null) next = handle.getNext(); if (next == null) throw new IllegalStateException("No next?: " + handle); // See if the next instruction is a control flow merge // (which would make the current instruction the end of // the basic block.) if (isMerge(next)) { isMerge = true; break; } // If we're in EXCEPTION_SENSITIVE_MODE and the current instruction // is a potential exception thrower, end the basic block. if (mode == EXCEPTION_SENSITIVE_MODE && (handle.getInstruction() instanceof ExceptionThrower)) { isPotentialThrow = true; break; } // Continue to next instruction handle = next; assert handle != null; } if (DEBUG) System.out.println("END: " + handle); // Add exception edges from the basic block to all possible handlers. addExceptionEdges(bb, jsrStack); if (isMerge) { // Fall through. addFallThroughEdge(bb, next, jsrStack); } else if (visitor.instructionIsReturn() || visitor.instructionIsExit()) { // Return from method (or process exit, which we treat as method return). addEdge(bb, cfg.getExit(), RETURN_EDGE); } else if (visitor.instructionIsThrow()) { // NOTE: nothing to do - unhandled exceptions will be taken // care of after the main worklist loop has completed. } else if (isPotentialThrow) { // Instruction has been marked as a potential exception thrower, // and we're in EXCEPTION_SENSITIVE_MODE. Add a fall through // edge to the next instruction, if there is one. if (next != null) addFallThroughEdge(bb, next, jsrStack); } else { // Explicit branch. addBranchEdges(bb, visitor, jsrStack); } } // For each basic block containing instructions which can throw // exceptions, add unhandled exception edges. We conservatively // assume that any basic block capable of throwing an exception // may throw throw the exception out of the method. Iterator<BasicBlock> bbIter = cfg.blockIterator(); while (bbIter.hasNext()) { BasicBlock bb = bbIter.next(); boolean canThrow = false; Iterator<InstructionHandle> insIter = bb.instructionIterator(); while (insIter.hasNext()) { InstructionHandle handle = insIter.next(); Instruction ins = handle.getInstruction(); if (ins instanceof ExceptionThrower) { ExceptionThrower exceptionThrower = (ExceptionThrower) ins; java.lang.Class[] exceptionList = exceptionThrower.getExceptions(); if (exceptionList.length > 0) { canThrow = true; break; } } } if (canThrow) // Unhandled exception edges can duplicate ordinary return edges addDuplicateEdge(bb, cfg.getExit(), UNHANDLED_EXCEPTION_EDGE); } if (VERIFY_INTEGRITY) cfg.checkIntegrity(); } /** * Add edges for explicitly handled exceptions. * @param sourceBB the source basic block * @param jsrStack stack of most recently executed JSR instructions */ private void addExceptionEdges(BasicBlock sourceBB, LinkedList<InstructionHandle> jsrStack) { if (sourceBB.isEmpty()) return; HashSet<InstructionHandle> exceptionHandlerSet = new HashSet<InstructionHandle>(); { // Find set of all exception handlers for each instruction // in the basic block Iterator<InstructionHandle> i = sourceBB.instructionIterator(); while (i.hasNext()) { InstructionHandle cur = i.next(); List<InstructionHandle> handlerList = exceptionHandlerMap.get(cur); if (handlerList != null) exceptionHandlerSet.addAll(handlerList); } } { // Add edges from the source BB to all exception handler BBs Iterator<InstructionHandle> i = exceptionHandlerSet.iterator(); while (i.hasNext()) { InstructionHandle target= i.next(); BasicBlock targetBB = getBlock(target, jsrStack); addEdge(sourceBB, targetBB, HANDLED_EXCEPTION_EDGE); } } } /** * Determine whether or not the instruction whose handle is given * is a control-flow merge. * @param handle the instruction handle */ private boolean isMerge(InstructionHandle handle) { if (handle.hasTargeters()) { // Check all targeters of this handle to see if any // of them are branches. Note that we don't consider JSR // instructions to be branches, since we inline JSR subroutines. InstructionTargeter[] targeterList = handle.getTargeters(); for (int i = 0; i < targeterList.length; ++i) { InstructionTargeter targeter = targeterList[i]; if (targeter instanceof BranchInstruction && !(targeter instanceof JsrInstruction)) { if (DEBUG) System.out.println("MERGE!"); return true; } } } return false; } /** * Add fall through edge (when a basic block ends in a control flow merge). * @param sourceBB the source basic block * @param next the first instruction to be executed in the new basic block * @param jsrStack stack of most recently executed JSR instructions */ private void addFallThroughEdge(BasicBlock sourceBB, InstructionHandle next, LinkedList<InstructionHandle> jsrStack) { if (next == null) throw new IllegalStateException(); // Fall through to the next instruction. BasicBlock successor = getBlock(next, jsrStack); addEdge(sourceBB, successor, FALL_THROUGH_EDGE); } /** * Add edges for explicit branch instruction. * The visitor has accumulated all of the possible branch targets. * @param sourceBB the source basic block * @param visitor the instruction visitor containing the branch targets * @param jsrStack stack of most recently executed JSR instructions */ private void addBranchEdges(BasicBlock sourceBB, TargetEnumeratingVisitor visitor, LinkedList<InstructionHandle> jsrStack) { // Scan through targets of the last instruction in the block. for (Iterator i = visitor.targetIterator(); i.hasNext(); ) { Target target = (Target) i.next(); // Get the target BasicBlock. // This will add it to the work list if necessary. BasicBlock targetBB = getBlock(target.getTargetInstruction(), jsrStack); // Add CFG edge // Note that a switch statement may have many labels for the // same target. We do not (currently) consider these as // separate edges. if (cfg.lookupEdge(sourceBB, targetBB) == null) // Add only if no edge with same source and target already exists addEdge(sourceBB, targetBB, target.getEdgeType()); } } private static final boolean EXCEPTION_SELF_HANDLER_HACK = true; //Boolean.getBoolean("cfg.exceptionSelfHandlerHack"); /** * Build map of instructions to lists of potential exception handlers. * As a side effect, this also builds a map of instructions which are the * start of an exception handler to the CodeExceptionGen object * representing the handler. */ private void buildExceptionHandlerMap() { CodeExceptionGen[] exceptionHandlerList = methodGen.getExceptionHandlers(); for (int i = 0; i < exceptionHandlerList.length; ++i) { CodeExceptionGen exceptionGen = exceptionHandlerList[i]; InstructionHandle entry = exceptionGen.getHandlerPC(); // The classfiles for lucene 1.2 have exception handlers that // handle themselves! As a hack, ignore such handlers. if (EXCEPTION_SELF_HANDLER_HACK) { if (exceptionGen.getStartPC() == entry) { //System.out.println("Ignoring exception self-handler in class " + methodGen.getClassName() + "." + methodGen.getName()); continue; } } exceptionGenMap.put(entry, exceptionGen); // VM Spec, 4.7.3. The end_pc value for an exception handler // is exclusive, not inclusive. InstructionHandle handle = exceptionGen.getStartPC(); while (handle != exceptionGen.getEndPC()) { List<InstructionHandle> entryList = exceptionHandlerMap.get(handle); if (entryList == null) { entryList = new LinkedList<InstructionHandle>(); exceptionHandlerMap.put(handle, entryList); } entryList.add(entry); handle = handle.getNext(); } } } /** * Get basic block whose given instruction is that given. * If the block already exists, returns it. Otherwise, creates * a new block and adds it to the work list. * @param ins the handle of the instruction for which we want the basic block * @param jsrStack stack of most recently executed JSR instructions */ private BasicBlock getBlock(InstructionHandle ins, LinkedList<InstructionHandle> jsrStack) { if (ins == null) throw new IllegalStateException(); BasicBlock bb = firstInsToBBMap.get(ins); if (bb == null) { if (DEBUG) System.out.println("Adding BasicBlock for " + ins); // Allocate a new basic block bb = cfg.allocate(); firstInsToBBMap.put(ins, bb); bb.addInstruction(ins); // If this is the entry point of an exception handler, mark it as such bb.setExceptionGen(exceptionGenMap.get(ins)); // Add the block to the worklist workList.add(new WorkListItem(ins, bb, cloneJsrStack(jsrStack))); } return bb; } /** * Make a copy of the given JSR stack. * We do this because handling JSR and RET instructions modifies the * JSR stack; hence, work list items cannot share them. * @param jsrStack stack of most recently executed JSR instructions */ private LinkedList<InstructionHandle> cloneJsrStack(LinkedList<InstructionHandle> jsrStack) { LinkedList<InstructionHandle> dup = new LinkedList<InstructionHandle>(); dup.addAll(jsrStack); return dup; } /** * Based on the current JSR stack, determine whether or not * we are in a JSR subroutine. */ private boolean inSubroutine(LinkedList<InstructionHandle> jsrStack) { return !jsrStack.isEmpty(); } } // vim:ts=4
package org.opencms.db.generic; import org.opencms.db.CmsDriverManager; import org.opencms.db.CmsExportPointDriver; import org.opencms.db.I_CmsDriver; import org.opencms.db.I_CmsProjectDriver; import org.opencms.lock.CmsLock; import org.opencms.main.OpenCms; import org.opencms.report.I_CmsReport; import org.opencms.workflow.CmsTask; import org.opencms.workflow.CmsTaskLog; import com.opencms.boot.I_CmsLogChannels; import com.opencms.core.CmsException; import com.opencms.core.I_CmsConstants; import com.opencms.file.CmsFile; import com.opencms.file.CmsFolder; import com.opencms.file.CmsGroup; import com.opencms.file.CmsObject; import com.opencms.file.CmsProject; import com.opencms.file.CmsRequestContext; import com.opencms.file.CmsResource; import com.opencms.file.CmsUser; import com.opencms.flex.CmsEvent; import com.opencms.flex.I_CmsEventListener; import com.opencms.flex.util.CmsUUID; import com.opencms.linkmanagement.CmsPageLinks; import com.opencms.util.SqlHelper; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.EOFException; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Vector; import source.org.apache.java.util.Configurations; public class CmsProjectDriver extends Object implements I_CmsDriver, I_CmsProjectDriver { /** * Constant to get property from configurations. */ protected static String C_CONFIGURATIONS_DIGEST = "digest"; /** * Constant to get property from configurations. */ protected static String C_CONFIGURATIONS_DIGEST_FILE_ENCODING = "digest.fileencoding"; /** * Constant to get property from configurations. */ protected static String C_CONFIGURATIONS_POOL = "pool"; /** * The maximum amount of tables. */ protected static int C_MAX_TABLES = 18; public static int C_RESTYPE_LINK_ID = 2; /** * The session-timeout value: * currently six hours. After that time the session can't be restored. */ public static long C_SESSION_TIMEOUT = 6 * 60 * 60 * 1000; /** * Table-key for max-id */ protected static String C_TABLE_PROJECTS = "CMS_PROJECTS"; /** * Table-key for max-id */ protected static String C_TABLE_PROPERTIES = "CMS_PROPERTIES"; /** * Table-key for max-id */ protected static String C_TABLE_PROPERTYDEF = "CMS_PROPERTYDEF"; /** * Table-key for max-id */ protected static String C_TABLE_SYSTEMPROPERTIES = "CMS_SYSTEMPROPERTIES"; public static boolean C_USE_TARGET_DATE = true; protected CmsDriverManager m_driverManager; /** * A array containing all max-ids for the tables. */ protected int[] m_maxIds; protected org.opencms.db.generic.CmsSqlManager m_sqlManager; /** Internal debugging flag.<p> */ private static final boolean C_DEBUG = true; /** * Creates a serializable object in the systempropertys. * * @param name The name of the property. * @param object The property-object. * * @return object The property-object. * * @throws CmsException Throws CmsException if something goes wrong. */ public Serializable addSystemProperty(String name, Serializable object) throws CmsException { byte[] value; Connection conn = null; PreparedStatement stmt = null; try { // serialize the object ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream oout = new ObjectOutputStream(bout); oout.writeObject(object); oout.close(); value = bout.toByteArray(); // create the object conn = m_sqlManager.getConnection(); stmt = m_sqlManager.getPreparedStatement(conn, "C_SYSTEMPROPERTIES_WRITE"); stmt.setInt(1, m_sqlManager.nextId(C_TABLE_SYSTEMPROPERTIES)); stmt.setString(2, name); m_sqlManager.setBytes(stmt, 3, value); stmt.executeUpdate(); } catch (SQLException e) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false); } catch (IOException e) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SERIALIZATION, e, false); } finally { // close all db-resources m_sqlManager.closeAll(conn, stmt, null); } return readSystemProperty(name); } /** * Private helper method for publihing into the filesystem. * test if resource must be written to the filesystem.<p> * * @param filename Name of a resource in the OpenCms system * @param exportpoints the exportpoints * @return key in exportpoints or null */ protected String checkExport(String filename, Hashtable exportpoints) { String key = null; String exportpoint = null; Enumeration e = exportpoints.keys(); while (e.hasMoreElements()) { exportpoint = (String) e.nextElement(); if (filename.startsWith(exportpoint)) { return exportpoint; } } return key; } /** * creates a link entry for each of the link targets in the linktable.<p> * * @param pageId The resourceId (offline) of the page whose liks should be traced * @param linkTargets A vector of strings (the linkdestinations) * @throws CmsException if something goes wrong */ public void createLinkEntrys(CmsUUID pageId, Vector linkTargets) throws CmsException { //first delete old entrys in the database deleteLinkEntrys(pageId); if (linkTargets == null || linkTargets.size() == 0) { return; } // now write it Connection conn = null; PreparedStatement stmt = null; try { // TODO all the link management methods should be carefully turned into project dependent code! int dummyProjectId = Integer.MAX_VALUE; conn = m_sqlManager.getConnection(dummyProjectId); stmt = m_sqlManager.getPreparedStatement(conn, dummyProjectId, "C_LM_WRITE_ENTRY"); stmt.setString(1, pageId.toString()); for (int i = 0; i < linkTargets.size(); i++) { try { stmt.setString(2, (String) linkTargets.elementAt(i)); stmt.executeUpdate(); } catch (SQLException e) { } } } catch (SQLException e) { throw m_sqlManager.getCmsException(this, "createLinkEntrys(CmsUUID, Vector)", CmsException.C_SQL_ERROR, e, false); } finally { m_sqlManager.closeAll(conn, stmt, null); } } /** * creates a link entry for each of the link targets in the online linktable.<p> * * @param pageId The resourceId (online) of the page whose liks should be traced * @param linkTargets A vector of strings (the linkdestinations) * @throws CmsException if something goes wrong */ public void createOnlineLinkEntrys(CmsUUID pageId, Vector linkTargets) throws CmsException { //first delete old entrys in the database deleteLinkEntrys(pageId); if (linkTargets == null || linkTargets.size() == 0) { return; } // now write it Connection conn = null; PreparedStatement stmt = null; try { // TODO all the link management methods should be carefully turned into project dependent code! int dummyProjectId = I_CmsConstants.C_PROJECT_ONLINE_ID; conn = m_sqlManager.getConnection(dummyProjectId); stmt = m_sqlManager.getPreparedStatement(conn, dummyProjectId, "C_LM_WRITE_ENTRY"); stmt.setString(1, pageId.toString()); for (int i = 0; i < linkTargets.size(); i++) { try { stmt.setString(2, (String) linkTargets.elementAt(i)); stmt.executeUpdate(); } catch (SQLException e) { } } } catch (SQLException e) { throw m_sqlManager.getCmsException(this, "createOnlineLinkEntrys(CmsUUID, Vector)", CmsException.C_SQL_ERROR, e, false); } finally { m_sqlManager.closeAll(conn, stmt, null); } } /** * Creates a project.<p> * TODO: name x timestamp must be unique - since timestamp typically has a resulution * of one second, creation of several tasks with the same name may fail. * * @param owner The owner of this project * @param group The group for this project * @param managergroup The managergroup for this project * @param task The task * @param name The name of the project to create * @param description The description for the new project * @param flags The flags for the project (e.g. archive) * @param type the type for the project (e.g. normal) * @return the new CmsProject instance * @throws CmsException Throws CmsException if something goes wrong */ public CmsProject createProject(CmsUser owner, CmsGroup group, CmsGroup managergroup, CmsTask task, String name, String description, int flags, int type) throws CmsException { if ((description == null) || (description.length() < 1)) { description = " "; } Timestamp createTime = new Timestamp(new java.util.Date().getTime()); Connection conn = null; PreparedStatement stmt = null; int id = m_sqlManager.nextId(C_TABLE_PROJECTS); try { conn = m_sqlManager.getConnection(); stmt = m_sqlManager.getPreparedStatement(conn, "C_PROJECTS_CREATE"); // write data to database stmt.setInt(1, id); stmt.setString(2, owner.getId().toString()); stmt.setString(3, group.getId().toString()); stmt.setString(4, managergroup.getId().toString()); stmt.setInt(5, task.getId()); stmt.setString(6, name); stmt.setString(7, description); stmt.setInt(8, flags); stmt.setTimestamp(9, createTime); // no publish data stmt.setInt(10, type); stmt.executeUpdate(); } catch (SQLException e) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false); } finally { m_sqlManager.closeAll(conn, stmt, null); } return readProject(id); } /** * This method creates a new session in the database. It is used * for sessionfailover.<p> * * @param sessionId the id of the session * @param data the session data * @throws CmsException if something goes wrong */ public void createSession(String sessionId, Hashtable data) throws CmsException { byte[] value = null; Connection conn = null; PreparedStatement stmt = null; try { value = serializeSession(data); conn = m_sqlManager.getConnection(); stmt = m_sqlManager.getPreparedStatement(conn, "C_SESSION_CREATE"); // write data to database stmt.setString(1, sessionId); stmt.setTimestamp(2, new java.sql.Timestamp(System.currentTimeMillis())); m_sqlManager.setBytes(stmt, 3, value); stmt.executeUpdate(); } catch (SQLException e) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false); } catch (IOException e) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SERIALIZATION, e, false); } finally { m_sqlManager.closeAll(conn, stmt, null); } } /** * Deletes all projectResource from an given CmsProject.<p> * * @param projectId The project in which the resource is used * @throws CmsException Throws CmsException if operation was not succesful */ public void deleteAllProjectResources(int projectId) throws CmsException { Connection conn = null; PreparedStatement stmt = null; try { conn = m_sqlManager.getConnection(); stmt = m_sqlManager.getPreparedStatement(conn, "C_PROJECTRESOURCES_DELETEALL"); // delete all projectResources from the database stmt.setInt(1, projectId); stmt.executeUpdate(); } catch (SQLException e) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false); } finally { m_sqlManager.closeAll(conn, stmt, null); } } /** * Deletes all entrys in the link table that belong to the pageId.<p> * * @param pageId The resourceId (offline) of the page whose links should be deleted * @throws CmsException if something goes wrong */ public void deleteLinkEntrys(CmsUUID pageId) throws CmsException { Connection conn = null; PreparedStatement stmt = null; try { // TODO all the link management methods should be carefully turned into project dependent code! int dummyProjectId = Integer.MAX_VALUE; conn = m_sqlManager.getConnection(dummyProjectId); stmt = m_sqlManager.getPreparedStatement(conn, dummyProjectId, "C_LM_DELETE_ENTRYS"); stmt.setString(1, pageId.toString()); stmt.executeUpdate(); } catch (SQLException e) { throw m_sqlManager.getCmsException(this, "deleteLinkEntrys(CmsUUID)", CmsException.C_SQL_ERROR, e, false); } finally { m_sqlManager.closeAll(conn, stmt, null); } } /** * Deletes all entrys in the online link table that belong to the pageId.<p> * * @param pageId The resourceId (online) of the page whose links should be deleted * @throws CmsException if something goes wrong */ public void deleteOnlineLinkEntrys(CmsUUID pageId) throws CmsException { Connection conn = null; PreparedStatement stmt = null; try { // TODO all the link management methods should be carefully turned into project dependent code! int dummyProjectId = I_CmsConstants.C_PROJECT_ONLINE_ID; conn = m_sqlManager.getConnection(dummyProjectId); stmt = m_sqlManager.getPreparedStatement(conn, dummyProjectId, "C_LM_DELETE_ENTRYS"); // delete all project-resources. stmt.setString(1, pageId.toString()); stmt.executeUpdate(); } catch (SQLException e) { throw m_sqlManager.getCmsException(this, "deleteOnlineLinkEntrys(CmsUUID)", CmsException.C_SQL_ERROR, e, false); } finally { m_sqlManager.closeAll(conn, stmt, null); } } /** * Deletes a project from the cms. * Therefore it deletes all files, resources and properties. * * @param project the project to delete. * @throws CmsException Throws CmsException if something goes wrong. */ public void deleteProject(CmsProject project) throws CmsException { // delete the resources from project_resources deleteAllProjectResources(project.getId()); // finally delete the project Connection conn = null; PreparedStatement stmt = null; try { conn = m_sqlManager.getConnection(); stmt = m_sqlManager.getPreparedStatement(conn, "C_PROJECTS_DELETE"); // create the statement stmt.setInt(1, project.getId()); stmt.executeUpdate(); } catch (Exception exc) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, exc, false); } finally { m_sqlManager.closeAll(conn, stmt, null); } } /** * Deletes all properties for a project. * * @param project The project to delete. * * @throws CmsException Throws CmsException if operation was not succesful */ public void deleteProjectProperties(CmsProject project) throws CmsException { // delete properties with one statement Connection conn = null; PreparedStatement stmt = null; try { conn = m_sqlManager.getConnection(); stmt = m_sqlManager.getPreparedStatement(conn, "C_PROPERTIES_DELETEALLPROP"); // create statement stmt.setInt(1, project.getId()); stmt.executeQuery(); } catch (SQLException exc) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, exc, false); } finally { m_sqlManager.closeAll(conn, stmt, null); } } /** * delete a projectResource from an given CmsResource object.<p> * * @param projectId id of the project in which the resource is used * @param resourceName name of the resource to be deleted from the Cms * @throws CmsException if something goes wrong */ public void deleteProjectResource(int projectId, String resourceName) throws CmsException { Connection conn = null; PreparedStatement stmt = null; try { conn = m_sqlManager.getConnection(); stmt = m_sqlManager.getPreparedStatement(conn, "C_PROJECTRESOURCES_DELETE"); // delete resource from the database stmt.setInt(1, projectId); stmt.setString(2, resourceName); stmt.executeUpdate(); } catch (SQLException e) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false); } finally { m_sqlManager.closeAll(conn, stmt, null); } } /** * Deletes a specified project * * @param project The project to be deleted. * @throws CmsException Throws CmsException if operation was not succesful. */ public void deleteProjectResources(CmsProject project) throws CmsException { Connection conn = null; PreparedStatement stmt = null; try { conn = m_sqlManager.getConnection(); // stmt = m_sqlManager.getPreparedStatement(conn, "C_RESOURCES_DELETE_PROJECT"); // delete all project-resources. // stmt.setInt(1, project.getId()); // stmt.executeQuery(); stmt = m_sqlManager.getPreparedStatement(conn, project, "C_RESOURCES_DELETE_BY_PROJECTID"); stmt.setInt(1, project.getId()); stmt.executeUpdate(); m_sqlManager.closeAll(null, stmt, null); stmt = m_sqlManager.getPreparedStatement(conn, project, "C_STRUCTURE_DELETE_BY_PROJECTID"); stmt.setInt(1, project.getId()); stmt.executeUpdate(); } catch (SQLException e) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false); } finally { m_sqlManager.closeAll(conn, stmt, null); } } /** * Deletes old sessions. */ public void deleteSessions() { Connection conn = null; PreparedStatement stmt = null; try { conn = m_sqlManager.getConnection(); stmt = m_sqlManager.getPreparedStatement(conn, "C_SESSION_DELETE"); stmt.setTimestamp(1, new java.sql.Timestamp(System.currentTimeMillis() - C_SESSION_TIMEOUT)); stmt.execute(); } catch (Exception e) { if (OpenCms.isLogging(I_CmsLogChannels.C_OPENCMS_INFO)) { OpenCms.log(I_CmsLogChannels.C_OPENCMS_INFO, "[" + this.getClass().getName() + "] error while deleting old sessions: " + com.opencms.util.Utils.getStackTrace(e)); } } finally { m_sqlManager.closeAll(conn, stmt, null); } } /** * Deletes a serializable object from the systempropertys. * * @param name The name of the property. * * @throws CmsException Throws CmsException if something goes wrong. */ public void deleteSystemProperty(String name) throws CmsException { Connection conn = null; PreparedStatement stmt = null; try { conn = m_sqlManager.getConnection(); stmt = m_sqlManager.getPreparedStatement(conn, "C_SYSTEMPROPERTIES_DELETE"); stmt.setString(1, name); stmt.executeUpdate(); } catch (SQLException e) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false); } finally { m_sqlManager.closeAll(conn, stmt, null); } } /** * @see org.opencms.db.I_CmsProjectDriver#destroy() */ public void destroy() throws Throwable { finalize(); if (OpenCms.isLogging(I_CmsLogChannels.C_OPENCMS_INIT)) { OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[" + this.getClass().getName() + "] destroyed!"); } } /** * Ends a task from the Cms.<p> * * @param taskId Id of the task to end * @throws CmsException if something goes wrong */ public void endTask(int taskId) throws CmsException { Connection conn = null; PreparedStatement stmt = null; try { conn = m_sqlManager.getConnection(); stmt = m_sqlManager.getPreparedStatement(conn, "C_TASK_END"); stmt.setInt(1, 100); stmt.setTimestamp(2, new java.sql.Timestamp(System.currentTimeMillis())); stmt.setInt(3, taskId); stmt.executeUpdate(); } catch (SQLException exc) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, exc, false); } finally { m_sqlManager.closeAll(conn, stmt, null); } } /** * Method to init all default-resources.<p> * * @throws CmsException if something goes wrong */ public void fillDefaults() throws CmsException { try { if (readProject(I_CmsConstants.C_PROJECT_ONLINE_ID) != null) { // online-project exists - no need of filling defaults return; } } catch (CmsException exc) { // ignore the exception - the project was not readable so fill in the defaults } if (OpenCms.isLogging(I_CmsLogChannels.C_OPENCMS_INIT)) { OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, ". Database init : filling default values"); } // set the groups CmsGroup guests = m_driverManager.getUserDriver().createGroup(CmsUUID.getConstantUUID(OpenCms.getDefaultUsers().getGroupGuests()), OpenCms.getDefaultUsers().getGroupGuests(), "The guest group", I_CmsConstants.C_FLAG_ENABLED, null); CmsGroup administrators = m_driverManager.getUserDriver().createGroup(CmsUUID.getConstantUUID(OpenCms.getDefaultUsers().getGroupAdministrators()), OpenCms.getDefaultUsers().getGroupAdministrators(), "The administrators group", I_CmsConstants.C_FLAG_ENABLED | I_CmsConstants.C_FLAG_GROUP_PROJECTMANAGER, null); CmsGroup users = m_driverManager.getUserDriver().createGroup(CmsUUID.getConstantUUID(OpenCms.getDefaultUsers().getGroupUsers()), OpenCms.getDefaultUsers().getGroupUsers(), "The users group", I_CmsConstants.C_FLAG_ENABLED | I_CmsConstants.C_FLAG_GROUP_ROLE | I_CmsConstants.C_FLAG_GROUP_PROJECTCOWORKER, null); CmsGroup projectmanager = m_driverManager.getUserDriver().createGroup(CmsUUID.getConstantUUID(OpenCms.getDefaultUsers().getGroupProjectmanagers()), OpenCms.getDefaultUsers().getGroupProjectmanagers(), "The projectmanager group", I_CmsConstants.C_FLAG_ENABLED | I_CmsConstants.C_FLAG_GROUP_PROJECTMANAGER | I_CmsConstants.C_FLAG_GROUP_PROJECTCOWORKER | I_CmsConstants.C_FLAG_GROUP_ROLE, users.getName()); // add the users CmsUser guest = m_driverManager.getUserDriver().addImportUser(CmsUUID.getConstantUUID(OpenCms.getDefaultUsers().getUserGuest()), OpenCms.getDefaultUsers().getUserGuest(), m_driverManager.getUserDriver().digest(""), m_driverManager.getUserDriver().digest(""), "The guest user", " ", " ", " ", 0, 0, I_CmsConstants.C_FLAG_ENABLED, new Hashtable(), guests, " ", " ", I_CmsConstants.C_USER_TYPE_SYSTEMUSER); CmsUser admin = m_driverManager.getUserDriver().addImportUser(CmsUUID.getConstantUUID(OpenCms.getDefaultUsers().getUserAdmin()), OpenCms.getDefaultUsers().getUserAdmin(), m_driverManager.getUserDriver().digest("admin"), m_driverManager.getUserDriver().digest(""), "The admin user", " ", " ", " ", 0, 0, I_CmsConstants.C_FLAG_ENABLED, new Hashtable(), administrators, " ", " ", I_CmsConstants.C_USER_TYPE_SYSTEMUSER); m_driverManager.getUserDriver().addUserToGroup(guest.getId(), guests.getId()); m_driverManager.getUserDriver().addUserToGroup(admin.getId(), administrators.getId()); m_driverManager.getWorkflowDriver().writeTaskType(1, 0, "../taskforms/adhoc.asp", "Ad-Hoc", "30308", 1, 1); // online project stuff // create the online project CmsTask task = m_driverManager.getWorkflowDriver().createTask(0, 0, 1, admin.getId(), admin.getId(), administrators.getId(), I_CmsConstants.C_PROJECT_ONLINE, new java.sql.Timestamp(new java.util.Date().getTime()), new java.sql.Timestamp(new java.util.Date().getTime()), I_CmsConstants.C_TASK_PRIORITY_NORMAL); CmsProject online = createProject(admin, users /* guests */, projectmanager, task, I_CmsConstants.C_PROJECT_ONLINE, "the online-project", I_CmsConstants.C_FLAG_ENABLED, I_CmsConstants.C_PROJECT_TYPE_NORMAL); // create the root-folder for the online project CmsFolder onlineRootFolder = m_driverManager.getVfsDriver().createFolder(online, CmsUUID.getNullUUID(), CmsUUID.getNullUUID(), "/", 0, 0, admin.getId(), 0, admin.getId()); onlineRootFolder.setState(I_CmsConstants.C_STATE_UNCHANGED); m_driverManager.getVfsDriver().writeFolder(online, onlineRootFolder, CmsDriverManager.C_UPDATE_ALL, onlineRootFolder.getUserLastModified()); // setup project stuff // create the task for the setup project task = m_driverManager.getWorkflowDriver().createTask(0, 0, 1, admin.getId(), admin.getId(), administrators.getId(), "_setupProject", new java.sql.Timestamp(new java.util.Date().getTime()), new java.sql.Timestamp(new java.util.Date().getTime()), I_CmsConstants.C_TASK_PRIORITY_NORMAL); CmsProject setup = createProject(admin, administrators, administrators, task, "_setupProject", "Initial site import", I_CmsConstants.C_FLAG_ENABLED, I_CmsConstants.C_PROJECT_TYPE_TEMPORARY); // create the root-folder for the offline project CmsFolder setupRootFolder = m_driverManager.getVfsDriver().createFolder(setup, onlineRootFolder, CmsUUID.getNullUUID()); setupRootFolder.setState(I_CmsConstants.C_STATE_UNCHANGED); m_driverManager.getVfsDriver().writeFolder(setup, setupRootFolder, CmsDriverManager.C_UPDATE_ALL, setupRootFolder.getUserLastModified()); } /** * @see java.lang.Object#finalize() */ protected void finalize() throws Throwable { if (m_sqlManager!=null) { m_sqlManager.finalize(); } m_sqlManager = null; m_driverManager = null; } /** * Forwards a task to another user. * * @param taskId The id of the task that will be fowarded. * @param newRoleId The new Group the task belongs to * @param newUserId User who gets the task. * * @throws CmsException Throws CmsException if something goes wrong. */ public void forwardTask(int taskId, CmsUUID newRoleId, CmsUUID newUserId) throws CmsException { Connection conn = null; PreparedStatement stmt = null; try { conn = m_sqlManager.getConnection(); stmt = m_sqlManager.getPreparedStatement(conn, "C_TASK_FORWARD"); stmt.setString(1, newRoleId.toString()); stmt.setString(2, newUserId.toString()); stmt.setInt(3, taskId); stmt.executeUpdate(); } catch (SQLException exc) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, exc, false); } finally { m_sqlManager.closeAll(conn, stmt, null); } } /** * Returns all projects, which are accessible by a group.<p> * * @param group the requesting group * @return a Vector of projects * @throws CmsException if something goes wrong */ public Vector getAllAccessibleProjectsByGroup(CmsGroup group) throws CmsException { Vector projects = new Vector(); ResultSet res = null; Connection conn = null; PreparedStatement stmt = null; try { // create the statement conn = m_sqlManager.getConnection(); stmt = m_sqlManager.getPreparedStatement(conn, "C_PROJECTS_READ_BYGROUP"); stmt.setString(1, group.getId().toString()); stmt.setString(2, group.getId().toString()); res = stmt.executeQuery(); while (res.next()) { projects.addElement(new CmsProject(res, m_sqlManager)); } } catch (Exception exc) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, exc, false); } finally { m_sqlManager.closeAll(conn, stmt, res); } return (projects); } /** * Returns all projects, which are manageable by a group.<p> * * @param group The requesting group * @return a Vector of projects * @throws CmsException if something goes wrong */ public Vector getAllAccessibleProjectsByManagerGroup(CmsGroup group) throws CmsException { Vector projects = new Vector(); ResultSet res = null; PreparedStatement stmt = null; Connection conn = null; try { // create the statement conn = m_sqlManager.getConnection(); stmt = m_sqlManager.getPreparedStatement(conn, "C_PROJECTS_READ_BYMANAGER"); stmt.setString(1, group.getId().toString()); res = stmt.executeQuery(); while (res.next()) { projects.addElement(new CmsProject(res, m_sqlManager)); } } catch (Exception exc) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, exc, false); } finally { m_sqlManager.closeAll(conn, stmt, res); } return (projects); } /** * Returns all projects, which are owned by a user.<p> * * @param user The requesting user * @return a Vector of projects * @throws CmsException if something goes wrong */ public Vector getAllAccessibleProjectsByUser(CmsUser user) throws CmsException { Vector projects = new Vector(); ResultSet res = null; PreparedStatement stmt = null; Connection conn = null; try { // create the statement conn = m_sqlManager.getConnection(); stmt = m_sqlManager.getPreparedStatement(conn, "C_PROJECTS_READ_BYUSER"); stmt.setString(1, user.getId().toString()); res = stmt.executeQuery(); while (res.next()) { projects.addElement(new CmsProject(res, m_sqlManager)); } } catch (Exception exc) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, exc, false); } finally { m_sqlManager.closeAll(conn, stmt, res); } return (projects); } /** * Reads all export links.<p> * * @return a Vector(of Strings) with the links * @throws CmsException if something goes wrong */ public Vector getAllExportLinks() throws CmsException { Vector retValue = new Vector(); PreparedStatement stmt = null; ResultSet res = null; Connection conn = null; try { conn = m_sqlManager.getConnection(); stmt = m_sqlManager.getPreparedStatement(conn, "C_EXPORT_GET_ALL_LINKS"); res = stmt.executeQuery(); while (res.next()) { retValue.add(res.getString(m_sqlManager.get("C_EXPORT_LINK"))); } return retValue; } catch (SQLException e) { throw m_sqlManager.getCmsException(this, "getAllExportLinks()", CmsException.C_SQL_ERROR, e, false); } catch (Exception e) { throw m_sqlManager.getCmsException(this, "getAllExportLinks()", CmsException.C_UNKNOWN_EXCEPTION, e, false); } finally { // close all db-resources m_sqlManager.closeAll(conn, stmt, res); } } /** * Returns all projects, with the overgiven state.<p> * * @param state The state of the projects to read * @return a Vector of projects * @throws CmsException if something goes wrong */ public Vector getAllProjects(int state) throws CmsException { Vector projects = new Vector(); ResultSet res = null; PreparedStatement stmt = null; Connection conn = null; try { // create the statement conn = m_sqlManager.getConnection(); stmt = m_sqlManager.getPreparedStatement(conn, "C_PROJECTS_READ_BYFLAG"); stmt.setInt(1, state); res = stmt.executeQuery(); while (res.next()) { projects.addElement( new CmsProject( res.getInt(m_sqlManager.get("C_PROJECTS_PROJECT_ID")), res.getString(m_sqlManager.get("C_PROJECTS_PROJECT_NAME")), res.getString(m_sqlManager.get("C_PROJECTS_PROJECT_DESCRIPTION")), res.getInt(m_sqlManager.get("C_PROJECTS_TASK_ID")), new CmsUUID(res.getString(m_sqlManager.get("C_PROJECTS_USER_ID"))), new CmsUUID(res.getString(m_sqlManager.get("C_PROJECTS_GROUP_ID"))), new CmsUUID(res.getString(m_sqlManager.get("C_PROJECTS_MANAGERGROUP_ID"))), res.getInt(m_sqlManager.get("C_PROJECTS_PROJECT_FLAGS")), SqlHelper.getTimestamp(res, m_sqlManager.get("C_PROJECTS_PROJECT_CREATEDATE")), res.getInt(m_sqlManager.get("C_PROJECTS_PROJECT_TYPE")))); } } catch (SQLException exc) { throw m_sqlManager.getCmsException(this, "getAllProjects(int)", CmsException.C_SQL_ERROR, exc, false); } finally { m_sqlManager.closeAll(conn, stmt, res); } return (projects); } /** * Reads all export links that depend on the resource.<p> * * @param resources vector of resources * @return a Vector(of Strings) with the linkrequest names * @throws CmsException if something goes wrong */ public Vector getDependingExportLinks(Vector resources) throws CmsException { Vector retValue = new Vector(); PreparedStatement stmt = null; ResultSet res = null; Connection conn = null; try { Vector firstResult = new Vector(); Vector secondResult = new Vector(); conn = m_sqlManager.getConnection(); stmt = m_sqlManager.getPreparedStatement(conn, "C_EXPORT_GET_ALL_DEPENDENCIES"); res = stmt.executeQuery(); while (res.next()) { firstResult.add(res.getString(m_sqlManager.get("C_EXPORT_DEPENDENCIES_RESOURCE"))); secondResult.add(res.getString(m_sqlManager.get("C_EXPORT_LINK"))); } // now we have all dependencies that are there. We can search now for // the ones we need for (int i = 0; i < resources.size(); i++) { for (int j = 0; j < firstResult.size(); j++) { if (((String) firstResult.elementAt(j)).startsWith((String) resources.elementAt(i))) { if (!retValue.contains(secondResult.elementAt(j))) { retValue.add(secondResult.elementAt(j)); } } else if (((String) resources.elementAt(i)).startsWith((String) firstResult.elementAt(j))) { if (!retValue.contains(secondResult.elementAt(j))) { // only direct subfolders count int index = ((String) firstResult.elementAt(j)).length(); String test = ((String) resources.elementAt(i)).substring(index); index = test.indexOf("/"); if (index == -1 || index + 1 == test.length()) { retValue.add(secondResult.elementAt(j)); } } } } } return retValue; } catch (SQLException e) { throw m_sqlManager.getCmsException(this, "getDependingExportlinks(Vector)", CmsException.C_SQL_ERROR, e, false); } catch (Exception e) { throw m_sqlManager.getCmsException(this, "getDependingExportLinks(Vector)", CmsException.C_UNKNOWN_EXCEPTION, e, false); } finally { // close all db-resources m_sqlManager.closeAll(conn, stmt, res); } } /** * Searches for broken links in the online project.<p> * * @return A Vector with a CmsPageLinks object for each page containing broken links * this CmsPageLinks object contains all links on the page withouth a valid target * @throws CmsException if something goes wrong */ public Vector getOnlineBrokenLinks() throws CmsException { Vector result = new Vector(); PreparedStatement stmt = null; ResultSet res = null; Connection conn = null; try { conn = m_sqlManager.getConnection(I_CmsConstants.C_PROJECT_ONLINE_ID); stmt = m_sqlManager.getPreparedStatement(conn, "C_LM_GET_ONLINE_BROKEN_LINKS"); res = stmt.executeQuery(); CmsUUID current = CmsUUID.getNullUUID(); CmsPageLinks links = null; while (res.next()) { CmsUUID next = new CmsUUID(res.getString(m_sqlManager.get("C_LM_PAGE_ID"))); if (!next.equals(current)) { if (links != null) { result.add(links); } links = new CmsPageLinks(next); links.addLinkTarget(res.getString(m_sqlManager.get("C_LM_LINK_DEST"))); try { links.setResourceName((m_driverManager.getVfsDriver().readFileHeader(I_CmsConstants.C_PROJECT_ONLINE_ID, next, false)).getResourceName()); } catch (CmsException e) { links.setResourceName("id=" + next + ". Sorry, can't read resource. " + e.getMessage()); } links.setOnline(true); } else { links.addLinkTarget(res.getString(m_sqlManager.get("C_LM_LINK_DEST"))); } current = next; } if (links != null) { result.add(links); } return result; } catch (SQLException e) { throw m_sqlManager.getCmsException(this, "getOnlineBrokenLinks()", CmsException.C_SQL_ERROR, e, false); } catch (Exception e) { throw m_sqlManager.getCmsException(this, "getOnlineBrokenLinks()", CmsException.C_UNKNOWN_EXCEPTION, e, false); } finally { // close all db-resources m_sqlManager.closeAll(conn, stmt, null); } } /** * Retrieves the online project from the database. * * @return com.opencms.file.CmsProject the onlineproject for the given project. * @throws CmsException Throws CmsException if the resource is not found, or the database communication went wrong. */ public CmsProject getOnlineProject() throws CmsException { return readProject(I_CmsConstants.C_PROJECT_ONLINE_ID); } /** * @see org.opencms.db.I_CmsDriver#init(source.org.apache.java.util.Configurations, java.util.List, org.opencms.db.CmsDriverManager) */ public void init(Configurations config, List successiveDrivers, CmsDriverManager driverManager) { String poolUrl = config.getString("db.project.pool"); m_sqlManager = this.initQueries(); m_sqlManager.setOfflinePoolUrl(poolUrl); m_sqlManager.setOnlinePoolUrl(poolUrl); m_sqlManager.setBackupPoolUrl(poolUrl); m_driverManager = driverManager; if (OpenCms.isLogging(I_CmsLogChannels.C_OPENCMS_INIT)) { OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, ". Assigned pool : " + poolUrl); } if (successiveDrivers != null && !successiveDrivers.isEmpty()) { if (OpenCms.isLogging(I_CmsLogChannels.C_OPENCMS_INIT)) { OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, this.getClass().toString() + " does not support successive drivers."); } } } /** * @see org.opencms.db.I_CmsProjectDriver#initQueries(java.lang.String) */ public org.opencms.db.generic.CmsSqlManager initQueries() { return new org.opencms.db.generic.CmsSqlManager(); } /** * Publishes a specified project to the online project.<p> * * @param context the context * @param onlineProject the online project of the OpenCms * @param backupEnabled flag if the backup is enabled * @param backupTagId the backup tag id * @param report a report object to provide the loggin messages * @param exportpoints the exportpoints * @param directPublishResource contains CmsResource when in publish directly mode * @param maxVersions maximum number of backup versions * @return a vector of changed or deleted resources * @throws CmsException if something goes wrong */ public synchronized Vector publishProject(CmsRequestContext context, CmsProject onlineProject, boolean backupEnabled, int backupTagId, I_CmsReport report, Hashtable exportpoints, CmsResource directPublishResource, int maxVersions) throws Exception { CmsExportPointDriver discAccess = null; CmsFolder currentFolder = null; CmsFile currentFile = null; CmsResource currentFileHeader = null; CmsLock currentLock = null; List offlineFolders = null; List offlineFiles = null; List deletedFolders = (List) new ArrayList(); Vector changedResources = new Vector(); String currentExportKey = null; String currentResourceName = null; long publishDate = System.currentTimeMillis(); Iterator i = null; boolean publishCurrentResource = false; List projectResources = null; Map sortedFolderMap = null; List sortedFolderList = null; byte[] contents = null; int publishHistoryId = nextPublishVersionId(); String encoding = null; int m, n; try { discAccess = new CmsExportPointDriver(exportpoints); if (backupEnabled) { // write an entry in the publish project log m_driverManager.backupProject(context, context.currentProject(), backupTagId, publishDate); } // read the project resources of the project that gets published projectResources = m_driverManager.readProjectResources(context, context.currentProject()); // read all changed/new/deleted folders offlineFolders = m_driverManager.getVfsDriver().readFolders(context.currentProject().getId()); // ensure that the folders appear in the correct (DFS) tree order // sort out folders that will not be published sortedFolderMap = (Map) new HashMap(); i = offlineFolders.iterator(); while (i.hasNext()) { publishCurrentResource = false; currentFolder = (CmsFolder) i.next(); currentResourceName = m_driverManager.readPath(context, currentFolder, true); currentFolder.setFullResourceName(currentResourceName); currentLock = m_driverManager.getLock(context, currentResourceName); // the resource must have either a new/deleted state in the link or a new/delete state in the resource record publishCurrentResource = currentFolder.getState() > I_CmsConstants.C_STATE_UNCHANGED; if (context.currentProject().getType() == I_CmsConstants.C_PROJECT_TYPE_DIRECT_PUBLISH && directPublishResource != null) { // the resource must be a sub resource of the direct-publish-resource in case of a "direct publish" publishCurrentResource = publishCurrentResource && currentResourceName.startsWith(directPublishResource.getFullResourceName()); } else { // the resource must have a changed state and must be changed in the project that is currently published publishCurrentResource = publishCurrentResource && currentFolder.getProjectId() == context.currentProject().getId(); // the resource must be in one of the paths defined for the project publishCurrentResource = publishCurrentResource && CmsProject.isInsideProject(projectResources, currentFolder); } // the resource must be unlocked publishCurrentResource = publishCurrentResource && currentLock.isNullLock(); if (publishCurrentResource) { sortedFolderMap.put(currentResourceName, currentFolder); } } sortedFolderList = (List) new ArrayList(sortedFolderMap.keySet()); Collections.sort(sortedFolderList); offlineFolders.clear(); offlineFolders = null; m = 1; n = sortedFolderList.size(); i = sortedFolderList.iterator(); if (n > 0) { report.println(report.key("report.publish_folders_begin"), I_CmsReport.C_FORMAT_HEADLINE); } while (i.hasNext()) { currentResourceName = (String) i.next(); currentFolder = (CmsFolder) sortedFolderMap.get(currentResourceName); currentExportKey = checkExport(currentResourceName, exportpoints); if (currentFolder.getState() == I_CmsConstants.C_STATE_DELETED) { // C_STATE_DELETE deletedFolders.add(currentFolder); changedResources.addElement(currentResourceName); } else if (currentFolder.getState() == I_CmsConstants.C_STATE_NEW) { changedResources.addElement(currentResourceName); // export to filesystem if necessary if (currentExportKey != null) { discAccess.createFolder(currentResourceName, currentExportKey); } // bounce the current publish task through all project drivers m_driverManager.getProjectDriver().publishFolder(context, report, m++, n, onlineProject, currentFolder, backupEnabled, publishDate, publishHistoryId, backupTagId, maxVersions); } else if (currentFolder.getState() == I_CmsConstants.C_STATE_CHANGED) { changedResources.addElement(currentResourceName); // export to filesystem if necessary if (currentExportKey != null) { discAccess.createFolder(currentResourceName, currentExportKey); } // bounce the current publish task through all project drivers m_driverManager.getProjectDriver().publishFolder(context, report, m++, n, onlineProject, currentFolder, backupEnabled, publishDate, publishHistoryId, backupTagId, maxVersions); } i.remove(); } if (n > 0) { report.println(report.key("report.publish_folders_end"), I_CmsReport.C_FORMAT_HEADLINE); } if (sortedFolderList != null) { sortedFolderList.clear(); sortedFolderList = null; } if (sortedFolderMap != null) { sortedFolderMap.clear(); sortedFolderMap = null; } // now read all changed/new/deleted files offlineFiles = m_driverManager.getVfsDriver().readFiles(context.currentProject().getId()); // sort out files that will not be published i = offlineFiles.iterator(); while (i.hasNext()) { publishCurrentResource = false; currentFileHeader = (CmsResource) i.next(); currentResourceName = m_driverManager.readPath(context, currentFileHeader, true); currentFileHeader.setFullResourceName(currentResourceName); currentLock = m_driverManager.getLock(context, currentResourceName); switch (currentFileHeader.getState()) { // the current resource is deleted case I_CmsConstants.C_STATE_DELETED : // it is published, if it was changed to deleted in the current project String delProject = m_driverManager.getVfsDriver().readProperty(I_CmsConstants.C_PROPERTY_INTERNAL, context.currentProject().getId(), currentFileHeader, currentFileHeader.getType()); if (delProject != null && delProject.equals("" + context.currentProject().getId())) { publishCurrentResource = true; } else { publishCurrentResource = false; } break; // the current resource is new case I_CmsConstants.C_STATE_NEW : // it is published, if it was created in the current project // or if it is a new sibling of another resource that is currently not changed in any project publishCurrentResource = currentFileHeader.getProjectId() == context.currentProject().getId() || currentFileHeader.getProjectId() == 0; break; // the current resource is changed case I_CmsConstants.C_STATE_CHANGED : // it is published, if it was changed in the current project publishCurrentResource = currentFileHeader.getProjectId() == context.currentProject().getId(); break; // the current resource is unchanged case I_CmsConstants.C_STATE_UNCHANGED : default : // so it is not published publishCurrentResource = false; break; } if (context.currentProject().getType() == I_CmsConstants.C_PROJECT_TYPE_DIRECT_PUBLISH && directPublishResource != null) { // the resource must be a sub resource of the direct-publish-resource in case of a "direct publish" publishCurrentResource = publishCurrentResource && currentResourceName.startsWith(directPublishResource.getFullResourceName()); } else { // the resource must be in one of the paths defined for the project publishCurrentResource = publishCurrentResource && CmsProject.isInsideProject(projectResources, currentFileHeader); } // do not publish resource that are locked publishCurrentResource = publishCurrentResource && currentLock.isNullLock(); // handle temporary files immediately here coz they aren't "published" anyway if (currentLock.isNullLock()) { // remove any possible temporary files for this resource m_driverManager.getVfsDriver().removeTemporaryFile(currentFileHeader); } if (currentFileHeader.getResourceName().startsWith(I_CmsConstants.C_TEMP_PREFIX)) { // trash the current resource if it is a temporary file m_driverManager.getVfsDriver().deleteAllProperties(context.currentProject().getId(), currentFileHeader); m_driverManager.getVfsDriver().removeFile(context.currentProject(), currentFileHeader); } if (!publishCurrentResource) { i.remove(); } } m = 1; n = offlineFiles.size(); i = offlineFiles.iterator(); if (n > 0) { report.println(report.key("report.publish_files_begin"), I_CmsReport.C_FORMAT_HEADLINE); } while (i.hasNext()) { currentFileHeader = (CmsResource) i.next(); currentResourceName = currentFileHeader.getFullResourceName(); currentExportKey = checkExport(currentResourceName, exportpoints); currentFile = m_driverManager.getVfsDriver().readFile(context.currentProject().getId(), true, currentFileHeader.getId()); currentFile.setFullResourceName(currentResourceName); if (currentFileHeader.getState() == I_CmsConstants.C_STATE_DELETED) { changedResources.addElement(currentResourceName); if (currentExportKey != null) { // delete the export point try { discAccess.removeResource(currentResourceName, currentExportKey); } catch (CmsException e) { if (OpenCms.isLogging(I_CmsLogChannels.C_OPENCMS_CRITICAL)) { OpenCms.log(I_CmsLogChannels.C_OPENCMS_CRITICAL, "[" + this.getClass().getName() + ".publishProject()] error deleting export point, type: " + e.getType() + ", " + currentFile.toString()); } } catch (Exception e) { if (OpenCms.isLogging(I_CmsLogChannels.C_OPENCMS_CRITICAL)) { OpenCms.log(I_CmsLogChannels.C_OPENCMS_CRITICAL, "[" + this.getClass().getName() + ".publishProject()] error deleting export point " + currentFile.toString()); } } } // bounce the current publish task through all project drivers m_driverManager.getProjectDriver().publishFile(context, report, m++, n, onlineProject, currentFileHeader, backupEnabled, publishDate, publishHistoryId, backupTagId, maxVersions); } else if (currentFileHeader.getState() == I_CmsConstants.C_STATE_CHANGED) { changedResources.addElement(currentResourceName); if (currentExportKey != null) { // write the export point try { // make sure files are written in the right encoding contents = currentFile.getContents(); encoding = m_driverManager.getVfsDriver().readProperty(I_CmsConstants.C_PROPERTY_CONTENT_ENCODING, context.currentProject().getId(), currentFile, currentFile.getType()); if (encoding != null) { // only files that have the encodig property set will be encoded, // other files will be ignored. images etc. are not touched. try { contents = (new String(contents, encoding)).getBytes(); } catch (UnsupportedEncodingException uex) { // noop } } discAccess.writeFile(currentResourceName, currentExportKey, contents); } catch (CmsException e) { if (OpenCms.isLogging(I_CmsLogChannels.C_OPENCMS_CRITICAL)) { OpenCms.log(I_CmsLogChannels.C_OPENCMS_CRITICAL, "[" + this.getClass().getName() + ".publishProject()] error writing export point, type: " + e.getType() + ", " + currentFile.toString()); } } catch (Exception e) { if (OpenCms.isLogging(I_CmsLogChannels.C_OPENCMS_CRITICAL)) { OpenCms.log(I_CmsLogChannels.C_OPENCMS_CRITICAL, "[" + this.getClass().getName() + ".publishProject()] error writing export point " + currentFile.toString()); } } } // bounce the current publish task through all project drivers m_driverManager.getProjectDriver().publishFile(context, report, m++, n, onlineProject, currentFileHeader, backupEnabled, publishDate, publishHistoryId, backupTagId, maxVersions); } else if (currentFileHeader.getState() == I_CmsConstants.C_STATE_NEW) { changedResources.addElement(currentResourceName); // export to filesystem if necessary if (currentExportKey != null) { // Encoding project: Make sure files are written in the right encoding contents = currentFile.getContents(); encoding = m_driverManager.getVfsDriver().readProperty(I_CmsConstants.C_PROPERTY_CONTENT_ENCODING, context.currentProject().getId(), currentFile, currentFile.getType()); if (encoding != null) { // Only files that have the encodig property set will be encoded, // the other files will be ignored. So images etc. are not touched. try { contents = (new String(contents, encoding)).getBytes(); } catch (UnsupportedEncodingException uex) { // contents will keep original value } } discAccess.writeFile(currentResourceName, currentExportKey, contents); } // bounce the current publish task through all project drivers m_driverManager.getProjectDriver().publishFile(context, report, m++, n, onlineProject, currentFileHeader, backupEnabled, publishDate, publishHistoryId, backupTagId, maxVersions); } i.remove(); } if (n > 0) { report.println(report.key("report.publish_files_end"), I_CmsReport.C_FORMAT_HEADLINE); } if (offlineFiles != null) { offlineFiles.clear(); offlineFiles = null; } // now delete the "deleted" folders if (deletedFolders.isEmpty()) { return changedResources; } // ensure that the folders appear in the correct (DFS) tree order sortedFolderMap = (Map) new HashMap(); i = deletedFolders.iterator(); while (i.hasNext()) { currentFolder = (CmsFolder) i.next(); currentResourceName = currentFolder.getFullResourceName(); sortedFolderMap.put(currentResourceName, currentFolder); } sortedFolderList = (List) new ArrayList(sortedFolderMap.keySet()); Collections.sort(sortedFolderList); // reverse the order of the folder to delete them in a bottom-up order Collections.reverse(sortedFolderList); if (deletedFolders != null) { deletedFolders.clear(); deletedFolders = null; } m = 1; n = sortedFolderList.size(); i = sortedFolderList.iterator(); if (n > 0) { report.println(report.key("report.publish_delete_folders_begin"), I_CmsReport.C_FORMAT_HEADLINE); } while (i.hasNext()) { currentResourceName = (String) i.next(); currentFolder = (CmsFolder) sortedFolderMap.get(currentResourceName); currentExportKey = checkExport(currentResourceName, exportpoints); if (currentExportKey != null) { discAccess.removeResource(currentResourceName, currentExportKey); } // bounce the current publish task through all project drivers m_driverManager.getProjectDriver().publishDeletedFolder(context, report, m++, n, onlineProject, currentFolder, backupEnabled, publishDate, publishHistoryId, backupTagId, maxVersions); i.remove(); } if (n > 0) { report.println(report.key("report.publish_delete_folders_end"), I_CmsReport.C_FORMAT_HEADLINE); } if (sortedFolderList != null) { sortedFolderList.clear(); sortedFolderList = null; } if (sortedFolderMap != null) { sortedFolderMap.clear(); sortedFolderMap = null; } } catch (Exception e) { // these are dummy catch blocks to have a finally block for clearing // allocated resources. thus the exceptions are just logged and // immediately thrown to the upper app. layer. if (C_DEBUG) { System.err.println(e.getMessage()); e.printStackTrace(System.err); } throw e; } catch (OutOfMemoryError o) { if (OpenCms.isLogging(I_CmsLogChannels.C_OPENCMS_CRITICAL)) { OpenCms.log(I_CmsLogChannels.C_OPENCMS_CRITICAL, "[" + this.getClass().getName() + ".publishProject] out of memory error!"); } // clear all caches to reclaim memory OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_CLEAR_CACHES, new HashMap(), false)); // force a complete object finalization and garbage collection System.runFinalization(); Runtime.getRuntime().runFinalization(); System.gc(); Runtime.getRuntime().gc(); throw o; } finally { if (sortedFolderList != null) { sortedFolderList.clear(); sortedFolderList = null; } if (sortedFolderMap != null) { sortedFolderMap.clear(); sortedFolderMap = null; } if (deletedFolders != null) { deletedFolders.clear(); deletedFolders = null; } if (offlineFiles != null) { offlineFiles.clear(); offlineFiles = null; } currentFile = null; currentFileHeader = null; currentFolder = null; discAccess = null; currentExportKey = null; contents = null; } return changedResources; } /** * Select all projectResources from an given project.<p> * * @param projectId the project in which the resource is used * @return Vector of resources belongig to the project * @throws CmsException if something goes wrong */ public Vector readAllProjectResources(int projectId) throws CmsException { Connection conn = null; PreparedStatement stmt = null; ResultSet res = null; Vector projectResources = new Vector(); try { conn = m_sqlManager.getConnection(); stmt = m_sqlManager.getPreparedStatement(conn, "C_PROJECTRESOURCES_READALL"); // select all resources from the database stmt.setInt(1, projectId); res = stmt.executeQuery(); while (res.next()) { projectResources.addElement(res.getString("RESOURCE_NAME")); } res.close(); } catch (SQLException e) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false); } finally { m_sqlManager.closeAll(conn, stmt, null); } return projectResources; } /** * Returns a Vector (Strings) with the link destinations of all links on the page with * the pageId.<p> * * @param pageId The resourceId (offline) of the page whose liks should be read * @return the vector of link destinations * @throws CmsException if something goes wrong */ public Vector readLinkEntrys(CmsUUID pageId) throws CmsException { Vector result = new Vector(); PreparedStatement stmt = null; ResultSet res = null; Connection conn = null; try { // TODO all the link management methods should be carefully turned into project dependent code! int dummyProjectId = Integer.MAX_VALUE; conn = m_sqlManager.getConnection(dummyProjectId); stmt = m_sqlManager.getPreparedStatement(conn, dummyProjectId, "C_LM_READ_ENTRYS"); stmt.setString(1, pageId.toString()); res = stmt.executeQuery(); while (res.next()) { result.add(res.getString(m_sqlManager.get("C_LM_LINK_DEST"))); } return result; } catch (SQLException e) { throw m_sqlManager.getCmsException(this, "readLinkEntrys(CmsUUID)", CmsException.C_SQL_ERROR, e, false); } catch (Exception e) { throw m_sqlManager.getCmsException(this, "readLinkEntrys(CmsUUID)", CmsException.C_UNKNOWN_EXCEPTION, e, false); } finally { // close all db-resources m_sqlManager.closeAll(conn, stmt, res); } } /** * Reads the online id of a offline file.<p> * * @param filename name of the file * @return the id or -1 if not found (should not happen) * @throws CmsException if something goes wrong */ private CmsUUID readOnlineId(String filename) throws CmsException { ResultSet res = null; PreparedStatement stmt = null; Connection conn = null; CmsUUID resourceId = CmsUUID.getNullUUID(); try { conn = m_sqlManager.getConnection(I_CmsConstants.C_PROJECT_ONLINE_ID); stmt = m_sqlManager.getPreparedStatement(conn, "C_LM_READ_ONLINE_ID"); // read file data from database stmt.setString(1, filename); res = stmt.executeQuery(); // read the id if (res.next()) { resourceId = new CmsUUID(res.getString(m_sqlManager.get("C_RESOURCES_STRUCTURE_ID"))); while (res.next()) { // do nothing only move through all rows because of mssql odbc driver } } } catch (SQLException e) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false); } catch (Exception exc) { throw m_sqlManager.getCmsException(this, null, CmsException.C_UNKNOWN_EXCEPTION, exc, false); } finally { m_sqlManager.closeAll(conn, stmt, res); } return resourceId; } /** * Returns a Vector (Strings) with the link destinations of all links on the page with * the pageId.<p> * * @param pageId The resourceId (online) of the page whose liks should be read * @return the vector of link destinations * @throws CmsException if something goes wrong */ public Vector readOnlineLinkEntrys(CmsUUID pageId) throws CmsException { Vector result = new Vector(); PreparedStatement stmt = null; ResultSet res = null; Connection conn = null; try { // TODO all the link management methods should be carefully turned into project dependent code! int dummyProjectId = I_CmsConstants.C_PROJECT_ONLINE_ID; conn = m_sqlManager.getConnection(dummyProjectId); stmt = m_sqlManager.getPreparedStatement(conn, dummyProjectId, "C_LM_READ_ENTRYS"); stmt.setString(1, pageId.toString()); res = stmt.executeQuery(); while (res.next()) { result.add(res.getString(m_sqlManager.get("C_LM_LINK_DEST"))); } return result; } catch (SQLException e) { throw m_sqlManager.getCmsException(this, "readOnlineLinkEntrys(CmsUUID)", CmsException.C_SQL_ERROR, e, false); } catch (Exception e) { throw m_sqlManager.getCmsException(this, "readOnlineLinkEntrys(CmsUUID)", CmsException.C_UNKNOWN_EXCEPTION, e, false); } finally { // close all db-resources m_sqlManager.closeAll(conn, stmt, res); } } /** * Reads a project by task-id.<p> * * @param task the task to read the project for * @return the project the tasks belongs to * @throws CmsException if something goes wrong */ public CmsProject readProject(CmsTask task) throws CmsException { PreparedStatement stmt = null; CmsProject project = null; ResultSet res = null; Connection conn = null; try { conn = m_sqlManager.getConnection(); stmt = m_sqlManager.getPreparedStatement(conn, "C_PROJECTS_READ_BYTASK"); stmt.setInt(1, task.getId()); res = stmt.executeQuery(); if (res.next()) project = new CmsProject(res, m_sqlManager); else // project not found! throw new CmsException("[" + this.getClass().getName() + "] " + task, CmsException.C_NOT_FOUND); } catch (SQLException e) { throw m_sqlManager.getCmsException(this, "readProject(CmsTask)", CmsException.C_SQL_ERROR, e, false); } finally { // close all db-resources m_sqlManager.closeAll(conn, stmt, res); } return project; } /** * Reads a project.<p> * * @param id the id of the project * @return the project with the given id * @throws CmsException if something goes wrong */ public CmsProject readProject(int id) throws CmsException { PreparedStatement stmt = null; CmsProject project = null; ResultSet res = null; Connection conn = null; try { conn = m_sqlManager.getConnection(); stmt = m_sqlManager.getPreparedStatement(conn, "C_PROJECTS_READ"); stmt.setInt(1, id); res = stmt.executeQuery(); if (res.next()) { project = new CmsProject( res.getInt(m_sqlManager.get("C_PROJECTS_PROJECT_ID")), res.getString(m_sqlManager.get("C_PROJECTS_PROJECT_NAME")), res.getString(m_sqlManager.get("C_PROJECTS_PROJECT_DESCRIPTION")), res.getInt(m_sqlManager.get("C_PROJECTS_TASK_ID")), new CmsUUID(res.getString(m_sqlManager.get("C_PROJECTS_USER_ID"))), new CmsUUID(res.getString(m_sqlManager.get("C_PROJECTS_GROUP_ID"))), new CmsUUID(res.getString(m_sqlManager.get("C_PROJECTS_MANAGERGROUP_ID"))), res.getInt(m_sqlManager.get("C_PROJECTS_PROJECT_FLAGS")), SqlHelper.getTimestamp(res, m_sqlManager.get("C_PROJECTS_PROJECT_CREATEDATE")), res.getInt(m_sqlManager.get("C_PROJECTS_PROJECT_TYPE"))); } else { // project not found! throw m_sqlManager.getCmsException(this, "project with ID " + id + " not found", CmsException.C_NOT_FOUND, null, true); } } catch (SQLException e) { throw m_sqlManager.getCmsException(this, "readProject(int)/1 ", CmsException.C_SQL_ERROR, e, false); } finally { m_sqlManager.closeAll(conn, stmt, res); } return project; } /** * Reads log entries for a project.<p> * * @param projectid the project for tasklog to read * @return a vector of new TaskLog objects * @throws CmsException if something goes wrong */ public Vector readProjectLogs(int projectid) throws CmsException { ResultSet res = null; Connection conn = null; CmsTaskLog tasklog = null; Vector logs = new Vector(); PreparedStatement stmt = null; String comment = null; java.sql.Timestamp starttime = null; int id = I_CmsConstants.C_UNKNOWN_ID; CmsUUID user = CmsUUID.getNullUUID(); int type = I_CmsConstants.C_UNKNOWN_ID; try { conn = m_sqlManager.getConnection(); stmt = m_sqlManager.getPreparedStatement(conn, "C_TASKLOG_READ_PPROJECTLOGS"); stmt.setInt(1, projectid); res = stmt.executeQuery(); while (res.next()) { comment = res.getString(m_sqlManager.get("C_LOG_COMMENT")); id = res.getInt(m_sqlManager.get("C_LOG_ID")); starttime = SqlHelper.getTimestamp(res, m_sqlManager.get("C_LOG_STARTTIME")); user = new CmsUUID(res.getString(m_sqlManager.get("C_LOG_USER"))); type = res.getInt(m_sqlManager.get("C_LOG_TYPE")); tasklog = new CmsTaskLog(id, comment, user, starttime, type); logs.addElement(tasklog); } } catch (SQLException exc) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, exc, false); } catch (Exception exc) { throw m_sqlManager.getCmsException(this, null, CmsException.C_UNKNOWN_EXCEPTION, exc, false); } finally { // close all db-resources m_sqlManager.closeAll(conn, stmt, res); } return logs; } /** * Reads all resource from the Cms, that are in one project.<BR/> * A resource is either a file header or a folder. * * @param project The id of the project in which the resource will be used. * @param filter The filter for the resources to be read * @return A Vecor of resources. * @throws CmsException Throws CmsException if operation was not succesful */ public List readProjectView(int project, String filter) throws CmsException { List resources = (List) new ArrayList(); CmsResource currentResource = null; ResultSet res = null; PreparedStatement stmt = null; Connection conn = null; String orderClause = " ORDER BY CMS_T_STRUCTURE.STRUCTURE_ID"; String whereClause = new String(); // TODO: dangerous - move this somehow into query.properties if ("new".equalsIgnoreCase(filter)) { whereClause = " AND (CMS_T_STRUCTURE.STRUCTURE_STATE=" + I_CmsConstants.C_STATE_NEW + " OR CMS_T_RESOURCES.RESOURCE_STATE=" + I_CmsConstants.C_STATE_NEW + ")"; } else if ("changed".equalsIgnoreCase(filter)) { whereClause = " AND (CMS_T_STRUCTURE.STRUCTURE_STATE=" + I_CmsConstants.C_STATE_CHANGED + " OR CMS_T_RESOURCES.RESOURCE_STATE=" + I_CmsConstants.C_STATE_CHANGED + ")"; } else if ("deleted".equalsIgnoreCase(filter)) { whereClause = " AND (CMS_T_STRUCTURE.STRUCTURE_STATE=" + I_CmsConstants.C_STATE_DELETED + " OR CMS_T_RESOURCES.RESOURCE_STATE=" + I_CmsConstants.C_STATE_DELETED + ")"; } else if ("locked".equalsIgnoreCase(filter)) { whereClause = ""; } else { whereClause = " AND (CMS_T_STRUCTURE.STRUCTURE_STATE!=" + I_CmsConstants.C_STATE_UNCHANGED + " OR CMS_T_RESOURCES.RESOURCE_STATE!=" + I_CmsConstants.C_STATE_UNCHANGED + ")"; } try { // TODO make the getConnection and getPreparedStatement calls project-ID dependent conn = m_sqlManager.getConnection(); String query = m_sqlManager.get("C_RESOURCES_PROJECTVIEW") + whereClause + orderClause; stmt = m_sqlManager.getPreparedStatementForSql(conn, CmsSqlManager.replaceTableKey(I_CmsConstants.C_PROJECT_ONLINE_ID+1,query)); stmt.setInt(1, project); res = stmt.executeQuery(); while (res.next()) { currentResource = m_driverManager.getVfsDriver().createCmsResourceFromResultSet(res, project); resources.add(currentResource); } } catch (SQLException e) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false); } catch (Exception ex) { throw m_sqlManager.getCmsException(this, null, CmsException.C_UNKNOWN_EXCEPTION, ex, false); } finally { m_sqlManager.closeAll(conn, stmt, res); } return resources; } /** * Reads a session from the database.<p> * * @param sessionId the id og the session to read * @return the session data as Hashtable * @throws CmsException if something goes wrong */ public Hashtable readSession(String sessionId) throws CmsException { PreparedStatement stmt = null; ResultSet res = null; Hashtable sessionData = new Hashtable(); Hashtable data = null; Connection conn = null; try { conn = m_sqlManager.getConnection(); stmt = m_sqlManager.getPreparedStatement(conn, "C_SESSION_READ"); stmt.setString(1, sessionId); stmt.setTimestamp(2, new java.sql.Timestamp(System.currentTimeMillis() - C_SESSION_TIMEOUT)); res = stmt.executeQuery(); // create new Cms user object if (res.next()) { // read the additional infos. byte[] value = m_sqlManager.getBytes(res, "SESSION_DATA"); // now deserialize the object ByteArrayInputStream bin = new ByteArrayInputStream(value); ObjectInputStream oin = new ObjectInputStream(bin); data = (Hashtable) oin.readObject(); try { for (;;) { Object key = oin.readObject(); Object sessionValue = oin.readObject(); sessionData.put(key, sessionValue); } } catch (EOFException exc) { // reached eof - stop reading all is done now. } data.put(I_CmsConstants.C_SESSION_DATA, sessionData); } else { deleteSessions(); } } catch (SQLException e) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false); } catch (Exception e) { throw m_sqlManager.getCmsException(this, null, CmsException.C_UNKNOWN_EXCEPTION, e, false); } finally { // close all db-resources m_sqlManager.closeAll(conn, stmt, res); } return data; } /** * Reads a serializable object from the systempropertys. * * @param name The name of the property. * @return object The property-object. * @throws CmsException Throws CmsException if something goes wrong. */ public Serializable readSystemProperty(String name) throws CmsException { Serializable property = null; byte[] value; ResultSet res = null; PreparedStatement stmt = null; Connection conn = null; // create get the property data from the database try { conn = m_sqlManager.getConnection(); stmt = m_sqlManager.getPreparedStatement(conn, "C_SYSTEMPROPERTIES_READ"); stmt.setString(1, name); res = stmt.executeQuery(); if (res.next()) { value = m_sqlManager.getBytes(res, m_sqlManager.get("C_SYSTEMPROPERTY_VALUE")); // now deserialize the object ByteArrayInputStream bin = new ByteArrayInputStream(value); ObjectInputStream oin = new ObjectInputStream(bin); property = (Serializable) oin.readObject(); } } catch (SQLException e) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false); } catch (IOException e) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SERIALIZATION, e, false); } catch (ClassNotFoundException e) { throw m_sqlManager.getCmsException(this, null, CmsException.C_CLASSLOADER_ERROR, e, false); } finally { m_sqlManager.closeAll(conn, stmt, res); } return property; } /** * Helper method to serialize the hashtable.<p> * This method is used by updateSession() and createSession(). * @param data the data to be serialized * @return byte array of serialized data * @throws IOException if something goes wrong */ private byte[] serializeSession(Hashtable data) throws IOException { // serialize the hashtable byte[] value; Hashtable sessionData = (Hashtable) data.remove(I_CmsConstants.C_SESSION_DATA); StringBuffer notSerializable = new StringBuffer(); ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream oout = new ObjectOutputStream(bout); // first write the user data oout.writeObject(data); if (sessionData != null) { Enumeration keys = sessionData.keys(); while (keys.hasMoreElements()) { Object key = keys.nextElement(); Object sessionValue = sessionData.get(key); if (sessionValue instanceof Serializable) { // this value is serializeable -> write it to the outputstream oout.writeObject(key); oout.writeObject(sessionValue); } else { // this object is not serializeable -> remark for warning notSerializable.append(key); notSerializable.append("; "); } } } oout.close(); value = bout.toByteArray(); if (OpenCms.isLogging(I_CmsLogChannels.C_OPENCMS_INFO) && (notSerializable.length() > 0)) { OpenCms.log(I_CmsLogChannels.C_OPENCMS_INFO, "[" + this.getClass().getName() + "] warning, following entrys are not serializeable in the session: " + notSerializable.toString() + "."); } return value; } /** * Sorts a vector of files or folders alphabetically. * This method uses an insertion sort algorithm. * NOT IN USE AT THIS TIME * * @param list array of strings containing the list of files or folders * @return Vector of sorted strings */ protected Vector SortEntrys(Vector list) { int in, out; int nElem = list.size(); CmsResource[] unsortedList = new CmsResource[list.size()]; for (int i = 0; i < list.size(); i++) { unsortedList[i] = (CmsResource) list.elementAt(i); } for (out = 1; out < nElem; out++) { CmsResource temp = unsortedList[out]; in = out; while (in > 0 && unsortedList[in - 1].getResourceName().compareTo(temp.getResourceName()) >= 0) { unsortedList[in] = unsortedList[in - 1]; --in; } unsortedList[in] = temp; } Vector sortedList = new Vector(); for (int i = 0; i < list.size(); i++) { sortedList.addElement(unsortedList[i]); } return sortedList; } /** * Unlocks all resources in this project. * * @param project The project to be unlocked. * * @throws CmsException Throws CmsException if something goes wrong. */ public void unlockProject(CmsProject project) throws CmsException { PreparedStatement stmt = null; Connection conn = null; try { conn = m_sqlManager.getConnection(project); stmt = m_sqlManager.getPreparedStatement(conn, project, "C_RESOURCES_UNLOCK"); stmt.setString(1, CmsUUID.getNullUUID().toString()); stmt.setInt(2, project.getId()); stmt.executeUpdate(); } catch (Exception exc) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, exc, false); } finally { // close all db-resources m_sqlManager.closeAll(conn, stmt, null); } } /** * Update the online link table (after a project is published).<p> * * @param deleted vector (of CmsResources) with the deleted resources of the project * @param changed vector (of CmsResources) with the changed resources of the project * @param newRes vector (of CmsResources) with the newRes resources of the project * @param pageType the page type * @throws CmsException if something goes wrong */ public void updateOnlineProjectLinks(Vector deleted, Vector changed, Vector newRes, int pageType) throws CmsException { if (deleted != null) { for (int i = 0; i < deleted.size(); i++) { // delete the old values in the online table if (((CmsResource) deleted.elementAt(i)).getType() == pageType) { CmsUUID id = readOnlineId(((CmsResource) deleted.elementAt(i)).getResourceName()); if (!id.isNullUUID()) { deleteOnlineLinkEntrys(id); } } } } if (changed != null) { for (int i = 0; i < changed.size(); i++) { // delete the old values and copy the new values from the project link table if (((CmsResource) changed.elementAt(i)).getType() == pageType) { CmsUUID id = readOnlineId(((CmsResource) changed.elementAt(i)).getResourceName()); if (!id.isNullUUID()) { deleteOnlineLinkEntrys(id); createOnlineLinkEntrys(id, readLinkEntrys(((CmsResource) changed.elementAt(i)).getResourceId())); } } } } if (newRes != null) { for (int i = 0; i < newRes.size(); i++) { // copy the values from the project link table if (((CmsResource) newRes.elementAt(i)).getType() == pageType) { CmsUUID id = readOnlineId(((CmsResource) newRes.elementAt(i)).getResourceName()); if (!id.isNullUUID()) { createOnlineLinkEntrys(id, readLinkEntrys(((CmsResource) newRes.elementAt(i)).getResourceId())); } } } } } /** * This method updates a session in the database. It is used * for sessionfailover.<p> * * @param sessionId the id of the session * @param data the session data * @return the amount of data written to the database * @throws CmsException if something goes wrong */ public int updateSession(String sessionId, Hashtable data) throws CmsException { byte[] value = null; PreparedStatement stmt = null; Connection conn = null; int retValue; try { value = serializeSession(data); conn = m_sqlManager.getConnection(); stmt = m_sqlManager.getPreparedStatement(conn, "C_SESSION_UPDATE"); // write data to database stmt.setTimestamp(1, new java.sql.Timestamp(System.currentTimeMillis())); m_sqlManager.setBytes(stmt, 2, value); stmt.setString(3, sessionId); retValue = stmt.executeUpdate(); } catch (SQLException e) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false); } catch (IOException e) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SERIALIZATION, e, false); } finally { m_sqlManager.closeAll(conn, stmt, null); } return retValue; } /** * Deletes a project from the cms. * Therefore it deletes all files, resources and properties. * * @param project the project to delete. * @throws CmsException Throws CmsException if something goes wrong. */ public void writeProject(CmsProject project) throws CmsException { PreparedStatement stmt = null; Connection conn = null; try { conn = m_sqlManager.getConnection(); stmt = m_sqlManager.getPreparedStatement(conn, "C_PROJECTS_WRITE"); stmt.setString(1, project.getOwnerId().toString()); stmt.setString(2, project.getGroupId().toString()); stmt.setString(3, project.getManagerGroupId().toString()); stmt.setInt(4, project.getFlags()); // no publishing data stmt.setInt(7, project.getId()); stmt.executeUpdate(); } catch (Exception exc) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, exc, false); } finally { // close all db-resources m_sqlManager.closeAll(conn, stmt, null); } } /** * Writes a serializable object to the systemproperties. * * @param name The name of the property. * @param object The property-object. * * @return object The property-object. * * @throws CmsException Throws CmsException if something goes wrong. */ public Serializable writeSystemProperty(String name, Serializable object) throws CmsException { byte[] value = null; PreparedStatement stmt = null; Connection conn = null; try { // serialize the object ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream oout = new ObjectOutputStream(bout); oout.writeObject(object); oout.close(); value = bout.toByteArray(); conn = m_sqlManager.getConnection(); stmt = m_sqlManager.getPreparedStatement(conn, "C_SYSTEMPROPERTIES_UPDATE"); m_sqlManager.setBytes(stmt, 1, value); stmt.setString(2, name); stmt.executeUpdate(); } catch (SQLException e) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false); } catch (IOException e) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SERIALIZATION, e, false); } finally { m_sqlManager.closeAll(conn, stmt, null); } return readSystemProperty(name); } /** * @see org.opencms.db.I_CmsProjectDriver#writePublishHistory(com.opencms.file.CmsProject, int, int, java.lang.String, com.opencms.file.CmsResource) */ public void writePublishHistory(CmsProject currentProject, int publishId, int tagId, String resourcename, CmsResource resource) throws CmsException { Connection conn = null; PreparedStatement stmt = null; try { conn = m_sqlManager.getConnectionForBackup(); stmt = m_sqlManager.getPreparedStatement(conn, "C_RESOURCES_WRITE_PUBLISH_HISTORY"); stmt.setInt(1, tagId); stmt.setString(2, resource.getId().toString()); stmt.setString(3, resource.getResourceId().toString()); stmt.setString(4, resource.getFileId().toString()); stmt.setString(5, resourcename); stmt.setInt(6, resource.getState()); stmt.setInt(7, resource.getType()); stmt.setInt(8, publishId); stmt.executeUpdate(); } catch (SQLException e) { throw m_sqlManager.getCmsException(this, null, CmsException.C_SQL_ERROR, e, false); } finally { m_sqlManager.closeAll(conn, stmt, null); } } /** * @see org.opencms.db.I_CmsProjectDriver#nextPublishVersionId() */ public int nextPublishVersionId() throws CmsException { PreparedStatement stmt = null; Connection conn = null; ResultSet res = null; int versionId = 1; try { conn = m_sqlManager.getConnectionForBackup(); stmt = m_sqlManager.getPreparedStatement(conn, "C_RESOURCES_PUBLISH_MAXVER"); res = stmt.executeQuery(); if (res.next()) { versionId = res.getInt(1) + 1; } } catch (SQLException exc) { return 1; } finally { m_sqlManager.closeAll(conn, stmt, res); } return versionId; } /** * @see org.opencms.db.I_CmsProjectDriver#publishFolder(com.opencms.file.CmsRequestContext, org.opencms.report.I_CmsReport, int, int, com.opencms.file.CmsProject, com.opencms.file.CmsFolder, boolean, long, int, int, int) */ public void publishFolder(CmsRequestContext context, I_CmsReport report, int m, int n, CmsProject onlineProject, CmsFolder offlineFolder, boolean backupEnabled, long publishDate, int publishHistoryId, int backupTagId, int maxVersions) throws Exception { CmsFolder newFolder = null; CmsFolder onlineFolder = null; Map offlineProperties = null; try { report.print("( " + m + " / " + n + " ) " + report.key("report.publishing.folder"), I_CmsReport.C_FORMAT_NOTE); report.println(context.removeSiteRoot(offlineFolder.getFullResourceName())); if (offlineFolder.getState() == I_CmsConstants.C_STATE_NEW) { try { // create the folder online newFolder = (CmsFolder) offlineFolder.clone(); newFolder.setState(I_CmsConstants.C_STATE_UNCHANGED); newFolder.setFullResourceName(offlineFolder.getFullResourceName()); m_driverManager.getVfsDriver().createFolder(onlineProject, newFolder, newFolder.getParentId()); } catch (CmsException e) { if (e.getType() == CmsException.C_FILE_EXISTS) { try { onlineFolder = m_driverManager.getVfsDriver().readFolder(onlineProject.getId(), newFolder.getId()); onlineFolder.setFullResourceName(offlineFolder.getFullResourceName()); m_driverManager.getVfsDriver().updateResource(onlineFolder, offlineFolder); } catch (CmsException e1) { if (OpenCms.isLogging(I_CmsLogChannels.C_OPENCMS_CRITICAL)) { OpenCms.log(I_CmsLogChannels.C_OPENCMS_CRITICAL, "[" + this.getClass().getName() + ".publishFolder] error reading resource, type: " + e.getTypeText() + ", " + offlineFolder.toString()); } throw e1; } } else if (OpenCms.isLogging(I_CmsLogChannels.C_OPENCMS_CRITICAL)) { OpenCms.log(I_CmsLogChannels.C_OPENCMS_CRITICAL, "[" + this.getClass().getName() + ".publishFolder] error creating resource, type: " + e.getTypeText() + ", " + offlineFolder.toString()); } throw e; } try { // write the ACL online m_driverManager.getUserDriver().publishAccessControlEntries(context.currentProject(), onlineProject, offlineFolder.getResourceAceId(), newFolder.getResourceAceId()); } catch (CmsException e) { if (OpenCms.isLogging(I_CmsLogChannels.C_OPENCMS_CRITICAL)) { OpenCms.log(I_CmsLogChannels.C_OPENCMS_CRITICAL, "[" + this.getClass().getName() + ".publishFolder] error writing ACLs, type: " + e.getTypeText() + ", " + offlineFolder.toString()); } throw e; } try { // write the properties online offlineProperties = m_driverManager.getVfsDriver().readProperties(context.currentProject().getId(), offlineFolder, offlineFolder.getType()); m_driverManager.getVfsDriver().writeProperties(offlineProperties, onlineProject.getId(), newFolder, newFolder.getType(), false); } catch (CmsException e) { if (OpenCms.isLogging(I_CmsLogChannels.C_OPENCMS_CRITICAL)) { OpenCms.log(I_CmsLogChannels.C_OPENCMS_CRITICAL, "[" + this.getClass().getName() + ".publishFolder] error writing properties, type: " + e.getTypeText() + ", " + offlineFolder.toString()); } throw e; } } else if (offlineFolder.getState() == I_CmsConstants.C_STATE_CHANGED) { try { // read the folder online onlineFolder = m_driverManager.getVfsDriver().readFolder(onlineProject.getId(), offlineFolder.getId()); onlineFolder.setFullResourceName(offlineFolder.getFullResourceName()); } catch (CmsException e) { if (e.getType() == CmsException.C_NOT_FOUND) { try { onlineFolder = m_driverManager.getVfsDriver().createFolder(onlineProject, offlineFolder, offlineFolder.getParentId()); onlineFolder.setState(I_CmsConstants.C_STATE_UNCHANGED); onlineFolder.setFullResourceName(offlineFolder.getFullResourceName()); m_driverManager.getVfsDriver().updateResourceState(context.currentProject(), onlineFolder, CmsDriverManager.C_UPDATE_ALL); } catch (CmsException e1) { if (OpenCms.isLogging(I_CmsLogChannels.C_OPENCMS_CRITICAL)) { OpenCms.log(I_CmsLogChannels.C_OPENCMS_CRITICAL, "[" + this.getClass().getName() + ".publishFolder] error creating resource, type: " + e.getTypeText() + ", " + offlineFolder.toString()); } throw e1; } } else if (OpenCms.isLogging(I_CmsLogChannels.C_OPENCMS_CRITICAL)) { OpenCms.log(I_CmsLogChannels.C_OPENCMS_CRITICAL, "[" + this.getClass().getName() + ".publishFolder] error reading resource, type: " + e.getTypeText() + ", " + offlineFolder.toString()); } throw e; } try { // update the folder online m_driverManager.getVfsDriver().updateResource(onlineFolder, offlineFolder); } catch (CmsException e) { if (OpenCms.isLogging(I_CmsLogChannels.C_OPENCMS_CRITICAL)) { OpenCms.log(I_CmsLogChannels.C_OPENCMS_CRITICAL, "[" + this.getClass().getName() + ".publishFolder] error updating resource, type: " + e.getTypeText() + ", " + offlineFolder.toString()); } throw e; } try { // write the ACL online m_driverManager.getUserDriver().publishAccessControlEntries(context.currentProject(), onlineProject, offlineFolder.getResourceAceId(), onlineFolder.getResourceAceId()); } catch (CmsException e) { if (OpenCms.isLogging(I_CmsLogChannels.C_OPENCMS_CRITICAL)) { OpenCms.log(I_CmsLogChannels.C_OPENCMS_CRITICAL, "[" + this.getClass().getName() + ".publishFolder] error writing ACLs, type: " + e.getTypeText() + ", " + offlineFolder.toString()); } throw e; } try { // write the properties online m_driverManager.getVfsDriver().deleteAllProperties(onlineProject.getId(), onlineFolder); offlineProperties = m_driverManager.getVfsDriver().readProperties(context.currentProject().getId(), offlineFolder, offlineFolder.getType()); m_driverManager.getVfsDriver().writeProperties(offlineProperties, onlineProject.getId(), onlineFolder, offlineFolder.getType(), false); } catch (CmsException e) { if (OpenCms.isLogging(I_CmsLogChannels.C_OPENCMS_CRITICAL)) { OpenCms.log(I_CmsLogChannels.C_OPENCMS_CRITICAL, "[" + this.getClass().getName() + ".publishFolder] error writing properties, type: " + e.getTypeText() + ", " + offlineFolder.toString()); } throw e; } } try { // write the folder to the backup and publishing history if (backupEnabled) { m_driverManager.getBackupDriver().writeBackupResource(context.currentUser(), context.currentProject(), offlineFolder, offlineProperties, backupTagId, publishDate, maxVersions); } writePublishHistory(context.currentProject(), publishHistoryId, backupTagId, offlineFolder.getFullResourceName(), offlineFolder); } catch (CmsException e) { if (OpenCms.isLogging(I_CmsLogChannels.C_OPENCMS_CRITICAL)) { OpenCms.log(I_CmsLogChannels.C_OPENCMS_CRITICAL, "[" + this.getClass().getName() + ".publishFolder] error writing backup/publishing history, type: " + e.getTypeText() + ", " + offlineFolder.toString()); } throw e; } try { // reset the resource state and the last-modified-in-project ID offline if (offlineFolder.getState() != I_CmsConstants.C_STATE_UNCHANGED) { offlineFolder.setState(I_CmsConstants.C_STATE_UNCHANGED); m_driverManager.getVfsDriver().updateResourceState(context.currentProject(), offlineFolder, CmsDriverManager.C_UPDATE_ALL); } m_driverManager.getVfsDriver().resetProjectId(context.currentProject(), offlineFolder); } catch (CmsException e) { if (OpenCms.isLogging(I_CmsLogChannels.C_OPENCMS_CRITICAL)) { OpenCms.log(I_CmsLogChannels.C_OPENCMS_CRITICAL, "[" + this.getClass().getName() + ".publishFolder] error reseting resource state, type: " + e.getTypeText() + ", " + offlineFolder.toString()); } throw e; } } catch (Exception e) { // this is a dummy try-catch block to have a finally clause here if (C_DEBUG) { System.err.println(e.getMessage()); e.printStackTrace(System.err); } throw e; } finally { // notify the app. that the published folder and it's properties have been modified offline OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_PROPERTIES_MODIFIED, Collections.singletonMap("resource", offlineFolder))); } } /** * @see org.opencms.db.I_CmsProjectDriver#publishDeletedFolder(com.opencms.file.CmsRequestContext, org.opencms.report.I_CmsReport, int, int, com.opencms.file.CmsProject, com.opencms.file.CmsFolder, boolean, long, int, int, int) */ public void publishDeletedFolder(CmsRequestContext context, I_CmsReport report, int m, int n, CmsProject onlineProject, CmsFolder currentFolder, boolean backupEnabled, long publishDate, int publishHistoryId, int backupTagId, int maxVersions) throws Exception { CmsFolder onlineFolder = null; Map offlineProperties = null; try { report.print("( " + m + " / " + n + " ) " + report.key("report.deleting.folder"), I_CmsReport.C_FORMAT_NOTE); report.println(context.removeSiteRoot(currentFolder.getFullResourceName())); try { // write the folder to the backup and publishing history if (backupEnabled) { offlineProperties = m_driverManager.getVfsDriver().readProperties(context.currentProject().getId(), currentFolder, currentFolder.getType()); m_driverManager.getBackupDriver().writeBackupResource(context.currentUser(), context.currentProject(), currentFolder, offlineProperties, backupTagId, publishDate, maxVersions); } writePublishHistory(context.currentProject(), publishHistoryId, backupTagId, currentFolder.getFullResourceName(), currentFolder); } catch (CmsException e) { if (OpenCms.isLogging(I_CmsLogChannels.C_OPENCMS_CRITICAL)) { OpenCms.log(I_CmsLogChannels.C_OPENCMS_CRITICAL, "[" + this.getClass().getName() + ".publishDeletedFolder] error writing backup/publishing history, type: " + e.getTypeText() + ", " + currentFolder.toString()); } throw e; } try { // read the folder online onlineFolder = m_driverManager.readFolder(context, currentFolder.getId(), true); onlineFolder.setFullResourceName(currentFolder.getFullResourceName()); } catch (CmsException e) { if (OpenCms.isLogging(I_CmsLogChannels.C_OPENCMS_CRITICAL)) { OpenCms.log(I_CmsLogChannels.C_OPENCMS_CRITICAL, "[" + this.getClass().getName() + ".publishDeletedFolder] error reading resource, type: " + e.getTypeText() + ", " + currentFolder.toString()); } throw e; } try { // delete the properties online and offline m_driverManager.getVfsDriver().deleteAllProperties(onlineProject.getId(), onlineFolder); m_driverManager.getVfsDriver().deleteAllProperties(context.currentProject().getId(), currentFolder); } catch (CmsException e) { if (OpenCms.isLogging(I_CmsLogChannels.C_OPENCMS_CRITICAL)) { OpenCms.log(I_CmsLogChannels.C_OPENCMS_CRITICAL, "[" + this.getClass().getName() + ".publishDeletedFolder] error deleting properties, type: " + e.getTypeText() + ", " + currentFolder.toString()); } throw e; } try { // remove the folder online and offline m_driverManager.getVfsDriver().removeFolder(onlineProject, currentFolder); m_driverManager.getVfsDriver().removeFolder(context.currentProject(), currentFolder); } catch (CmsException e) { if (OpenCms.isLogging(I_CmsLogChannels.C_OPENCMS_CRITICAL)) { OpenCms.log(I_CmsLogChannels.C_OPENCMS_CRITICAL, "[" + this.getClass().getName() + ".publishDeletedFolder] error removing resource, type: " + e.getTypeText() + ", " + currentFolder.toString()); } throw e; } try { // remove the ACL online and offline m_driverManager.getUserDriver().removeAllAccessControlEntries(onlineProject, onlineFolder.getResourceAceId()); m_driverManager.getUserDriver().removeAllAccessControlEntries(context.currentProject(), currentFolder.getResourceAceId()); } catch (CmsException e) { if (OpenCms.isLogging(I_CmsLogChannels.C_OPENCMS_CRITICAL)) { OpenCms.log(I_CmsLogChannels.C_OPENCMS_CRITICAL, "[" + this.getClass().getName() + ".publishDeletedFolder] error removing ACLs, type: " + e.getTypeText() + ", " + currentFolder.toString()); } throw e; } } catch (Exception e) { // this is a dummy try-catch block to have a finally clause here if (C_DEBUG) { System.err.println(e.getMessage()); e.printStackTrace(System.err); } throw e; } finally { // notify the app. that the published folder and it's properties have been modified offline OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_PROPERTIES_MODIFIED, Collections.singletonMap("resource", currentFolder))); } } /** * @see org.opencms.db.I_CmsProjectDriver#publishFile(com.opencms.file.CmsRequestContext, org.opencms.report.I_CmsReport, int, int, com.opencms.file.CmsProject, com.opencms.file.CmsResource, boolean, long, int, int, int) */ public void publishFile(CmsRequestContext context, I_CmsReport report, int m, int n, CmsProject onlineProject, CmsResource offlineFileHeader, boolean backupEnabled, long publishDate, int publishHistoryId, int backupTagId, int maxVersions) throws Exception { CmsFile onlineFile = null; CmsFile offlineFile = null; CmsFile newFile = null; Map offlineProperties = null; // TODO the file(-content) should be read only once while it is published /* * Never use offlineFile.getState() here! * Only use offlineFileHeader.getState() to determine the state of a resource! * * In case a resource has siblings, after a sibling was published the structure * and resource states are reset to UNCHANGED -> the state of the corresponding * offlineFileHeader is still NEW, DELETED or CHANGED, but the state of offlineFile * is UNCHANGED because offlineFile is read AFTER siblings already got published. * Thus, using offlineFile.getState() will inevitably result in unpublished resources! */ try { offlineFile = m_driverManager.getVfsDriver().readFile(context.currentProject().getId(), true, offlineFileHeader.getId()); offlineFile.setFullResourceName(offlineFileHeader.getFullResourceName()); if (offlineFileHeader.getState() == I_CmsConstants.C_STATE_DELETED) { report.print("( " + m + " / " + n + " ) " + report.key("report.deleting.file"), I_CmsReport.C_FORMAT_NOTE); report.println(context.removeSiteRoot(offlineFileHeader.getFullResourceName())); try { // read the file online onlineFile = m_driverManager.getVfsDriver().readFile(onlineProject.getId(), true, offlineFile.getId()); onlineFile.setFullResourceName(offlineFileHeader.getFullResourceName()); } catch (CmsException e) { if (OpenCms.isLogging(I_CmsLogChannels.C_OPENCMS_CRITICAL)) { OpenCms.log(I_CmsLogChannels.C_OPENCMS_CRITICAL, "[" + this.getClass().getName() + ".publishFile] error reading resource, type: " + e.getTypeText() + ", " + offlineFile.toString()); } throw e; } if (offlineFile.isLabeled() && !m_driverManager.hasLabeledLinks(context, context.currentProject(), offlineFile)) { // update the resource flags to "unlabel" of the siblings of the offline resource int flags = offlineFile.getFlags(); flags &= ~I_CmsConstants.C_RESOURCEFLAG_LABELLINK; offlineFile.setFlags(flags); } if (onlineFile.isLabeled() && !m_driverManager.hasLabeledLinks(context, onlineProject, onlineFile)) { // update the resource flags to "unlabel" of the siblings of the online resource int flags = onlineFile.getFlags(); flags &= ~I_CmsConstants.C_RESOURCEFLAG_LABELLINK; onlineFile.setFlags(flags); } try { // delete the properties online and offline m_driverManager.getVfsDriver().deleteAllProperties(onlineProject.getId(), onlineFile); m_driverManager.getVfsDriver().deleteAllProperties(context.currentProject().getId(), offlineFile); // if the offline file has a resource ID different from the online file // (probably because a (deleted) file was replaced by a new file with the // same name), the properties with the "old" resource ID have to be // deleted also offline if (!onlineFile.getResourceId().equals(offlineFile.getResourceId())) { m_driverManager.getVfsDriver().deleteAllProperties(context.currentProject().getId(), onlineFile); } } catch (CmsException e) { if (OpenCms.isLogging(I_CmsLogChannels.C_OPENCMS_CRITICAL)) { OpenCms.log(I_CmsLogChannels.C_OPENCMS_CRITICAL, "[" + this.getClass().getName() + ".publishFile] error deleting properties, type: " + e.getTypeText() + ", " + offlineFile.toString()); } throw e; } try { // remove the file online and offline m_driverManager.getVfsDriver().removeFile(onlineProject, onlineFile); m_driverManager.getVfsDriver().removeFile(context.currentProject(), offlineFile); } catch (CmsException e) { if (OpenCms.isLogging(I_CmsLogChannels.C_OPENCMS_CRITICAL)) { OpenCms.log(I_CmsLogChannels.C_OPENCMS_CRITICAL, "[" + this.getClass().getName() + ".publishFile] error removing resource, type: " + e.getTypeText() + ", " + offlineFile.toString()); } throw e; } try { // delete the ACL online and offline m_driverManager.getUserDriver().removeAllAccessControlEntries(onlineProject, onlineFile.getResourceAceId()); m_driverManager.getUserDriver().removeAllAccessControlEntries(context.currentProject(), offlineFile.getResourceAceId()); } catch (CmsException e) { if (OpenCms.isLogging(I_CmsLogChannels.C_OPENCMS_CRITICAL)) { OpenCms.log(I_CmsLogChannels.C_OPENCMS_CRITICAL, "[" + this.getClass().getName() + ".publishFile] error removing ACLs, type: " + e.getTypeText() + ", " + offlineFile.toString()); } throw e; } try { // write the file to the backup and publishing history if (backupEnabled) { offlineProperties = m_driverManager.getVfsDriver().readProperties(context.currentProject().getId(), offlineFile, offlineFile.getType()); m_driverManager.getBackupDriver().writeBackupResource(context.currentUser(), context.currentProject(), offlineFile, offlineProperties, backupTagId, publishDate, maxVersions); } writePublishHistory(context.currentProject(), publishHistoryId, backupTagId, offlineFileHeader.getFullResourceName(), offlineFile); } catch (CmsException e) { if (OpenCms.isLogging(I_CmsLogChannels.C_OPENCMS_CRITICAL)) { OpenCms.log(I_CmsLogChannels.C_OPENCMS_CRITICAL, "[" + this.getClass().getName() + ".publishFile] error writing backup/publishing history, type: " + e.getTypeText() + ", " + offlineFile.toString()); } throw e; } } else if (offlineFileHeader.getState() == I_CmsConstants.C_STATE_CHANGED) { report.print("( " + m + " / " + n + " ) " + report.key("report.publishing.file"), I_CmsReport.C_FORMAT_NOTE); report.println(context.removeSiteRoot(offlineFileHeader.getFullResourceName())); try { // read the file online onlineFile = m_driverManager.getVfsDriver().readFile(onlineProject.getId(), true, offlineFile.getId()); onlineFile.setFullResourceName(offlineFileHeader.getFullResourceName()); // delete the properties online m_driverManager.getVfsDriver().deleteAllProperties(onlineProject.getId(), onlineFile); // if the offline file has a resource ID different from the online file // (probably because a (deleted) file was replaced by a new file with the // same name), the properties with the "old" resource ID have to be // deleted also offline if (!onlineFile.getResourceId().equals(offlineFile.getResourceId())) { m_driverManager.getVfsDriver().deleteAllProperties(context.currentProject().getId(), onlineFile); } // remove the file online m_driverManager.getVfsDriver().removeFile(onlineProject, onlineFile); } catch (CmsException e) { if (OpenCms.isLogging(I_CmsLogChannels.C_OPENCMS_CRITICAL)) { OpenCms.log(I_CmsLogChannels.C_OPENCMS_CRITICAL, "[" + this.getClass().getName() + ".publishFile] error deleting properties, type: " + e.getTypeText() + ", " + offlineFile.toString()); } throw e; } try { // create the file online newFile = (CmsFile) offlineFile.clone(); newFile.setState(I_CmsConstants.C_STATE_UNCHANGED); newFile.setFullResourceName(offlineFileHeader.getFullResourceName()); m_driverManager.getVfsDriver().createFile(onlineProject, newFile, context.currentUser().getId(), newFile.getParentId(), newFile.getResourceName()); m_driverManager.getVfsDriver().updateResource(newFile,offlineFile); } catch (CmsException e) { if (OpenCms.isLogging(I_CmsLogChannels.C_OPENCMS_CRITICAL)) { OpenCms.log(I_CmsLogChannels.C_OPENCMS_CRITICAL, "[" + this.getClass().getName() + ".publishFile] error creating resource, type: " + e.getTypeText() + ", " + newFile.toString()); } throw e; } try { // write the properties online offlineProperties = m_driverManager.getVfsDriver().readProperties(context.currentProject().getId(), offlineFile, offlineFile.getType()); m_driverManager.getVfsDriver().writeProperties(offlineProperties, onlineProject.getId(), newFile, newFile.getType(), false); } catch (CmsException e) { if (OpenCms.isLogging(I_CmsLogChannels.C_OPENCMS_CRITICAL)) { OpenCms.log(I_CmsLogChannels.C_OPENCMS_CRITICAL, "[" + this.getClass().getName() + ".publishFile] error writing properties, type: " + e.getTypeText() + ", " + newFile.toString()); } throw e; } try { // write the ACL online m_driverManager.getUserDriver().publishAccessControlEntries(context.currentProject(), onlineProject, newFile.getResourceAceId(), onlineFile.getResourceAceId()); } catch (CmsException e) { if (OpenCms.isLogging(I_CmsLogChannels.C_OPENCMS_CRITICAL)) { OpenCms.log(I_CmsLogChannels.C_OPENCMS_CRITICAL, "[" + this.getClass().getName() + ".publishFile] error writing ACLs, type: " + e.getTypeText() + ", " + offlineFile.toString()); } throw e; } try { // write the file to the backup and publishing history if (backupEnabled) { m_driverManager.getBackupDriver().writeBackupResource(context.currentUser(), context.currentProject(), offlineFile, offlineProperties, backupTagId, publishDate, maxVersions); } m_driverManager.getBackupDriver().writeBackupResource(context.currentUser(), context.currentProject(), offlineFile, offlineProperties, backupTagId, publishDate, maxVersions); } catch (CmsException e) { if (OpenCms.isLogging(I_CmsLogChannels.C_OPENCMS_CRITICAL)) { OpenCms.log(I_CmsLogChannels.C_OPENCMS_CRITICAL, "[" + this.getClass().getName() + ".publishFile] error writing backup/publishing history, type: " + e.getTypeText() + ", " + offlineFile.toString()); } throw e; } try { // reset the resource state and the last-modified-in-project ID offline if (offlineFileHeader.getState() != I_CmsConstants.C_STATE_UNCHANGED) { offlineFile.setState(I_CmsConstants.C_STATE_UNCHANGED); m_driverManager.getVfsDriver().updateResourceState(context.currentProject(), offlineFile, CmsDriverManager.C_UPDATE_ALL); } m_driverManager.getVfsDriver().resetProjectId(context.currentProject(), offlineFile); } catch (CmsException e) { if (OpenCms.isLogging(I_CmsLogChannels.C_OPENCMS_CRITICAL)) { OpenCms.log(I_CmsLogChannels.C_OPENCMS_CRITICAL, "[" + this.getClass().getName() + ".publishFile] error reseting resource state, type: " + e.getTypeText() + ", " + offlineFile.toString()); } throw e; } } else if (offlineFileHeader.getState() == I_CmsConstants.C_STATE_NEW) { report.print("( " + m + " / " + n + " ) " + report.key("report.publishing.file"), I_CmsReport.C_FORMAT_NOTE); report.println(context.removeSiteRoot(offlineFileHeader.getFullResourceName())); try { // create the file online newFile = (CmsFile) offlineFile.clone(); newFile.setState(I_CmsConstants.C_STATE_UNCHANGED); newFile.setFullResourceName(offlineFileHeader.getFullResourceName()); m_driverManager.getVfsDriver().createFile(onlineProject, newFile, context.currentUser().getId(), newFile.getParentId(), newFile.getResourceName()); } catch (CmsException e) { if (e.getType() == CmsException.C_FILE_EXISTS) { try { m_driverManager.getVfsDriver().removeFile(onlineProject, offlineFile); m_driverManager.getVfsDriver().createFile(onlineProject, newFile, context.currentUser().getId(), newFile.getParentId(), newFile.getResourceName()); } catch (CmsException e1) { if (OpenCms.isLogging(I_CmsLogChannels.C_OPENCMS_CRITICAL)) { OpenCms.log(I_CmsLogChannels.C_OPENCMS_CRITICAL, "[" + this.getClass().getName() + ".publishFile] error creating resource, type: " + e.getTypeText() + ", " + offlineFile.toString()); } throw e1; } } else if (OpenCms.isLogging(I_CmsLogChannels.C_OPENCMS_CRITICAL)) { OpenCms.log(I_CmsLogChannels.C_OPENCMS_CRITICAL, "[" + this.getClass().getName() + ".publishFile] error creating resource, type: " + e.getTypeText() + ", " + offlineFile.toString()); } throw e; } try { // write the properties online offlineProperties = m_driverManager.getVfsDriver().readProperties(context.currentProject().getId(), offlineFile, offlineFile.getType()); m_driverManager.getVfsDriver().writeProperties(offlineProperties, onlineProject.getId(), newFile, newFile.getType(), false); } catch (CmsException e) { if (OpenCms.isLogging(I_CmsLogChannels.C_OPENCMS_CRITICAL)) { OpenCms.log(I_CmsLogChannels.C_OPENCMS_CRITICAL, "[" + this.getClass().getName() + ".publishFile] error writing properties, type: " + e.getTypeText() + ", " + newFile.toString()); } throw e; } try { // write the ACL online m_driverManager.getUserDriver().publishAccessControlEntries(context.currentProject(), onlineProject, offlineFile.getResourceAceId(), newFile.getResourceAceId()); } catch (CmsException e) { if (OpenCms.isLogging(I_CmsLogChannels.C_OPENCMS_CRITICAL)) { OpenCms.log(I_CmsLogChannels.C_OPENCMS_CRITICAL, "[" + this.getClass().getName() + ".publishFile] error writing ACLs, type: " + e.getTypeText() + ", " + newFile.toString()); } throw e; } try { // write the file to the backup and publishing history if (backupEnabled) { m_driverManager.getBackupDriver().writeBackupResource(context.currentUser(), context.currentProject(), offlineFile, offlineProperties, backupTagId, publishDate, maxVersions); } writePublishHistory(context.currentProject(), publishHistoryId, backupTagId, offlineFileHeader.getFullResourceName(), offlineFile); } catch (CmsException e) { if (OpenCms.isLogging(I_CmsLogChannels.C_OPENCMS_CRITICAL)) { OpenCms.log(I_CmsLogChannels.C_OPENCMS_CRITICAL, "[" + this.getClass().getName() + ".publishFile] error writing backup/publishing history, type: " + e.getTypeText() + ", " + newFile.toString()); } throw e; } try { // reset the resource state and the last-modified-in-project ID offline if (offlineFileHeader.getState() != I_CmsConstants.C_STATE_UNCHANGED) { offlineFile.setState(I_CmsConstants.C_STATE_UNCHANGED); m_driverManager.getVfsDriver().updateResourceState(context.currentProject(), offlineFile, CmsDriverManager.C_UPDATE_ALL); } m_driverManager.getVfsDriver().resetProjectId(context.currentProject(), offlineFile); } catch (CmsException e) { if (OpenCms.isLogging(I_CmsLogChannels.C_OPENCMS_CRITICAL)) { OpenCms.log(I_CmsLogChannels.C_OPENCMS_CRITICAL, "[" + this.getClass().getName() + ".publishFile] error reseting resource state, type: " + e.getTypeText() + ", " + offlineFile.toString()); } throw e; } } } catch (Exception e) { // this is a dummy try-catch block to have a finally clause here if (C_DEBUG) { System.err.println(e.getMessage()); e.printStackTrace(System.err); } throw e; } finally { // notify the app. that the published file and it's properties have been modified offline OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_PROPERTIES_MODIFIED, Collections.singletonMap("resource", offlineFileHeader))); } } }
package org.pentaho.di.core.database; import java.io.StringReader; import java.sql.BatchUpdateException; import java.sql.Blob; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ParameterMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Savepoint; import java.sql.Statement; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Properties; import javax.sql.DataSource; import org.pentaho.di.core.Const; import org.pentaho.di.core.Counter; import org.pentaho.di.core.DBCache; import org.pentaho.di.core.DBCacheEntry; import org.pentaho.di.core.ProgressMonitorListener; import org.pentaho.di.core.Result; import org.pentaho.di.core.RowMetaAndData; import org.pentaho.di.core.database.map.DatabaseConnectionMap; import org.pentaho.di.core.database.util.DatabaseUtil; import org.pentaho.di.core.encryption.Encr; import org.pentaho.di.core.exception.KettleDatabaseBatchException; import org.pentaho.di.core.exception.KettleDatabaseException; import org.pentaho.di.core.exception.KettleValueException; import org.pentaho.di.core.logging.LogWriter; import org.pentaho.di.core.row.RowDataUtil; import org.pentaho.di.core.row.RowMeta; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.row.ValueMeta; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.core.variables.VariableSpace; import org.pentaho.di.core.variables.Variables; /** * Database handles the process of connecting to, reading from, writing to and updating databases. * The database specific parameters are defined in DatabaseInfo. * * @author Matt * @since 05-04-2003 * */ public class Database implements VariableSpace { private DatabaseMeta databaseMeta; private int rowlimit; private int commitsize; private Connection connection; private Statement sel_stmt; private PreparedStatement pstmt; private PreparedStatement prepStatementLookup; private PreparedStatement prepStatementUpdate; private PreparedStatement prepStatementInsert; private PreparedStatement pstmt_seq; private CallableStatement cstmt; // private ResultSetMetaData rsmd; private DatabaseMetaData dbmd; private RowMetaInterface rowMeta; private int written; private LogWriter log; /* * Counts the number of rows written to a batch for a certain PreparedStatement. * private Map<PreparedStatement, Integer> batchCounterMap; */ /** * Number of times a connection was opened using this object. * Only used in the context of a database connection map */ private int opened; /** * The copy is equal to opened at the time of creation. */ private int copy; private String connectionGroup; private String partitionId; private VariableSpace variables = new Variables(); /** * Construct a new Database Connection * @param inf The Database Connection Info to construct the connection with. */ public Database(DatabaseMeta inf) { log=LogWriter.getInstance(); databaseMeta = inf; shareVariablesWith(inf); pstmt = null; rowMeta = null; dbmd = null; rowlimit=0; written=0; log.logDetailed(toString(), "New database connection defined"); } public boolean equals(Object obj) { Database other = (Database) obj; return other.databaseMeta.equals(other.databaseMeta); } /** * Allows for the injection of a "life" connection, generated by a piece of software outside of Kettle. * @param connection */ public void setConnection(Connection connection) { this.connection = connection; } /** * @return Returns the connection. */ public Connection getConnection() { return connection; } /** * Set the maximum number of records to retrieve from a query. * @param rows */ public void setQueryLimit(int rows) { rowlimit = rows; } /** * @return Returns the prepStatementInsert. */ public PreparedStatement getPrepStatementInsert() { return prepStatementInsert; } /** * @return Returns the prepStatementLookup. */ public PreparedStatement getPrepStatementLookup() { return prepStatementLookup; } /** * @return Returns the prepStatementUpdate. */ public PreparedStatement getPrepStatementUpdate() { return prepStatementUpdate; } /** * Open the database connection. * @throws KettleDatabaseException if something went wrong. */ public void connect() throws KettleDatabaseException { connect(null); } /** * Open the database connection. * @param partitionId the partition ID in the cluster to connect to. * @throws KettleDatabaseException if something went wrong. */ public void connect(String partitionId) throws KettleDatabaseException { connect(null, partitionId); } public synchronized void connect(String group, String partitionId) throws KettleDatabaseException { // Before anything else, let's see if we already have a connection defined for this group/partition! // The group is called after the thread-name of the transformation or job that is running // The name of that threadname is expected to be unique (it is in Kettle) // So the deal is that if there is another thread using that, we go for it. if (!Const.isEmpty(group)) { this.connectionGroup = group; this.partitionId = partitionId; DatabaseConnectionMap map = DatabaseConnectionMap.getInstance(); // Try to find the conection for the group Database lookup = map.getDatabase(group, partitionId, this); if (lookup==null) // We already opened this connection for the partition & database in this group { // Do a normal connect and then store this database object for later re-use. normalConnect(partitionId); opened++; copy = opened; map.storeDatabase(group, partitionId, this); } else { connection = lookup.getConnection(); lookup.setOpened(lookup.getOpened()+1); // if this counter hits 0 again, close the connection. copy = lookup.getOpened(); } } else { // Proceed with a normal connect normalConnect(partitionId); } } /** * Open the database connection. * @param partitionId the partition ID in the cluster to connect to. * @throws KettleDatabaseException if something went wrong. */ public void normalConnect(String partitionId) throws KettleDatabaseException { if (databaseMeta==null) { throw new KettleDatabaseException("No valid database connection defined!"); } try { // First see if we use connection pooling... if ( databaseMeta.isUsingConnectionPool() && // default = false for backward compatibility databaseMeta.getAccessType()!=DatabaseMeta.TYPE_ACCESS_JNDI // JNDI does pooling on it's own. ) { try { this.connection = ConnectionPoolUtil.getConnection(databaseMeta, partitionId); } catch (Exception e) { throw new KettleDatabaseException("Error occured while trying to connect to the database", e); } } else { connectUsingClass(databaseMeta.getDriverClass(), partitionId ); log.logDetailed(toString(), "Connected to database."); // See if we need to execute extra SQL statemtent... String sql = environmentSubstitute( databaseMeta.getConnectSQL() ); // only execute if the SQL is not empty, null and is not just a bunch of spaces, tabs, CR etc. if (!Const.isEmpty(sql) && !Const.onlySpaces(sql)) { execStatements(sql); log.logDetailed(toString(), "Executed connect time SQL statements:"+Const.CR+sql); } } } catch(Exception e) { throw new KettleDatabaseException("Error occured while trying to connect to the database", e); } } private void initWithJNDI(String jndiName) throws KettleDatabaseException { connection = null; try { DataSource dataSource = DatabaseUtil.getDataSourceFromJndi(jndiName); if (dataSource != null) { connection = dataSource.getConnection(); if (connection == null) { throw new KettleDatabaseException( "Invalid JNDI connection "+ jndiName); //$NON-NLS-1$ } } else { throw new KettleDatabaseException( "Invalid JNDI connection "+ jndiName); //$NON-NLS-1$ } } catch (Exception e) { throw new KettleDatabaseException( "Invalid JNDI connection "+ jndiName + " : " + e.getMessage()); //$NON-NLS-1$ } } /** * Connect using the correct classname * @param classname for example "org.gjt.mm.mysql.Driver" * @return true if the connect was succesfull, false if something went wrong. */ private void connectUsingClass(String classname, String partitionId) throws KettleDatabaseException { // Install and load the jdbc Driver // first see if this is a JNDI connection if( databaseMeta.getAccessType() == DatabaseMeta.TYPE_ACCESS_JNDI ) { initWithJNDI( environmentSubstitute(databaseMeta.getDatabaseName()) ); return; } try { Class.forName(classname); } catch(NoClassDefFoundError e) { throw new KettleDatabaseException("Exception while loading class", e); } catch(ClassNotFoundException e) { throw new KettleDatabaseException("Exception while loading class", e); } catch(Exception e) { throw new KettleDatabaseException("Exception while loading class", e); } try { String url; if (databaseMeta.isPartitioned() && !Const.isEmpty(partitionId)) { url = environmentSubstitute(databaseMeta.getURL(partitionId)); } else { url = environmentSubstitute(databaseMeta.getURL()); } String clusterUsername=null; String clusterPassword=null; if (databaseMeta.isPartitioned() && !Const.isEmpty(partitionId)) { // Get the cluster information... PartitionDatabaseMeta partition = databaseMeta.getPartitionMeta(partitionId); if (partition!=null) { clusterUsername = partition.getUsername(); clusterPassword = Encr.decryptPasswordOptionallyEncrypted(partition.getPassword()); } } String username; String password; if (!Const.isEmpty(clusterUsername)) { username = clusterUsername; password = clusterPassword; } else { username = environmentSubstitute(databaseMeta.getUsername()); password = Encr.decryptPasswordOptionallyEncrypted(environmentSubstitute(databaseMeta.getPassword())); } if (databaseMeta.supportsOptionsInURL()) { if (!Const.isEmpty(username) || !Const.isEmpty(password)) { // also allow for empty username with given password, in this case username must be given with one space connection = DriverManager.getConnection(url, Const.NVL(username, " "), Const.NVL(password, "")); } else { // Perhaps the username is in the URL or no username is required... connection = DriverManager.getConnection(url); } } else { Properties properties = databaseMeta.getConnectionProperties(); if (!Const.isEmpty(username)) properties.put("user", username); if (!Const.isEmpty(password)) properties.put("password", password); connection = DriverManager.getConnection(url, properties); } } catch(SQLException e) { throw new KettleDatabaseException("Error connecting to database: (using class "+classname+")", e); } catch(Throwable e) { throw new KettleDatabaseException("Error connecting to database: (using class "+classname+")", e); } } /** * Disconnect from the database and close all open prepared statements. */ public synchronized void disconnect() { try { if (connection==null) { return ; // Nothing to do... } if (connection.isClosed()) { return ; // Nothing to do... } if (pstmt !=null) { pstmt.close(); pstmt=null; } if (prepStatementLookup!=null) { prepStatementLookup.close(); prepStatementLookup=null; } if (prepStatementInsert!=null) { prepStatementInsert.close(); prepStatementInsert=null; } if (prepStatementUpdate!=null) { prepStatementUpdate.close(); prepStatementUpdate=null; } if (pstmt_seq!=null) { pstmt_seq.close(); pstmt_seq=null; } // See if there are other steps using this connection in a connection group. // If so, we will hold commit & connection close until then. if (!Const.isEmpty(connectionGroup)) { return; } else { if (!isAutoCommit()) // Do we really still need this commit?? { commit(); } } closeConnectionOnly(); } catch(SQLException ex) { log.logError(toString(), "Error disconnecting from database:"+Const.CR+ex.getMessage()); log.logError(toString(), Const.getStackTracker(ex)); } catch(KettleDatabaseException dbe) { log.logError(toString(), "Error disconnecting from database:"+Const.CR+dbe.getMessage()); log.logError(toString(), Const.getStackTracker(dbe)); } } /** * Only for unique connections usage, typically you use disconnect() to disconnect() from the database. * @throws KettleDatabaseException in case there is an error during connection close. */ public synchronized void closeConnectionOnly() throws KettleDatabaseException { try { if (connection!=null) { connection.close(); if (!databaseMeta.isUsingConnectionPool()) { connection=null; } } log.logDetailed(toString(), "Connection to database closed!"); } catch(SQLException e) { throw new KettleDatabaseException("Error disconnecting from database '"+toString()+"'", e); } } /** * Cancel the open/running queries on the database connection * @throws KettleDatabaseException */ public void cancelQuery() throws KettleDatabaseException { cancelStatement(pstmt); cancelStatement(sel_stmt); } /** * Cancel an open/running SQL statement * @param statement the statement to cancel * @throws KettleDatabaseException */ public void cancelStatement(Statement statement) throws KettleDatabaseException { try { if (statement!=null) { statement.cancel(); } log.logDetailed(toString(), "Statement canceled!"); } catch(SQLException ex) { throw new KettleDatabaseException("Error cancelling statement", ex); } } /** * Specify after how many rows a commit needs to occur when inserting or updating values. * @param commsize The number of rows to wait before doing a commit on the connection. */ public void setCommit(int commsize) { commitsize=commsize; String onOff = (commitsize<=0?"on":"off"); try { connection.setAutoCommit(commitsize<=0); log.logDetailed(toString(), "Auto commit "+onOff); } catch(Exception e) { log.logError(toString(), "Can't turn auto commit "+onOff); } } public void setAutoCommit(boolean useAutoCommit) throws KettleDatabaseException { try { connection.setAutoCommit(useAutoCommit); } catch (SQLException e) { if (useAutoCommit) { throw new KettleDatabaseException(Messages.getString("Database.Exception.UnableToEnableAutoCommit", toString())); } else { throw new KettleDatabaseException(Messages.getString("Database.Exception.UnableToDisableAutoCommit", toString())); } } } /** * Perform a commit the connection if this is supported by the database */ public void commit() throws KettleDatabaseException { commit(false); } public void commit(boolean force) throws KettleDatabaseException { try { // Don't do the commit, wait until the end of the transformation. // When the last database copy (opened counter) is about to be closed, we do a commit // There is one catch, we need to catch the rollback // The transformation will stop everything and then we'll do the rollback. // The flag is in "performRollback", private only if (!Const.isEmpty(connectionGroup) && !force) { return; } if (getDatabaseMetaData().supportsTransactions()) { if (log.isDebug()) log.logDebug(toString(), "Commit on database connection ["+toString()+"]"); connection.commit(); } else { log.logDetailed(toString(), "No commit possible on database connection ["+toString()+"]"); } } catch(Exception e) { if (databaseMeta.supportsEmptyTransactions()) throw new KettleDatabaseException("Error comitting connection", e); } } public void rollback() throws KettleDatabaseException { rollback(false); } public void rollback(boolean force) throws KettleDatabaseException { try { if (!Const.isEmpty(connectionGroup) && !force) { return; // Will be handled by Trans --> endProcessing() } if (getDatabaseMetaData().supportsTransactions()) { if (connection!=null) { if (log.isDebug()) log.logDebug(toString(), "Rollback on database connection ["+toString()+"]"); connection.rollback(); } } else { log.logDetailed(toString(), "No rollback possible on database connection ["+toString()+"]"); } } catch(SQLException e) { throw new KettleDatabaseException("Error performing rollback on connection", e); } } /** * Prepare inserting values into a table, using the fields & values in a Row * @param rowMeta The row metadata to determine which values need to be inserted * @param table The name of the table in which we want to insert rows * @throws KettleDatabaseException if something went wrong. */ public void prepareInsert(RowMetaInterface rowMeta, String tableName) throws KettleDatabaseException { prepareInsert(rowMeta, null, tableName); } /** * Prepare inserting values into a table, using the fields & values in a Row * @param rowMeta The metadata row to determine which values need to be inserted * @param schemaName The name of the schema in which we want to insert rows * @param tableName The name of the table in which we want to insert rows * @throws KettleDatabaseException if something went wrong. */ public void prepareInsert(RowMetaInterface rowMeta, String schemaName, String tableName) throws KettleDatabaseException { if (rowMeta.size()==0) { throw new KettleDatabaseException("No fields in row, can't insert!"); } String ins = getInsertStatement(schemaName, tableName, rowMeta); log.logDetailed(toString(),"Preparing statement: "+Const.CR+ins); prepStatementInsert=prepareSQL(ins); } /** * Prepare a statement to be executed on the database. (does not return generated keys) * @param sql The SQL to be prepared * @return The PreparedStatement object. * @throws KettleDatabaseException */ public PreparedStatement prepareSQL(String sql) throws KettleDatabaseException { return prepareSQL(sql, false); } /** * Prepare a statement to be executed on the database. * @param sql The SQL to be prepared * @param returnKeys set to true if you want to return generated keys from an insert statement * @return The PreparedStatement object. * @throws KettleDatabaseException */ public PreparedStatement prepareSQL(String sql, boolean returnKeys) throws KettleDatabaseException { try { if (returnKeys) { return connection.prepareStatement(databaseMeta.stripCR(sql), Statement.RETURN_GENERATED_KEYS); } else { return connection.prepareStatement(databaseMeta.stripCR(sql)); } } catch(SQLException ex) { throw new KettleDatabaseException("Couldn't prepare statement:"+Const.CR+sql, ex); } } public void closeLookup() throws KettleDatabaseException { closePreparedStatement(pstmt); pstmt=null; } public void closePreparedStatement(PreparedStatement ps) throws KettleDatabaseException { if (ps!=null) { try { ps.close(); } catch(SQLException e) { throw new KettleDatabaseException("Error closing prepared statement", e); } } } public void closeInsert() throws KettleDatabaseException { if (prepStatementInsert!=null) { try { prepStatementInsert.close(); prepStatementInsert = null; } catch(SQLException e) { throw new KettleDatabaseException("Error closing insert prepared statement.", e); } } } public void closeUpdate() throws KettleDatabaseException { if (prepStatementUpdate!=null) { try { prepStatementUpdate.close(); prepStatementUpdate=null; } catch(SQLException e) { throw new KettleDatabaseException("Error closing update prepared statement.", e); } } } public void setValues(RowMetaInterface rowMeta, Object[] data) throws KettleDatabaseException { setValues(rowMeta, data, pstmt); } public void setValues(RowMetaAndData row) throws KettleDatabaseException { setValues(row.getRowMeta(), row.getData()); } public void setValuesInsert(RowMetaInterface rowMeta, Object[] data) throws KettleDatabaseException { setValues(rowMeta, data, prepStatementInsert); } public void setValuesInsert(RowMetaAndData row) throws KettleDatabaseException { setValues(row.getRowMeta(), row.getData(), prepStatementInsert); } public void setValuesUpdate(RowMetaInterface rowMeta, Object[] data) throws KettleDatabaseException { setValues(rowMeta, data, prepStatementUpdate); } public void setValuesLookup(RowMetaInterface rowMeta, Object[] data) throws KettleDatabaseException { setValues(rowMeta, data, prepStatementLookup); } public void setProcValues(RowMetaInterface rowMeta, Object[] data, int argnrs[], String argdir[], boolean result) throws KettleDatabaseException { int pos; if (result) pos=2; else pos=1; for (int i=0;i<argnrs.length;i++) { if (argdir[i].equalsIgnoreCase("IN") || argdir[i].equalsIgnoreCase("INOUT")) { ValueMetaInterface valueMeta = rowMeta.getValueMeta(argnrs[i]); Object value = data[argnrs[i]]; setValue(cstmt, valueMeta, value, pos); pos++; } else { pos++; //next parameter when OUT } } } public void setValue(PreparedStatement ps, ValueMetaInterface v, Object object, int pos) throws KettleDatabaseException { String debug = ""; try { switch(v.getType()) { case ValueMetaInterface.TYPE_NUMBER : if (object!=null) { debug="Number, not null, getting number from value"; double num = v.getNumber(object).doubleValue(); if (databaseMeta.supportsFloatRoundingOnUpdate() && v.getPrecision()>=0) { debug="Number, rounding to precision ["+v.getPrecision()+"]"; num = Const.round(num, v.getPrecision()); } debug="Number, setting ["+num+"] on position #"+pos+" of the prepared statement"; ps.setDouble(pos, num); } else { ps.setNull(pos, java.sql.Types.DOUBLE); } break; case ValueMetaInterface.TYPE_INTEGER: debug="Integer"; if (object!=null) { if (databaseMeta.supportsSetLong()) { ps.setLong(pos, v.getInteger(object).longValue() ); } else { double d = v.getNumber(object).doubleValue(); if (databaseMeta.supportsFloatRoundingOnUpdate() && v.getPrecision()>=0) { ps.setDouble(pos, d ); } else { ps.setDouble(pos, Const.round( d, v.getPrecision() ) ); } } } else { ps.setNull(pos, java.sql.Types.INTEGER); } break; case ValueMetaInterface.TYPE_STRING : debug="String"; if (v.getLength()<DatabaseMeta.CLOB_LENGTH) { if (object!=null) { ps.setString(pos, v.getString(object)); } else { ps.setNull(pos, java.sql.Types.VARCHAR); } } else { if (object!=null) { String string = v.getString(object); int maxlen = databaseMeta.getMaxTextFieldLength(); int len = string.length(); // Take the last maxlen characters of the string... int begin = len - maxlen; if (begin<0) begin=0; // Get the substring! String logging = string.substring(begin); if (databaseMeta.supportsSetCharacterStream()) { StringReader sr = new StringReader(logging); ps.setCharacterStream(pos, sr, logging.length()); } else { ps.setString(pos, logging); } } else { ps.setNull(pos, java.sql.Types.VARCHAR); } } break; case ValueMetaInterface.TYPE_DATE : debug="Date"; if (object!=null) { long dat = v.getInteger(object).longValue(); // converts using Date.getTime() if(v.getPrecision()==1 || !databaseMeta.supportsTimeStampToDateConversion()) { // Convert to DATE! java.sql.Date ddate = new java.sql.Date(dat); ps.setDate(pos, ddate); } else { java.sql.Timestamp sdate = new java.sql.Timestamp(dat); ps.setTimestamp(pos, sdate); } } else { if(v.getPrecision()==1 || !databaseMeta.supportsTimeStampToDateConversion()) { ps.setNull(pos, java.sql.Types.DATE); } else { ps.setNull(pos, java.sql.Types.TIMESTAMP); } } break; case ValueMetaInterface.TYPE_BOOLEAN: debug="Boolean"; if (databaseMeta.supportsBooleanDataType()) { if (object!=null) { ps.setBoolean(pos, v.getBoolean(object).booleanValue()); } else { ps.setNull(pos, java.sql.Types.BOOLEAN); } } else { if (object!=null) { ps.setString(pos, v.getBoolean(object).booleanValue()?"Y":"N"); } else { ps.setNull(pos, java.sql.Types.CHAR); } } break; case ValueMetaInterface.TYPE_BIGNUMBER: debug="BigNumber"; if (object!=null) { ps.setBigDecimal(pos, v.getBigNumber(object)); } else { ps.setNull(pos, java.sql.Types.DECIMAL); } break; case ValueMetaInterface.TYPE_BINARY: debug="Binary"; if (object!=null) { ps.setBytes(pos, v.getBinary(object)); } else { ps.setNull(pos, java.sql.Types.BINARY); } break; default: debug="default"; // placeholder ps.setNull(pos, java.sql.Types.VARCHAR); break; } } catch(SQLException ex) { throw new KettleDatabaseException("Error setting value #"+pos+" ["+v.toString()+"] on prepared statement ("+debug+")"+Const.CR+ex.toString(), ex); } catch(Exception e) { throw new KettleDatabaseException("Error setting value #"+pos+" ["+(v==null?"NULL":v.toString())+"] on prepared statement ("+debug+")"+Const.CR+e.toString(), e); } } public void setValues(RowMetaAndData row, PreparedStatement ps) throws KettleDatabaseException { setValues(row.getRowMeta(), row.getData(), ps); } public void setValues(RowMetaInterface rowMeta, Object[] data, PreparedStatement ps) throws KettleDatabaseException { // now set the values in the row! for (int i=0;i<rowMeta.size();i++) { ValueMetaInterface v = rowMeta.getValueMeta(i); Object object = data[i]; try { setValue(ps, v, object, i+1); } catch(KettleDatabaseException e) { throw new KettleDatabaseException("offending row : "+rowMeta, e); } } } /** * Sets the values of the preparedStatement pstmt. * @param rowMeta * @param data */ public void setValues(RowMetaInterface rowMeta, Object[] data, PreparedStatement ps, int ignoreThisValueIndex) throws KettleDatabaseException { // now set the values in the row! int index=0; for (int i=0;i<rowMeta.size();i++) { if (i!=ignoreThisValueIndex) { ValueMetaInterface v = rowMeta.getValueMeta(i); Object object = data[i]; try { setValue(ps, v, object, index+1); index++; } catch(KettleDatabaseException e) { throw new KettleDatabaseException("offending row : "+rowMeta, e); } } } } /** * @param ps The prepared insert statement to use * @return The generated keys in auto-increment fields * @throws KettleDatabaseException in case something goes wrong retrieving the keys. */ public RowMetaAndData getGeneratedKeys(PreparedStatement ps) throws KettleDatabaseException { ResultSet keys = null; try { keys=ps.getGeneratedKeys(); // 1 row of keys ResultSetMetaData resultSetMetaData = keys.getMetaData(); RowMetaInterface rowMeta = getRowInfo(resultSetMetaData, false, false); return new RowMetaAndData(rowMeta, getRow(keys, resultSetMetaData, rowMeta)); } catch(Exception ex) { throw new KettleDatabaseException("Unable to retrieve key(s) from auto-increment field(s)", ex); } finally { if (keys!=null) { try { keys.close(); } catch(SQLException e) { throw new KettleDatabaseException("Unable to close resultset of auto-generated keys", e); } } } } public Long getNextSequenceValue(String sequenceName, String keyfield) throws KettleDatabaseException { return getNextSequenceValue(null, sequenceName, keyfield); } public Long getNextSequenceValue(String schemaName, String sequenceName, String keyfield) throws KettleDatabaseException { Long retval=null; String schemaSequence = databaseMeta.getQuotedSchemaTableCombination(schemaName, sequenceName); try { if (pstmt_seq==null) { pstmt_seq=connection.prepareStatement(databaseMeta.getSeqNextvalSQL(databaseMeta.stripCR(schemaSequence))); } ResultSet rs=null; try { rs = pstmt_seq.executeQuery(); if (rs.next()) { retval = Long.valueOf( rs.getLong(1) ); } } finally { if ( rs != null ) rs.close(); } } catch(SQLException ex) { throw new KettleDatabaseException("Unable to get next value for sequence : "+schemaSequence, ex); } return retval; } public void insertRow(String tableName, RowMetaInterface fields, Object[] data) throws KettleDatabaseException { prepareInsert(fields, tableName); setValuesInsert(fields, data); insertRow(); closeInsert(); } public String getInsertStatement(String tableName, RowMetaInterface fields) { return getInsertStatement(null, tableName, fields); } public String getInsertStatement(String schemaName, String tableName, RowMetaInterface fields) { StringBuffer ins=new StringBuffer(128); String schemaTable = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName); ins.append("INSERT INTO ").append(schemaTable).append('('); // now add the names in the row: for (int i=0;i<fields.size();i++) { if (i>0) ins.append(", "); String name = fields.getValueMeta(i).getName(); ins.append(databaseMeta.quoteField(name)); } ins.append(") VALUES ("); // Add placeholders... for (int i=0;i<fields.size();i++) { if (i>0) ins.append(", "); ins.append(" ?"); } ins.append(')'); return ins.toString(); } public void insertRow() throws KettleDatabaseException { insertRow(prepStatementInsert); } public void insertRow(boolean batch) throws KettleDatabaseException { insertRow(prepStatementInsert, batch); } public void updateRow() throws KettleDatabaseException { insertRow(prepStatementUpdate); } public void insertRow(PreparedStatement ps) throws KettleDatabaseException { insertRow(ps, false); } /** * Insert a row into the database using a prepared statement that has all values set. * @param ps The prepared statement * @param batch True if you want to use batch inserts (size = commit size) * @return true if the rows are safe: if batch of rows was sent to the database OR if a commit was done. * @throws KettleDatabaseException */ public boolean insertRow(PreparedStatement ps, boolean batch) throws KettleDatabaseException { String debug="insertRow start"; boolean rowsAreSafe=false; try { // Unique connections and Batch inserts don't mix when you want to roll back on certain databases. // That's why we disable the batch insert in that case. boolean useBatchInsert = batch && getDatabaseMetaData().supportsBatchUpdates() && databaseMeta.supportsBatchUpdates() && Const.isEmpty(connectionGroup); // Add support for batch inserts... if (!isAutoCommit()) { if (useBatchInsert) { debug="insertRow add batch"; ps.addBatch(); // Add the batch, but don't forget to run the batch } else { debug="insertRow exec update"; ps.executeUpdate(); } } else { ps.executeUpdate(); } written++; /* if (!isAutoCommit() && (written%commitsize)==0) { if (useBatchInsert) { debug="insertRow executeBatch commit"; ps.executeBatch(); commit(); ps.clearBatch(); batchCounterMap.put(ps, Integer.valueOf(0)); } else { debug="insertRow normal commit"; commit(); } rowsAreSafe=true; } */ return rowsAreSafe; } catch(BatchUpdateException ex) { KettleDatabaseBatchException kdbe = new KettleDatabaseBatchException("Error updating batch", ex); kdbe.setUpdateCounts(ex.getUpdateCounts()); List<Exception> exceptions = new ArrayList<Exception>(); // 'seed' the loop with the root exception SQLException nextException = ex; do { exceptions.add(nextException); // while current exception has next exception, add to list } while ((nextException = nextException.getNextException())!=null); kdbe.setExceptionsList(exceptions); throw kdbe; } catch(SQLException ex) { // log.logError(toString(), Const.getStackTracker(ex)); throw new KettleDatabaseException("Error inserting row", ex); } catch(Exception e) { // System.out.println("Unexpected exception in ["+debug+"] : "+e.getMessage()); throw new KettleDatabaseException("Unexpected error inserting row in part ["+debug+"]", e); } } /** * Clears batch of insert prepared statement * @deprecated * @throws KettleDatabaseException */ public void clearInsertBatch() throws KettleDatabaseException { clearBatch(prepStatementInsert); } public void clearBatch(PreparedStatement preparedStatement) throws KettleDatabaseException { try { preparedStatement.clearBatch(); } catch(SQLException e) { throw new KettleDatabaseException("Unable to clear batch for prepared statement", e); } } public void insertFinished(boolean batch) throws KettleDatabaseException { insertFinished(prepStatementInsert, batch); prepStatementInsert = null; } /** * Close the prepared statement of the insert statement. * * @param ps The prepared statement to empty and close. * @param batch true if you are using batch processing * @param psBatchCounter The number of rows on the batch queue * @throws KettleDatabaseException */ public void emptyAndCommit(PreparedStatement ps, boolean batch, int batchCounter) throws KettleDatabaseException { try { if (ps!=null) { if (!isAutoCommit()) { // Execute the batch or just perform a commit. if (batch && getDatabaseMetaData().supportsBatchUpdates() && batchCounter>0) { // The problem with the batch counters is that you can't just execute the current batch. // Certain databases have a problem if you execute the batch and if there are no statements in it. // You can't just catch the exception either because you would have to roll back on certain databases before you can then continue to do anything. // That leaves the task of keeping track of the number of rows up to our responsibility. ps.executeBatch(); commit(); } else { commit(); } } // Let's not forget to close the prepared statement. ps.close(); } } catch(BatchUpdateException ex) { KettleDatabaseBatchException kdbe = new KettleDatabaseBatchException("Error updating batch", ex); kdbe.setUpdateCounts(ex.getUpdateCounts()); List<Exception> exceptions = new ArrayList<Exception>(); SQLException nextException = ex.getNextException(); SQLException oldException = null; // This construction is specifically done for some JDBC drivers, these drivers // always return the same exception on getNextException() (and thus go into an infinite loop). // So it's not "equals" but != (comments from Sven Boden). while ( (nextException != null) && (oldException != nextException) ) { exceptions.add(nextException); oldException = nextException; nextException = nextException.getNextException(); } kdbe.setExceptionsList(exceptions); throw kdbe; } catch(SQLException ex) { throw new KettleDatabaseException("Unable to empty ps and commit connection.", ex); } } /** * Close the prepared statement of the insert statement. * * @param ps The prepared statement to empty and close. * @param batch true if you are using batch processing (typically true for this method) * @param psBatchCounter The number of rows on the batch queue * @throws KettleDatabaseException * * @deprecated use emptyAndCommit() instead (pass in the number of rows left in the batch) */ public void insertFinished(PreparedStatement ps, boolean batch) throws KettleDatabaseException { try { if (ps!=null) { if (!isAutoCommit()) { // Execute the batch or just perform a commit. if (batch && getDatabaseMetaData().supportsBatchUpdates()) { // The problem with the batch counters is that you can't just execute the current batch. // Certain databases have a problem if you execute the batch and if there are no statements in it. // You can't just catch the exception either because you would have to roll back on certain databases before you can then continue to do anything. // That leaves the task of keeping track of the number of rows up to our responsibility. ps.executeBatch(); commit(); } else { commit(); } } // Let's not forget to close the prepared statement. ps.close(); } } catch(BatchUpdateException ex) { KettleDatabaseBatchException kdbe = new KettleDatabaseBatchException("Error updating batch", ex); kdbe.setUpdateCounts(ex.getUpdateCounts()); List<Exception> exceptions = new ArrayList<Exception>(); SQLException nextException = ex.getNextException(); SQLException oldException = null; // This construction is specifically done for some JDBC drivers, these drivers // always return the same exception on getNextException() (and thus go into an infinite loop). // So it's not "equals" but != (comments from Sven Boden). while ( (nextException != null) && (oldException != nextException) ) { exceptions.add(nextException); oldException = nextException; nextException = nextException.getNextException(); } kdbe.setExceptionsList(exceptions); throw kdbe; } catch(SQLException ex) { throw new KettleDatabaseException("Unable to commit connection after having inserted rows.", ex); } } /** * Execute an SQL statement on the database connection (has to be open) * @param sql The SQL to execute * @return a Result object indicating the number of lines read, deleted, inserted, updated, ... * @throws KettleDatabaseException in case anything goes wrong. */ public Result execStatement(String sql) throws KettleDatabaseException { return execStatement(sql, null, null); } public Result execStatement(String sql, RowMetaInterface params, Object[] data) throws KettleDatabaseException { Result result = new Result(); try { boolean resultSet; int count; if (params!=null) { PreparedStatement prep_stmt = connection.prepareStatement(databaseMeta.stripCR(sql)); setValues(params, data, prep_stmt); // set the parameters! resultSet = prep_stmt.execute(); count = prep_stmt.getUpdateCount(); prep_stmt.close(); } else { String sqlStripped = databaseMeta.stripCR(sql); // log.logDetailed(toString(), "Executing SQL Statement: ["+sqlStripped+"]"); Statement stmt = connection.createStatement(); resultSet = stmt.execute(sqlStripped); count = stmt.getUpdateCount(); stmt.close(); } if (resultSet) { // the result is a resultset, but we don't do anything with it! // You should have called something else! // log.logDetailed(toString(), "What to do with ResultSet??? (count="+count+")"); } else { if (count > 0) { if (sql.toUpperCase().startsWith("INSERT")) result.setNrLinesOutput(count); if (sql.toUpperCase().startsWith("UPDATE")) result.setNrLinesUpdated(count); if (sql.toUpperCase().startsWith("DELETE")) result.setNrLinesDeleted(count); } } // See if a cache needs to be cleared... if (sql.toUpperCase().startsWith("ALTER TABLE") || sql.toUpperCase().startsWith("DROP TABLE") || sql.toUpperCase().startsWith("CREATE TABLE") ) { DBCache.getInstance().clear(databaseMeta.getName()); } } catch(SQLException ex) { throw new KettleDatabaseException("Couldn't execute SQL: "+sql+Const.CR, ex); } catch(Exception e) { throw new KettleDatabaseException("Unexpected error executing SQL: "+Const.CR, e); } return result; } /** * Execute a series of SQL statements, separated by ; * * We are already connected... * Multiple statements have to be split into parts * We use the ";" to separate statements... * * We keep the results in Result object from Jobs * * @param script The SQL script to be execute * @throws KettleDatabaseException In case an error occurs * @return A result with counts of the number or records updates, inserted, deleted or read. */ public Result execStatements(String script) throws KettleDatabaseException { Result result = new Result(); String all = script; int from=0; int to=0; int length = all.length(); int nrstats = 0; while (to<length) { char c = all.charAt(to); if (c=='"') { to++; c=' '; while (to<length && c!='"') { c=all.charAt(to); to++; } } else if (c=='\'') // skip until next ' { to++; c=' '; while (to<length && c!='\'') { c=all.charAt(to); to++; } } else if (all.substring(to).startsWith("--")) // -- means: ignore comment until end of line... { to++; while (to<length && c!='\n' && c!='\r') { c=all.charAt(to); to++; } } if (c==';' || to>=length-1) // end of statement { if (to>=length-1) to++; // grab last char also! String stat; if (to<=length) stat = all.substring(from, to); else stat = all.substring(from); // If it ends with a ; remove that ; // Oracle for example can't stand it when this happens... if (stat.length()>0 && stat.charAt(stat.length()-1)==';') { stat = stat.substring(0,stat.length()-1); } if (!Const.onlySpaces(stat)) { String sql=Const.trim(stat); if (sql.toUpperCase().startsWith("SELECT")) { // A Query log.logDetailed(toString(), "launch SELECT statement: "+Const.CR+sql); nrstats++; ResultSet rs = null; try { rs = openQuery(sql); if (rs!=null) { Object[] row = getRow(rs); while (row!=null) { result.setNrLinesRead(result.getNrLinesRead()+1); if (log.isDetailed()) log.logDetailed(toString(), rowMeta.getString(row)); row = getRow(rs); } } else { if (log.isDebug()) log.logDebug(toString(), "Error executing query: "+Const.CR+sql); } } catch (KettleValueException e) { throw new KettleDatabaseException(e); // just pass the error upwards. } finally { try { if ( rs != null ) rs.close(); } catch (SQLException ex ) { if (log.isDebug()) log.logDebug(toString(), "Error closing query: "+Const.CR+sql); } } } else // any kind of statement { log.logDetailed(toString(), "launch DDL statement: "+Const.CR+sql); // A DDL statement nrstats++; Result res = execStatement(sql); result.add(res); } } to++; from=to; } else { to++; } } log.logDetailed(toString(), nrstats+" statement"+(nrstats==1?"":"s")+" executed"); return result; } public ResultSet openQuery(String sql) throws KettleDatabaseException { return openQuery(sql, null, null); } /** * Open a query on the database with a set of parameters stored in a Kettle Row * @param sql The SQL to launch with question marks (?) as placeholders for the parameters * @param params The parameters or null if no parameters are used. * @data the parameter data to open the query with * @return A JDBC ResultSet * @throws KettleDatabaseException when something goes wrong with the query. */ public ResultSet openQuery(String sql, RowMetaInterface params, Object[] data) throws KettleDatabaseException { return openQuery(sql, params, data, ResultSet.FETCH_FORWARD); } public ResultSet openQuery(String sql, RowMetaInterface params, Object[] data, int fetch_mode) throws KettleDatabaseException { return openQuery(sql, params, data, fetch_mode, false); } public ResultSet openQuery(String sql, RowMetaInterface params, Object[] data, int fetch_mode, boolean lazyConversion) throws KettleDatabaseException { ResultSet res; String debug = "Start"; // Create a Statement try { if (params!=null) { debug = "P create prepared statement (con==null? "+(connection==null)+")"; pstmt = connection.prepareStatement(databaseMeta.stripCR(sql), ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); debug = "P Set values"; setValues(params, data); // set the dates etc! if (canWeSetFetchSize(pstmt) ) { debug = "P Set fetchsize"; int fs = Const.FETCH_SIZE<=pstmt.getMaxRows()?pstmt.getMaxRows():Const.FETCH_SIZE; // System.out.println("Setting pstmt fetchsize to : "+fs); { if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL && databaseMeta.isStreamingResults()) { pstmt.setFetchSize(Integer.MIN_VALUE); } else pstmt.setFetchSize(fs); } debug = "P Set fetch direction"; pstmt.setFetchDirection(fetch_mode); } debug = "P Set max rows"; if (rowlimit>0 && databaseMeta.supportsSetMaxRows()) pstmt.setMaxRows(rowlimit); debug = "exec query"; res = pstmt.executeQuery(); } else { debug = "create statement"; sel_stmt = connection.createStatement(); if (canWeSetFetchSize(sel_stmt)) { debug = "Set fetchsize"; int fs = Const.FETCH_SIZE<=sel_stmt.getMaxRows()?sel_stmt.getMaxRows():Const.FETCH_SIZE; if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL && databaseMeta.isStreamingResults()) { sel_stmt.setFetchSize(Integer.MIN_VALUE); } else { sel_stmt.setFetchSize(fs); } debug = "Set fetch direction"; sel_stmt.setFetchDirection(fetch_mode); } debug = "Set max rows"; if (rowlimit>0 && databaseMeta.supportsSetMaxRows()) sel_stmt.setMaxRows(rowlimit); debug = "exec query"; res=sel_stmt.executeQuery(databaseMeta.stripCR(sql)); } debug = "openQuery : get rowinfo"; // MySQL Hack only. It seems too much for the cursor type of operation on MySQL, to have another cursor opened // to get the length of a String field. So, on MySQL, we ingore the length of Strings in result rows. rowMeta = getRowInfo(res.getMetaData(), databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL, lazyConversion); } catch(SQLException ex) { // log.logError(toString(), "ERROR executing ["+sql+"]"); // log.logError(toString(), "ERROR in part: ["+debug+"]"); // printSQLException(ex); throw new KettleDatabaseException("An error occurred executing SQL: "+Const.CR+sql, ex); } catch(Exception e) { log.logError(toString(), "ERROR executing query: "+e.toString()); log.logError(toString(), "ERROR in part: "+debug); throw new KettleDatabaseException("An error occurred executing SQL in part ["+debug+"]:"+Const.CR+sql, e); } return res; } private boolean canWeSetFetchSize(Statement statement) throws SQLException { return databaseMeta.isFetchSizeSupported() && ( statement.getMaxRows()>0 || databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_POSTGRES || ( databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_MYSQL && databaseMeta.isStreamingResults() ) ); } public ResultSet openQuery(PreparedStatement ps, RowMetaInterface params, Object[] data) throws KettleDatabaseException { ResultSet res; String debug = "Start"; // Create a Statement try { debug = "OQ Set values"; setValues(params, data, ps); // set the parameters! if (canWeSetFetchSize(ps)) { debug = "OQ Set fetchsize"; int fs = Const.FETCH_SIZE<=ps.getMaxRows()?ps.getMaxRows():Const.FETCH_SIZE; if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL && databaseMeta.isStreamingResults()) { ps.setFetchSize(Integer.MIN_VALUE); } else { ps.setFetchSize(fs); } debug = "OQ Set fetch direction"; ps.setFetchDirection(ResultSet.FETCH_FORWARD); } debug = "OQ Set max rows"; if (rowlimit>0 && databaseMeta.supportsSetMaxRows()) ps.setMaxRows(rowlimit); debug = "OQ exec query"; res = ps.executeQuery(); debug = "OQ getRowInfo()"; // rowinfo = getRowInfo(res.getMetaData()); // MySQL Hack only. It seems too much for the cursor type of operation on MySQL, to have another cursor opened // to get the length of a String field. So, on MySQL, we ingore the length of Strings in result rows. rowMeta = getRowInfo(res.getMetaData(), databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL, false); } catch(SQLException ex) { throw new KettleDatabaseException("ERROR executing query in part["+debug+"]", ex); } catch(Exception e) { throw new KettleDatabaseException("ERROR executing query in part["+debug+"]", e); } return res; } public RowMetaInterface getTableFields(String tablename) throws KettleDatabaseException { return getQueryFields(databaseMeta.getSQLQueryFields(tablename), false); } public RowMetaInterface getQueryFields(String sql, boolean param) throws KettleDatabaseException { return getQueryFields(sql, param, null, null); } /** * See if the table specified exists by reading * @param tablename The name of the table to check. * @return true if the table exists, false if it doesn't. */ public boolean checkTableExists(String tablename) throws KettleDatabaseException { try { log.logDebug(toString(), "Checking if table ["+tablename+"] exists!"); // Just try to read from the table. String sql = databaseMeta.getSQLTableExists(tablename); try { getOneRow(sql); return true; } catch(KettleDatabaseException e) { return false; } /* if (getDatabaseMetaData()!=null) { ResultSet alltables = getDatabaseMetaData().getTables(null, null, "%" , new String[] { "TABLE", "VIEW", "SYNONYM" } ); boolean found = false; if (alltables!=null) { while (alltables.next() && !found) { String schemaName = alltables.getString("TABLE_SCHEM"); String name = alltables.getString("TABLE_NAME"); if ( tablename.equalsIgnoreCase(name) || ( schemaName!=null && tablename.equalsIgnoreCase( databaseMeta.getSchemaTableCombination(schemaName, name)) ) ) { log.logDebug(toString(), "table ["+tablename+"] was found!"); found=true; } } alltables.close(); return found; } else { throw new KettleDatabaseException("Unable to read table-names from the database meta-data."); } } else { throw new KettleDatabaseException("Unable to get database meta-data from the database."); } */ } catch(Exception e) { throw new KettleDatabaseException("Unable to check if table ["+tablename+"] exists on connection ["+databaseMeta.getName()+"]", e); } } /** * Check whether the sequence exists, Oracle only! * @param sequenceName The name of the sequence * @return true if the sequence exists. */ public boolean checkSequenceExists(String sequenceName) throws KettleDatabaseException { return checkSequenceExists(null, sequenceName); } /** * Check whether the sequence exists, Oracle only! * @param sequenceName The name of the sequence * @return true if the sequence exists. */ public boolean checkSequenceExists(String schemaName, String sequenceName) throws KettleDatabaseException { boolean retval=false; if (!databaseMeta.supportsSequences()) return retval; String schemaSequence = databaseMeta.getQuotedSchemaTableCombination(schemaName, sequenceName); try { // Get the info from the data dictionary... String sql = databaseMeta.getSQLSequenceExists(schemaSequence); ResultSet res = openQuery(sql); if (res!=null) { Object[] row = getRow(res); if (row!=null) { retval=true; } closeQuery(res); } } catch(Exception e) { throw new KettleDatabaseException("Unexpected error checking whether or not sequence ["+schemaSequence+"] exists", e); } return retval; } /** * Check if an index on certain fields in a table exists. * @param tableName The table on which the index is checked * @param idx_fields The fields on which the indexe is checked * @return True if the index exists */ public boolean checkIndexExists(String tableName, String idx_fields[]) throws KettleDatabaseException { return checkIndexExists(null, tableName, idx_fields); } /** * Check if an index on certain fields in a table exists. * @param tablename The table on which the index is checked * @param idx_fields The fields on which the indexe is checked * @return True if the index exists */ public boolean checkIndexExists(String schemaName, String tableName, String idx_fields[]) throws KettleDatabaseException { String tablename = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName); if (!checkTableExists(tablename)) return false; log.logDebug(toString(), "CheckIndexExists() tablename = "+tablename+" type = "+databaseMeta.getDatabaseTypeDesc()); boolean exists[] = new boolean[idx_fields.length]; for (int i=0;i<exists.length;i++) exists[i]=false; try { switch(databaseMeta.getDatabaseType()) { case DatabaseMeta.TYPE_DATABASE_MSSQL: { // Get the info from the data dictionary... StringBuffer sql = new StringBuffer(128); sql.append("select i.name table_name, c.name column_name "); sql.append("from sysindexes i, sysindexkeys k, syscolumns c "); sql.append("where i.name = '"+tablename+"' "); sql.append("AND i.id = k.id "); sql.append("AND i.id = c.id "); sql.append("AND k.colid = c.colid "); ResultSet res = null; try { res = openQuery(sql.toString()); if (res!=null) { Object[] row = getRow(res); while (row!=null) { String column = rowMeta.getString(row, "column_name", ""); int idx = Const.indexOfString(column, idx_fields); if (idx>=0) exists[idx]=true; row = getRow(res); } } else { return false; } } finally { if ( res != null ) closeQuery(res); } } break; case DatabaseMeta.TYPE_DATABASE_ORACLE: { // Get the info from the data dictionary... String sql = "SELECT * FROM USER_IND_COLUMNS WHERE TABLE_NAME = '"+tableName+"'"; ResultSet res = null; try { res = openQuery(sql); if (res!=null) { Object[] row = getRow(res); while (row!=null) { String column = rowMeta.getString(row, "COLUMN_NAME", ""); int idx = Const.indexOfString(column, idx_fields); if (idx>=0) { exists[idx]=true; } row = getRow(res); } } else { return false; } } finally { if ( res != null ) closeQuery(res); } } break; case DatabaseMeta.TYPE_DATABASE_ACCESS: { // Get a list of all the indexes for this table ResultSet indexList = null; try { indexList = getDatabaseMetaData().getIndexInfo(null,null,tablename,false,true); while (indexList.next()) { // String tablen = indexList.getString("TABLE_NAME"); // String indexn = indexList.getString("INDEX_NAME"); String column = indexList.getString("COLUMN_NAME"); // int pos = indexList.getShort("ORDINAL_POSITION"); // int type = indexList.getShort("TYPE"); int idx = Const.indexOfString(column, idx_fields); if (idx>=0) { exists[idx]=true; } } } finally { if ( indexList != null ) indexList.close(); } } break; default: { // Get a list of all the indexes for this table ResultSet indexList = null; try { indexList = getDatabaseMetaData().getIndexInfo(null,null,tablename,false,true); while (indexList.next()) { // String tablen = indexList.getString("TABLE_NAME"); // String indexn = indexList.getString("INDEX_NAME"); String column = indexList.getString("COLUMN_NAME"); // int pos = indexList.getShort("ORDINAL_POSITION"); // int type = indexList.getShort("TYPE"); int idx = Const.indexOfString(column, idx_fields); if (idx>=0) { exists[idx]=true; } } } finally { if ( indexList != null ) indexList.close(); } } break; } // See if all the fields are indexed... boolean all=true; for (int i=0;i<exists.length && all;i++) if (!exists[i]) all=false; return all; } catch(Exception e) { log.logError(toString(), Const.getStackTracker(e)); throw new KettleDatabaseException("Unable to determine if indexes exists on table ["+tablename+"]", e); } } public String getCreateIndexStatement(String tablename, String indexname, String idx_fields[], boolean tk, boolean unique, boolean bitmap, boolean semi_colon) { return getCreateIndexStatement(null, tablename, indexname, idx_fields, tk, unique, bitmap, semi_colon); } public String getCreateIndexStatement(String schemaname, String tablename, String indexname, String idx_fields[], boolean tk, boolean unique, boolean bitmap, boolean semi_colon) { String cr_index=""; cr_index += "CREATE "; if (unique || ( tk && databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_SYBASE)) cr_index += "UNIQUE "; if (bitmap && databaseMeta.supportsBitmapIndex()) cr_index += "BITMAP "; cr_index += "INDEX "+databaseMeta.quoteField(indexname)+Const.CR+" "; cr_index += "ON "; // assume table has already been quoted (and possibly includes schema) cr_index += tablename; cr_index += Const.CR + "( "+Const.CR; for (int i=0;i<idx_fields.length;i++) { if (i>0) cr_index+=", "; else cr_index+=" "; cr_index += databaseMeta.quoteField(idx_fields[i])+Const.CR; } cr_index+=")"+Const.CR; if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE && databaseMeta.getIndexTablespace()!=null && databaseMeta.getIndexTablespace().length()>0) { cr_index+="TABLESPACE "+databaseMeta.quoteField(databaseMeta.getIndexTablespace()); } if (semi_colon) { cr_index+=";"+Const.CR; } return cr_index; } public String getCreateSequenceStatement(String sequence, long start_at, long increment_by, long max_value, boolean semi_colon) { return getCreateSequenceStatement(null, sequence, Long.toString(start_at), Long.toString(increment_by), Long.toString(max_value), semi_colon); } public String getCreateSequenceStatement(String sequence, String start_at, String increment_by, String max_value, boolean semi_colon) { return getCreateSequenceStatement(null, sequence, start_at, increment_by, max_value, semi_colon); } public String getCreateSequenceStatement(String schemaName, String sequence, long start_at, long increment_by, long max_value, boolean semi_colon) { return getCreateSequenceStatement(schemaName, sequence, Long.toString(start_at), Long.toString(increment_by), Long.toString(max_value), semi_colon); } public String getCreateSequenceStatement(String schemaName, String sequenceName, String start_at, String increment_by, String max_value, boolean semi_colon) { String cr_seq=""; if (Const.isEmpty(sequenceName)) return cr_seq; if (databaseMeta.supportsSequences()) { String schemaSequence = databaseMeta.getQuotedSchemaTableCombination(schemaName, sequenceName); cr_seq += "CREATE SEQUENCE "+schemaSequence+" "+Const.CR; // Works for both Oracle and PostgreSQL :-) cr_seq += "START WITH "+start_at+" "+Const.CR; cr_seq += "INCREMENT BY "+increment_by+" "+Const.CR; if (max_value != null) cr_seq += "MAXVALUE "+max_value+Const.CR; if (semi_colon) cr_seq+=";"+Const.CR; } return cr_seq; } public RowMetaInterface getQueryFields(String sql, boolean param, RowMetaInterface inform, Object[] data) throws KettleDatabaseException { RowMetaInterface fields; DBCache dbcache = DBCache.getInstance(); DBCacheEntry entry=null; // Check the cache first! if (dbcache!=null) { entry = new DBCacheEntry(databaseMeta.getName(), sql); fields = dbcache.get(entry); if (fields!=null) { return fields; } } if (connection==null) return null; // Cache test without connect. // No cache entry found // The new method of retrieving the query fields fails on Oracle because // they failed to implement the getMetaData method on a prepared statement. (!!!) // Even recent drivers like 10.2 fail because of it. // There might be other databases that don't support it (we have no knowledge of this at the time of writing). // If we discover other RDBMSs, we will create an interface for it. // For now, we just try to get the field layout on the re-bound in the exception block below. if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE || databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_H2 || databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_GENERIC) { fields=getQueryFieldsFallback(sql, param, inform, data); } else { // On with the regular program. PreparedStatement preparedStatement = null; try { preparedStatement = connection.prepareStatement(databaseMeta.stripCR(sql), ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); ResultSetMetaData rsmd = preparedStatement.getMetaData(); fields = getRowInfo(rsmd, false, false); } catch(Exception e) { fields = getQueryFieldsFallback(sql, param, inform, data); } finally { if (preparedStatement!=null) { try { preparedStatement.close(); } catch (SQLException e) { throw new KettleDatabaseException("Unable to close prepared statement after determining SQL layout", e); } } } } // Store in cache!! if (dbcache!=null && entry!=null) { if (fields!=null) { dbcache.put(entry, fields); } } return fields; } private RowMetaInterface getQueryFieldsFallback(String sql, boolean param, RowMetaInterface inform, Object[] data) throws KettleDatabaseException { RowMetaInterface fields; try { if (inform==null // Hack for MSSQL jtds 1.2 when using xxx NOT IN yyy we have to use a prepared statement (see BugID 3214) && databaseMeta.getDatabaseType()!=DatabaseMeta.TYPE_DATABASE_MSSQL ) { sel_stmt = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); if (databaseMeta.isFetchSizeSupported() && sel_stmt.getMaxRows()>=1) { if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL) { sel_stmt.setFetchSize(Integer.MIN_VALUE); } else { sel_stmt.setFetchSize(1); } } if (databaseMeta.supportsSetMaxRows()) sel_stmt.setMaxRows(1); ResultSet r=sel_stmt.executeQuery(databaseMeta.stripCR(sql)); fields = getRowInfo(r.getMetaData(), false, false); r.close(); sel_stmt.close(); sel_stmt=null; } else { PreparedStatement ps = connection.prepareStatement(databaseMeta.stripCR(sql)); if (param) { RowMetaInterface par = inform; if (par==null || par.isEmpty()) par = getParameterMetaData(ps); if (par==null || par.isEmpty()) par = getParameterMetaData(sql, inform, data); setValues(par, data, ps); } ResultSet r = ps.executeQuery(); fields=getRowInfo(ps.getMetaData(), false, false); r.close(); ps.close(); } } catch(Exception ex) { throw new KettleDatabaseException("Couldn't get field info from ["+sql+"]"+Const.CR, ex); } return fields; } public void closeQuery(ResultSet res) throws KettleDatabaseException { // close everything involved in the query! try { if (res!=null) res.close(); if (sel_stmt!=null) { sel_stmt.close(); sel_stmt=null; } if (pstmt!=null) { pstmt.close(); pstmt=null;} } catch(SQLException ex) { throw new KettleDatabaseException("Couldn't close query: resultset or prepared statements", ex); } } /** * Build the row using ResultSetMetaData rsmd * @param rm The resultset metadata to inquire * @param ignoreLength true if you want to ignore the length (workaround for MySQL bug/problem) * @param lazyConversion true if lazy conversion needs to be enabled where possible */ private RowMetaInterface getRowInfo(ResultSetMetaData rm, boolean ignoreLength, boolean lazyConversion) throws KettleDatabaseException { if (rm==null) return null; rowMeta = new RowMeta(); try { // TODO If we do lazy conversion, we need to find out about the encoding int fieldNr = 1; int nrcols=rm.getColumnCount(); for (int i=1;i<=nrcols;i++) { String name=new String(rm.getColumnName(i)); // Check the name, sometimes it's empty. if (Const.isEmpty(name) || Const.onlySpaces(name)) { name = "Field"+fieldNr; fieldNr++; } ValueMetaInterface v = getValueFromSQLType(name, rm, i, ignoreLength, lazyConversion); rowMeta.addValueMeta(v); } return rowMeta; } catch(SQLException ex) { throw new KettleDatabaseException("Error getting row information from database: ", ex); } } private ValueMetaInterface getValueFromSQLType(String name, ResultSetMetaData rm, int index, boolean ignoreLength, boolean lazyConversion) throws SQLException { int length=-1; int precision=-1; int valtype=ValueMetaInterface.TYPE_NONE; boolean isClob = false; int type = rm.getColumnType(index); switch(type) { case java.sql.Types.CHAR: case java.sql.Types.VARCHAR: case java.sql.Types.LONGVARCHAR: // Character Large Object valtype=ValueMetaInterface.TYPE_STRING; if (!ignoreLength) length=rm.getColumnDisplaySize(index); break; case java.sql.Types.CLOB: valtype=ValueMetaInterface.TYPE_STRING; length=DatabaseMeta.CLOB_LENGTH; isClob=true; break; case java.sql.Types.BIGINT: valtype=ValueMetaInterface.TYPE_INTEGER; precision=0; // Max 9.223.372.036.854.775.807 length=15; break; case java.sql.Types.INTEGER: valtype=ValueMetaInterface.TYPE_INTEGER; precision=0; // Max 2.147.483.647 length=9; break; case java.sql.Types.SMALLINT: valtype=ValueMetaInterface.TYPE_INTEGER; precision=0; // Max 32.767 length=4; break; case java.sql.Types.TINYINT: valtype=ValueMetaInterface.TYPE_INTEGER; precision=0; // Max 127 length=2; break; case java.sql.Types.DECIMAL: case java.sql.Types.DOUBLE: case java.sql.Types.FLOAT: case java.sql.Types.REAL: case java.sql.Types.NUMERIC: valtype=ValueMetaInterface.TYPE_NUMBER; length=rm.getPrecision(index); precision=rm.getScale(index); if (length >=126) length=-1; if (precision >=126) precision=-1; if (type==java.sql.Types.DOUBLE || type==java.sql.Types.FLOAT || type==java.sql.Types.REAL) { if (precision==0) { precision=-1; // precision is obviously incorrect if the type if Double/Float/Real } // If we're dealing with PostgreSQL and double precision types if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_POSTGRES && type==java.sql.Types.DOUBLE && precision==16 && length==16) { precision=-1; length=-1; } // MySQL: max resolution is double precision floating point (double) // The (12,31) that is given back is not correct if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL) { if (precision >= length) { precision=-1; length=-1; } } } else { if (precision==0 && length<18 && length>0) // Among others Oracle is affected here. { valtype=ValueMetaInterface.TYPE_INTEGER; } } if (length>18 || precision>18) valtype=ValueMetaInterface.TYPE_BIGNUMBER; if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE) { if (precision == 0 && length == 38 ) { valtype=ValueMetaInterface.TYPE_INTEGER; } if (precision<=0 && length<=0) // undefined size: NUMBER { valtype=ValueMetaInterface.TYPE_NUMBER; length=-1; precision=-1; } } break; case java.sql.Types.DATE: if (databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_TERADATA) { precision = 1; } case java.sql.Types.TIME: case java.sql.Types.TIMESTAMP: valtype=ValueMetaInterface.TYPE_DATE; if (databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_MYSQL) { String property = databaseMeta.getConnectionProperties().getProperty("yearIsDateType"); if (property != null && property.equalsIgnoreCase("false") && rm.getColumnTypeName(index).equalsIgnoreCase("YEAR")) { valtype = ValueMetaInterface.TYPE_INTEGER; precision = 0; length = 4; break; } } break; case java.sql.Types.BOOLEAN: case java.sql.Types.BIT: valtype=ValueMetaInterface.TYPE_BOOLEAN; break; case java.sql.Types.BINARY: case java.sql.Types.BLOB: case java.sql.Types.VARBINARY: case java.sql.Types.LONGVARBINARY: valtype=ValueMetaInterface.TYPE_BINARY; if (databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_DB2 && (2 * rm.getPrecision(index)) == rm.getColumnDisplaySize(index)) { // set the length for "CHAR(X) FOR BIT DATA" length = rm.getPrecision(index); } else if (databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_ORACLE && ( type==java.sql.Types.VARBINARY || type==java.sql.Types.LONGVARBINARY ) ) { // set the length for Oracle "RAW" or "LONGRAW" data types valtype = ValueMetaInterface.TYPE_STRING; length = rm.getColumnDisplaySize(index); } else { length=-1; } precision=-1; break; default: valtype=ValueMetaInterface.TYPE_STRING; precision=rm.getScale(index); break; } // Grab the comment as a description to the field as well. String comments=rm.getColumnLabel(index); // get & store more result set meta data for later use int originalColumnType=rm.getColumnType(index); String originalColumnTypeName=rm.getColumnTypeName(index); int originalPrecision=-1; if (!ignoreLength) rm.getPrecision(index); // Throws exception on MySQL int originalScale=rm.getScale(index); boolean originalAutoIncrement=rm.isAutoIncrement(index); int originalNullable=rm.isNullable(index); boolean originalSigned=rm.isSigned(index); ValueMetaInterface v=new ValueMeta(name, valtype); v.setLength(length); v.setPrecision(precision); v.setComments(comments); v.setLargeTextField(isClob); v.setOriginalColumnType(originalColumnType); v.setOriginalColumnTypeName(originalColumnTypeName); v.setOriginalPrecision(originalPrecision); v.setOriginalScale(originalScale); v.setOriginalAutoIncrement(originalAutoIncrement); v.setOriginalNullable(originalNullable); v.setOriginalSigned(originalSigned); // See if we need to enable lazy conversion... if (lazyConversion && valtype==ValueMetaInterface.TYPE_STRING) { v.setStorageType(ValueMetaInterface.STORAGE_TYPE_BINARY_STRING); // TODO set some encoding to go with this. // Also set the storage metadata. a copy of the parent, set to String too. ValueMetaInterface storageMetaData = v.clone(); storageMetaData.setType(ValueMetaInterface.TYPE_STRING); storageMetaData.setStorageType(ValueMetaInterface.STORAGE_TYPE_NORMAL); v.setStorageMetadata(storageMetaData); } return v; } public boolean absolute(ResultSet rs, int position) throws KettleDatabaseException { try { return rs.absolute(position); } catch(SQLException e) { throw new KettleDatabaseException("Unable to move resultset to position "+position, e); } } public boolean relative(ResultSet rs, int rows) throws KettleDatabaseException { try { return rs.relative(rows); } catch(SQLException e) { throw new KettleDatabaseException("Unable to move the resultset forward "+rows+" rows", e); } } public void afterLast(ResultSet rs) throws KettleDatabaseException { try { rs.afterLast(); } catch(SQLException e) { throw new KettleDatabaseException("Unable to move resultset to after the last position", e); } } public void first(ResultSet rs) throws KettleDatabaseException { try { rs.first(); } catch(SQLException e) { throw new KettleDatabaseException("Unable to move resultset to the first position", e); } } /** * Get a row from the resultset. Do not use lazy conversion * @param rs The resultset to get the row from * @return one row or null if no row was found on the resultset or if an error occurred. */ public Object[] getRow(ResultSet rs) throws KettleDatabaseException { return getRow(rs, false); } /** * Get a row from the resultset. * @param rs The resultset to get the row from * @param lazyConversion set to true if strings need to have lazy conversion enabled * @return one row or null if no row was found on the resultset or if an error occurred. */ public Object[] getRow(ResultSet rs, boolean lazyConversion) throws KettleDatabaseException { if (rowMeta==null) { ResultSetMetaData rsmd = null; try { rsmd = rs.getMetaData(); } catch(SQLException e) { throw new KettleDatabaseException("Unable to retrieve metadata from resultset", e); } rowMeta = getRowInfo(rsmd, false, lazyConversion); } return getRow(rs, null, rowMeta); } /** * Get a row from the resultset. * @param rs The resultset to get the row from * @return one row or null if no row was found on the resultset or if an error occurred. */ public Object[] getRow(ResultSet rs, ResultSetMetaData dummy, RowMetaInterface rowInfo) throws KettleDatabaseException { try { int nrcols=rowInfo.size(); Object[] data = RowDataUtil.allocateRowData(nrcols); if (rs.next()) { for (int i=0;i<nrcols;i++) { ValueMetaInterface val = rowInfo.getValueMeta(i); switch(val.getType()) { case ValueMetaInterface.TYPE_BOOLEAN : data[i] = Boolean.valueOf( rs.getBoolean(i+1) ); break; case ValueMetaInterface.TYPE_NUMBER : data[i] = new Double( rs.getDouble(i+1) ); break; case ValueMetaInterface.TYPE_BIGNUMBER : data[i] = rs.getBigDecimal(i+1); break; case ValueMetaInterface.TYPE_INTEGER : data[i] = Long.valueOf( rs.getLong(i+1) ); break; case ValueMetaInterface.TYPE_STRING : { if (val.isStorageBinaryString()) { data[i] = rs.getBytes(i+1); } else { data[i] = rs.getString(i+1); } } break; case ValueMetaInterface.TYPE_BINARY : { if (databaseMeta.supportsGetBlob()) { Blob blob = rs.getBlob(i+1); if (blob!=null) { data[i] = blob.getBytes(1L, (int)blob.length()); } else { data[i] = null; } } else { data[i] = rs.getBytes(i+1); } } break; case ValueMetaInterface.TYPE_DATE : if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_NEOVIEW && val.getOriginalColumnType()==java.sql.Types.TIME) { // Neoview can not handle getDate / getTimestamp for a Time column data[i] = rs.getTime(i+1); break; // Time is a subclass of java.util.Date, the default date will be 1970-01-01 } else if (val.getPrecision()!=1 && databaseMeta.supportsTimeStampToDateConversion()) { data[i] = rs.getTimestamp(i+1); break; // Timestamp extends java.util.Date } else { data[i] = rs.getDate(i+1); break; } default: break; } if (rs.wasNull()) data[i] = null; // null value, it's the default but we want it just to make sure we handle this case too. } } else { data=null; } return data; } catch(SQLException ex) { throw new KettleDatabaseException("Couldn't get row from result set", ex); } } public void printSQLException(SQLException ex) { log.logError(toString(), "==> SQLException: "); while (ex != null) { log.logError(toString(), "Message: " + ex.getMessage ()); log.logError(toString(), "SQLState: " + ex.getSQLState ()); log.logError(toString(), "ErrorCode: " + ex.getErrorCode ()); ex = ex.getNextException(); log.logError(toString(), ""); } } public void setLookup(String table, String codes[], String condition[], String gets[], String rename[], String orderby ) throws KettleDatabaseException { setLookup(table, codes, condition, gets, rename, orderby, false); } public void setLookup(String schema, String table, String codes[], String condition[], String gets[], String rename[], String orderby ) throws KettleDatabaseException { setLookup(schema, table, codes, condition, gets, rename, orderby, false); } public void setLookup(String tableName, String codes[], String condition[], String gets[], String rename[], String orderby, boolean checkForMultipleResults) throws KettleDatabaseException { setLookup(null, tableName, codes, condition, gets, rename, orderby, checkForMultipleResults); } // Lookup certain fields in a table public void setLookup(String schemaName, String tableName, String codes[], String condition[], String gets[], String rename[], String orderby, boolean checkForMultipleResults) throws KettleDatabaseException { String table = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName); String sql = "SELECT "; for (int i=0;i<gets.length;i++) { if (i!=0) sql += ", "; sql += databaseMeta.quoteField(gets[i]); if (rename!=null && rename[i]!=null && !gets[i].equalsIgnoreCase(rename[i])) { sql+=" AS "+databaseMeta.quoteField(rename[i]); } } sql += " FROM "+table+" WHERE "; for (int i=0;i<codes.length;i++) { if (i!=0) sql += " AND "; sql += databaseMeta.quoteField(codes[i]); if ("BETWEEN".equalsIgnoreCase(condition[i])) { sql+=" BETWEEN ? AND ? "; } else if ("IS NULL".equalsIgnoreCase(condition[i]) || "IS NOT NULL".equalsIgnoreCase(condition[i])) { sql+=" "+condition[i]+" "; } else { sql+=" "+condition[i]+" ? "; } } if (orderby!=null && orderby.length()!=0) { sql += " ORDER BY "+orderby; } try { log.logDetailed(toString(), "Setting preparedStatement to ["+sql+"]"); prepStatementLookup=connection.prepareStatement(databaseMeta.stripCR(sql)); if (!checkForMultipleResults && databaseMeta.supportsSetMaxRows()) { prepStatementLookup.setMaxRows(1); // alywas get only 1 line back! } } catch(SQLException ex) { throw new KettleDatabaseException("Unable to prepare statement for update ["+sql+"]", ex); } } public boolean prepareUpdate(String table, String codes[], String condition[], String sets[]) { return prepareUpdate(null, table, codes, condition, sets); } // Lookup certain fields in a table public boolean prepareUpdate(String schemaName, String tableName, String codes[], String condition[], String sets[]) { StringBuffer sql = new StringBuffer(128); String schemaTable = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName); sql.append("UPDATE ").append(schemaTable).append(Const.CR).append("SET "); for (int i=0;i<sets.length;i++) { if (i!=0) sql.append(", "); sql.append(databaseMeta.quoteField(sets[i])); sql.append(" = ?").append(Const.CR); } sql.append("WHERE "); for (int i=0;i<codes.length;i++) { if (i!=0) sql.append("AND "); sql.append(databaseMeta.quoteField(codes[i])); if ("BETWEEN".equalsIgnoreCase(condition[i])) { sql.append(" BETWEEN ? AND ? "); } else if ("IS NULL".equalsIgnoreCase(condition[i]) || "IS NOT NULL".equalsIgnoreCase(condition[i])) { sql.append(' ').append(condition[i]).append(' '); } else { sql.append(' ').append(condition[i]).append(" ? "); } } try { String s = sql.toString(); log.logDetailed(toString(), "Setting update preparedStatement to ["+s+"]"); prepStatementUpdate=connection.prepareStatement(databaseMeta.stripCR(s)); } catch(SQLException ex) { printSQLException(ex); return false; } return true; } /** * Prepare a delete statement by giving it the tablename, fields and conditions to work with. * @param table The table-name to delete in * @param codes * @param condition * @return true when everything went OK, false when something went wrong. */ public boolean prepareDelete(String table, String codes[], String condition[]) { return prepareDelete(null, table, codes, condition); } /** * Prepare a delete statement by giving it the tablename, fields and conditions to work with. * @param schemaName the schema-name to delete in * @param tableName The table-name to delete in * @param codes * @param condition * @return true when everything went OK, false when something went wrong. */ public boolean prepareDelete(String schemaName, String tableName, String codes[], String condition[]) { String sql; String table = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName); sql = "DELETE FROM "+table+Const.CR; sql+= "WHERE "; for (int i=0;i<codes.length;i++) { if (i!=0) sql += "AND "; sql += codes[i]; if ("BETWEEN".equalsIgnoreCase(condition[i])) { sql+=" BETWEEN ? AND ? "; } else if ("IS NULL".equalsIgnoreCase(condition[i]) || "IS NOT NULL".equalsIgnoreCase(condition[i])) { sql+=" "+condition[i]+" "; } else { sql+=" "+condition[i]+" ? "; } } try { log.logDetailed(toString(), "Setting update preparedStatement to ["+sql+"]"); prepStatementUpdate=connection.prepareStatement(databaseMeta.stripCR(sql)); } catch(SQLException ex) { printSQLException(ex); return false; } return true; } public void setProcLookup(String proc, String arg[], String argdir[], int argtype[], String returnvalue, int returntype) throws KettleDatabaseException { String sql; int pos=0; sql = "{ "; if (returnvalue!=null && returnvalue.length()!=0) { sql+="? = "; } sql+="call "+proc+" "; if (arg.length>0) sql+="("; for (int i=0;i<arg.length;i++) { if (i!=0) sql += ", "; sql += " ?"; } if (arg.length>0) sql+=")"; sql+="}"; try { log.logDetailed(toString(), "DBA setting callableStatement to ["+sql+"]"); cstmt=connection.prepareCall(sql); pos=1; if (!Const.isEmpty(returnvalue)) { switch(returntype) { case ValueMetaInterface.TYPE_NUMBER : cstmt.registerOutParameter(pos, java.sql.Types.DOUBLE); break; case ValueMetaInterface.TYPE_BIGNUMBER : cstmt.registerOutParameter(pos, java.sql.Types.DECIMAL); break; case ValueMetaInterface.TYPE_INTEGER : cstmt.registerOutParameter(pos, java.sql.Types.BIGINT); break; case ValueMetaInterface.TYPE_STRING : cstmt.registerOutParameter(pos, java.sql.Types.VARCHAR); break; case ValueMetaInterface.TYPE_DATE : cstmt.registerOutParameter(pos, java.sql.Types.TIMESTAMP); break; case ValueMetaInterface.TYPE_BOOLEAN : cstmt.registerOutParameter(pos, java.sql.Types.BOOLEAN); break; default: break; } pos++; } for (int i=0;i<arg.length;i++) { if (argdir[i].equalsIgnoreCase("OUT") || argdir[i].equalsIgnoreCase("INOUT")) { switch(argtype[i]) { case ValueMetaInterface.TYPE_NUMBER : cstmt.registerOutParameter(i+pos, java.sql.Types.DOUBLE); break; case ValueMetaInterface.TYPE_BIGNUMBER : cstmt.registerOutParameter(i+pos, java.sql.Types.DECIMAL); break; case ValueMetaInterface.TYPE_INTEGER : cstmt.registerOutParameter(i+pos, java.sql.Types.BIGINT); break; case ValueMetaInterface.TYPE_STRING : cstmt.registerOutParameter(i+pos, java.sql.Types.VARCHAR); break; case ValueMetaInterface.TYPE_DATE : cstmt.registerOutParameter(i+pos, java.sql.Types.TIMESTAMP); break; case ValueMetaInterface.TYPE_BOOLEAN : cstmt.registerOutParameter(i+pos, java.sql.Types.BOOLEAN); break; default: break; } } } } catch(SQLException ex) { throw new KettleDatabaseException("Unable to prepare database procedure call", ex); } } public Object[] getLookup() throws KettleDatabaseException { return getLookup(prepStatementLookup); } public Object[] getLookup(boolean failOnMultipleResults) throws KettleDatabaseException { return getLookup(prepStatementLookup, failOnMultipleResults); } public Object[] getLookup(PreparedStatement ps) throws KettleDatabaseException { return getLookup(ps, false); } public Object[] getLookup(PreparedStatement ps, boolean failOnMultipleResults) throws KettleDatabaseException { String debug = "start"; ResultSet res = null; try { debug = "pstmt.executeQuery()"; res = ps.executeQuery(); debug = "getRowInfo()"; rowMeta = getRowInfo(res.getMetaData(), false, false); debug = "getRow(res)"; Object[] ret = getRow(res); if (failOnMultipleResults) { if (ret != null && res.next()) { // if the previous row was null, there's no reason to try res.next() again. // on DB2 this will even cause an exception (because of the buggy DB2 JDBC driver). throw new KettleDatabaseException("Only 1 row was expected as a result of a lookup, and at least 2 were found!"); } } return ret; } catch(SQLException ex) { throw new KettleDatabaseException("Error looking up row in database ("+debug+")", ex); } finally { try { debug = "res.close()"; if (res!=null) res.close(); // close resultset! } catch(SQLException e) { throw new KettleDatabaseException("Unable to close resultset after looking up data", e); } } } public DatabaseMetaData getDatabaseMetaData() throws KettleDatabaseException { try { if (dbmd==null) dbmd = connection.getMetaData(); // Only get the metadata once! } catch(Exception e) { throw new KettleDatabaseException("Unable to get database metadata from this database connection", e); } return dbmd; } public String getDDL(String tablename, RowMetaInterface fields) throws KettleDatabaseException { return getDDL(tablename, fields, null, false, null, true); } public String getDDL(String tablename, RowMetaInterface fields, String tk, boolean use_autoinc, String pk) throws KettleDatabaseException { return getDDL(tablename, fields, tk, use_autoinc, pk, true); } public String getDDL(String tableName, RowMetaInterface fields, String tk, boolean use_autoinc, String pk, boolean semicolon) throws KettleDatabaseException { String retval; // First, check for reserved SQL in the input row r... databaseMeta.quoteReservedWords(fields); String quotedTk = tk != null ? databaseMeta.quoteField(tk) : null; if (checkTableExists(tableName)) { retval=getAlterTableStatement(tableName, fields, quotedTk, use_autoinc, pk, semicolon); } else { retval=getCreateTableStatement(tableName, fields, quotedTk, use_autoinc, pk, semicolon); } return retval; } /** * Generates SQL * @param tableName the table name or schema/table combination: this needs to be quoted properly in advance. * @param fields the fields * @param tk the name of the technical key field * @param use_autoinc true if we need to use auto-increment fields for a primary key * @param pk the name of the primary/technical key field * @param semicolon append semicolon to the statement * @return the SQL needed to create the specified table and fields. */ public String getCreateTableStatement(String tableName, RowMetaInterface fields, String tk, boolean use_autoinc, String pk, boolean semicolon) { String retval; retval = "CREATE TABLE "+tableName+Const.CR; retval+= "("+Const.CR; for (int i=0;i<fields.size();i++) { if (i>0) retval+=", "; else retval+=" "; ValueMetaInterface v=fields.getValueMeta(i); retval+=databaseMeta.getFieldDefinition(v, tk, pk, use_autoinc); } // At the end, before the closing of the statement, we might need to add some constraints... // Technical keys if (tk!=null) { if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_CACHE) { retval+=", PRIMARY KEY ("+tk+")"+Const.CR; } } // Primary keys if (pk!=null) { if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE) { retval+=", PRIMARY KEY ("+pk+")"+Const.CR; } } retval+= ")"+Const.CR; if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE && databaseMeta.getIndexTablespace()!=null && databaseMeta.getIndexTablespace().length()>0) { retval+="TABLESPACE "+databaseMeta.getDataTablespace(); } if (pk==null && tk==null && databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_NEOVIEW) { retval+="NO PARTITION"; // use this as a default when no pk/tk is there, otherwise you get an error } if (semicolon) retval+=";"; retval+=Const.CR; return retval; } public String getAlterTableStatement(String tableName, RowMetaInterface fields, String tk, boolean use_autoinc, String pk, boolean semicolon) throws KettleDatabaseException { String retval=""; // Get the fields that are in the table now: RowMetaInterface tabFields = getTableFields(tableName); // Don't forget to quote these as well... databaseMeta.quoteReservedWords(tabFields); // Find the missing fields RowMetaInterface missing = new RowMeta(); for (int i=0;i<fields.size();i++) { ValueMetaInterface v = fields.getValueMeta(i); // Not found? if (tabFields.searchValueMeta( v.getName() )==null ) { missing.addValueMeta(v); // nope --> Missing! } } if (missing.size()!=0) { for (int i=0;i<missing.size();i++) { ValueMetaInterface v=missing.getValueMeta(i); retval+=databaseMeta.getAddColumnStatement(tableName, v, tk, use_autoinc, pk, true); } } // Find the surplus fields RowMetaInterface surplus = new RowMeta(); for (int i=0;i<tabFields.size();i++) { ValueMetaInterface v = tabFields.getValueMeta(i); // Found in table, not in input ? if (fields.searchValueMeta( v.getName() )==null ) { surplus.addValueMeta(v); // yes --> surplus! } } if (surplus.size()!=0) { for (int i=0;i<surplus.size();i++) { ValueMetaInterface v=surplus.getValueMeta(i); retval+=databaseMeta.getDropColumnStatement(tableName, v, tk, use_autoinc, pk, true); } } // OK, see if there are fields for wich we need to modify the type... (length, precision) RowMetaInterface modify = new RowMeta(); for (int i=0;i<fields.size();i++) { ValueMetaInterface desiredField = fields.getValueMeta(i); ValueMetaInterface currentField = tabFields.searchValueMeta( desiredField.getName()); if (currentField!=null) { boolean mod = false; mod |= ( currentField.getLength() < desiredField.getLength() ) && desiredField.getLength()>0; mod |= ( currentField.getPrecision() < desiredField.getPrecision() ) && desiredField.getPrecision()>0; // Numeric values... mod |= ( currentField.getType() != desiredField.getType() ) && ( currentField.isNumber()^desiredField.isNumeric() ); // TODO: this is not an optimal way of finding out changes. // Perhaps we should just generate the data types strings for existing and new data type and see if anything changed. if (mod) { // System.out.println("Desired field: ["+desiredField.toStringMeta()+"], current field: ["+currentField.toStringMeta()+"]"); modify.addValueMeta(desiredField); } } } if (modify.size()>0) { for (int i=0;i<modify.size();i++) { ValueMetaInterface v=modify.getValueMeta(i); retval+=databaseMeta.getModifyColumnStatement(tableName, v, tk, use_autoinc, pk, true); } } return retval; } public void truncateTable(String tablename) throws KettleDatabaseException { if (Const.isEmpty(connectionGroup)) { execStatement(databaseMeta.getTruncateTableStatement(null, tablename)); } else { execStatement("DELETE FROM "+databaseMeta.quoteField(tablename)); } } public void truncateTable(String schema, String tablename) throws KettleDatabaseException { if (Const.isEmpty(connectionGroup)) { execStatement(databaseMeta.getTruncateTableStatement(schema, tablename)); } else { execStatement("DELETE FROM "+databaseMeta.getQuotedSchemaTableCombination(schema, tablename)); } } /** * Execute a query and return at most one row from the resultset * @param sql The SQL for the query * @return one Row with data or null if nothing was found. */ public RowMetaAndData getOneRow(String sql) throws KettleDatabaseException { ResultSet rs = openQuery(sql); if (rs!=null) { Object[] row = getRow(rs); // One row only; try { rs.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close resultset", e); } if (pstmt!=null) { try { pstmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement pstmt", e); } pstmt=null; } if (sel_stmt!=null) { try { sel_stmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement sel_stmt", e); } sel_stmt=null; } return new RowMetaAndData(rowMeta, row); } else { throw new KettleDatabaseException("error opening resultset for query: "+sql); } } public RowMeta getMetaFromRow( Object[] row, ResultSetMetaData md ) throws SQLException { RowMeta meta = new RowMeta(); for( int i=0; i<md.getColumnCount(); i++ ) { String name = md.getColumnName(i+1); ValueMetaInterface valueMeta = getValueFromSQLType( name, md, i+1, true, false ); meta.addValueMeta( valueMeta ); } return meta; } public RowMetaAndData getOneRow(String sql, RowMetaInterface param, Object[] data) throws KettleDatabaseException { ResultSet rs = openQuery(sql, param, data); if (rs!=null) { Object[] row = getRow(rs); // One value: a number; rowMeta=null; RowMeta tmpMeta = null; try { ResultSetMetaData md = rs.getMetaData(); tmpMeta = getMetaFromRow( row, md ); } catch (Exception e) { e.printStackTrace(); } finally { try { rs.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close resultset", e); } if (pstmt!=null) { try { pstmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement pstmt", e); } pstmt=null; } if (sel_stmt!=null) { try { sel_stmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement sel_stmt", e); } sel_stmt=null; } } return new RowMetaAndData(tmpMeta, row); } else { return null; } } public RowMetaInterface getParameterMetaData(PreparedStatement ps) { RowMetaInterface par = new RowMeta(); try { ParameterMetaData pmd = ps.getParameterMetaData(); for (int i=1;i<=pmd.getParameterCount();i++) { String name = "par"+i; int sqltype = pmd.getParameterType(i); int length = pmd.getPrecision(i); int precision = pmd.getScale(i); ValueMeta val; switch(sqltype) { case java.sql.Types.CHAR: case java.sql.Types.VARCHAR: val=new ValueMeta(name, ValueMetaInterface.TYPE_STRING); break; case java.sql.Types.BIGINT: case java.sql.Types.INTEGER: case java.sql.Types.NUMERIC: case java.sql.Types.SMALLINT: case java.sql.Types.TINYINT: val=new ValueMeta(name, ValueMetaInterface.TYPE_INTEGER); break; case java.sql.Types.DECIMAL: case java.sql.Types.DOUBLE: case java.sql.Types.FLOAT: case java.sql.Types.REAL: val=new ValueMeta(name, ValueMetaInterface.TYPE_NUMBER); break; case java.sql.Types.DATE: case java.sql.Types.TIME: case java.sql.Types.TIMESTAMP: val=new ValueMeta(name, ValueMetaInterface.TYPE_DATE); break; case java.sql.Types.BOOLEAN: case java.sql.Types.BIT: val=new ValueMeta(name, ValueMetaInterface.TYPE_BOOLEAN); break; default: val=new ValueMeta(name, ValueMetaInterface.TYPE_NONE); break; } if (val.isNumeric() && ( length>18 || precision>18) ) { val = new ValueMeta(name, ValueMetaInterface.TYPE_BIGNUMBER); } par.addValueMeta(val); } } // Oops: probably the database or JDBC doesn't support it. catch(AbstractMethodError e) { return null; } catch(SQLException e) { return null; } catch(Exception e) { return null; } return par; } public int countParameters(String sql) { int q=0; boolean quote_opened=false; boolean dquote_opened=false; for (int x=0;x<sql.length();x++) { char c = sql.charAt(x); switch(c) { case '\'': quote_opened= !quote_opened; break; case '"' : dquote_opened=!dquote_opened; break; case '?' : if (!quote_opened && !dquote_opened) q++; break; } } return q; } // Get the fields back from an SQL query public RowMetaInterface getParameterMetaData(String sql, RowMetaInterface inform, Object[] data) { // The database couldn't handle it: try manually! int q=countParameters(sql); RowMetaInterface par=new RowMeta(); if (inform!=null && q==inform.size()) { for (int i=0;i<q;i++) { ValueMetaInterface inf=inform.getValueMeta(i); ValueMetaInterface v = inf.clone(); par.addValueMeta(v); } } else { for (int i=0;i<q;i++) { ValueMetaInterface v = new ValueMeta("name"+i, ValueMetaInterface.TYPE_NUMBER); par.addValueMeta(v); } } return par; } public static final RowMetaInterface getTransLogrecordFields(boolean update, boolean use_batchid, boolean use_logfield) { RowMetaInterface r = new RowMeta(); ValueMetaInterface v; if (use_batchid && !update) { v=new ValueMeta("ID_BATCH", ValueMetaInterface.TYPE_INTEGER, 8, 0); r.addValueMeta(v); } if (!update) { v=new ValueMeta("TRANSNAME", ValueMetaInterface.TYPE_STRING, 255, 0); r.addValueMeta(v); } v=new ValueMeta("STATUS", ValueMetaInterface.TYPE_STRING , 15, 0); r.addValueMeta(v); v=new ValueMeta("LINES_READ", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v); v=new ValueMeta("LINES_WRITTEN", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v); v=new ValueMeta("LINES_UPDATED", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v); v=new ValueMeta("LINES_INPUT", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v); v=new ValueMeta("LINES_OUTPUT", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v); v=new ValueMeta("ERRORS", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v); v=new ValueMeta("STARTDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v); v=new ValueMeta("ENDDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v); v=new ValueMeta("LOGDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v); v=new ValueMeta("DEPDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v); v=new ValueMeta("REPLAYDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v); if (use_logfield) { v=new ValueMeta("LOG_FIELD", ValueMetaInterface.TYPE_STRING, DatabaseMeta.CLOB_LENGTH, 0); r.addValueMeta(v); } if (use_batchid && update) { v=new ValueMeta("ID_BATCH", ValueMetaInterface.TYPE_INTEGER, 8, 0); r.addValueMeta(v); } return r; } public static final RowMetaInterface getJobLogrecordFields(boolean update, boolean use_jobid, boolean use_logfield) { RowMetaInterface r = new RowMeta(); ValueMetaInterface v; if (use_jobid && !update) { v=new ValueMeta("ID_JOB", ValueMetaInterface.TYPE_INTEGER, 8, 0); r.addValueMeta(v); } if (!update) { v=new ValueMeta("JOBNAME", ValueMetaInterface.TYPE_STRING,255, 0); r.addValueMeta(v); } v=new ValueMeta("STATUS", ValueMetaInterface.TYPE_STRING, 15, 0); r.addValueMeta(v); v=new ValueMeta("LINES_READ", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v); v=new ValueMeta("LINES_WRITTEN", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v); v=new ValueMeta("LINES_UPDATED", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v); v=new ValueMeta("LINES_INPUT", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v); v=new ValueMeta("LINES_OUTPUT", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v); v=new ValueMeta("ERRORS", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v); v=new ValueMeta("STARTDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v); v=new ValueMeta("ENDDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v); v=new ValueMeta("LOGDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v); v=new ValueMeta("DEPDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v); v=new ValueMeta("REPLAYDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v); if (use_logfield) { v=new ValueMeta("LOG_FIELD", ValueMetaInterface.TYPE_STRING, DatabaseMeta.CLOB_LENGTH, 0); r.addValueMeta(v); } if (use_jobid && update) { v=new ValueMeta("ID_JOB", ValueMetaInterface.TYPE_INTEGER, 8, 0); r.addValueMeta(v); } return r; } public void writeLogRecord(String logtable, boolean use_id, long id, boolean job, String name, String status, long read, long written, long updated, long input, long output, long errors, java.util.Date startdate, java.util.Date enddate, java.util.Date logdate, java.util.Date depdate, java.util.Date replayDate, String log_string) throws KettleDatabaseException { boolean update = use_id && log_string != null && !status.equalsIgnoreCase("start"); RowMetaInterface rowMeta; if (job) { rowMeta = getJobLogrecordFields(update, use_id, !Const.isEmpty(log_string)); } else { rowMeta = getTransLogrecordFields(update, use_id, !Const.isEmpty(log_string)); } if (update) { String sql = "UPDATE " + logtable + " SET "; for (int i = 0; i < rowMeta.size() - 1; i++) // Without ID_JOB or ID_BATCH { ValueMetaInterface valueMeta = rowMeta.getValueMeta(i); if (i > 0) { sql += ", "; } sql += databaseMeta.quoteField(valueMeta.getName()) + "=? "; } sql += "WHERE "; if (job) { sql += databaseMeta.quoteField("ID_JOB") + "=? "; } else { sql += databaseMeta.quoteField("ID_BATCH") + "=? "; } Object[] data = new Object[] { status, Long.valueOf(read), Long.valueOf(written), Long.valueOf(input), Long.valueOf(output), Long.valueOf(updated), Long.valueOf(errors), startdate, enddate, logdate, depdate, replayDate, log_string, Long.valueOf(id), }; execStatement(sql, rowMeta, data); } else { String sql = "INSERT INTO " + logtable + " ( "; for (int i = 0; i < rowMeta.size(); i++) { ValueMetaInterface valueMeta = rowMeta.getValueMeta(i); if (i > 0) sql += ", "; sql += databaseMeta.quoteField(valueMeta.getName()); } sql += ") VALUES("; for (int i = 0; i < rowMeta.size(); i++) { if (i > 0) sql += ", "; sql += "?"; } sql += ")"; try { pstmt = connection.prepareStatement(databaseMeta.stripCR(sql)); List<Object> data = new ArrayList<Object>(); if (job) { if (use_id) { data.add(Long.valueOf(id)); } data.add(name); } else { if (use_id) { data.add(Long.valueOf(id)); } data.add(name); } data.add(status); data.add(Long.valueOf(read)); data.add(Long.valueOf(written)); data.add(Long.valueOf(updated)); data.add(Long.valueOf(input)); data.add(Long.valueOf(output)); data.add(Long.valueOf(errors)); data.add(startdate); data.add(enddate); data.add(logdate); data.add(depdate); data.add(replayDate); if (!Const.isEmpty(log_string)) { data.add(log_string); } setValues(rowMeta, data.toArray(new Object[data.size()])); pstmt.executeUpdate(); pstmt.close(); pstmt = null; } catch (SQLException ex) { throw new KettleDatabaseException("Unable to write log record to log table " + logtable, ex); } } } public static final RowMetaInterface getStepPerformanceLogrecordFields() { RowMetaInterface r = new RowMeta(); ValueMetaInterface v; v=new ValueMeta("ID_BATCH", ValueMetaInterface.TYPE_INTEGER, 8, 0); r.addValueMeta(v); v=new ValueMeta("SEQ_NR", ValueMetaInterface.TYPE_INTEGER, 8, 0); r.addValueMeta(v); v=new ValueMeta("LOGDATE", ValueMetaInterface.TYPE_DATE ); r.addValueMeta(v); v=new ValueMeta("TRANSNAME", ValueMetaInterface.TYPE_STRING ,255, 0); r.addValueMeta(v); v=new ValueMeta("STEPNAME", ValueMetaInterface.TYPE_STRING ,255, 0); r.addValueMeta(v); v=new ValueMeta("STEP_COPY", ValueMetaInterface.TYPE_INTEGER, 3, 0); r.addValueMeta(v); v=new ValueMeta("LINES_READ", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v); v=new ValueMeta("LINES_WRITTEN", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v); v=new ValueMeta("LINES_UPDATED", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v); v=new ValueMeta("LINES_INPUT", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v); v=new ValueMeta("LINES_OUTPUT", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v); v=new ValueMeta("LINES_REJECTED", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v); v=new ValueMeta("ERRORS", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v); v=new ValueMeta("INPUT_BUFFER_ROWS", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v); v=new ValueMeta("OUTPUT_BUFFER_ROWS", ValueMetaInterface.TYPE_INTEGER, 10, 0); r.addValueMeta(v); return r; } public Object[] getLastLogDate( String logtable, String name, boolean job, String status ) throws KettleDatabaseException { Object[] row = null; String jobtrans = job?databaseMeta.quoteField("JOBNAME"):databaseMeta.quoteField("TRANSNAME"); String sql = ""; sql+=" SELECT "+databaseMeta.quoteField("ENDDATE")+", "+databaseMeta.quoteField("DEPDATE")+", "+databaseMeta.quoteField("STARTDATE"); sql+=" FROM "+logtable; sql+=" WHERE "+databaseMeta.quoteField("ERRORS")+" = 0"; sql+=" AND "+databaseMeta.quoteField("STATUS")+" = 'end'"; sql+=" AND "+jobtrans+" = ?"; sql+=" ORDER BY "+databaseMeta.quoteField("LOGDATE")+" DESC, "+databaseMeta.quoteField("ENDDATE")+" DESC"; try { pstmt = connection.prepareStatement(databaseMeta.stripCR(sql)); RowMetaInterface r = new RowMeta(); r.addValueMeta( new ValueMeta("TRANSNAME", ValueMetaInterface.TYPE_STRING)); setValues(r, new Object[] { name }); ResultSet res = pstmt.executeQuery(); if (res!=null) { rowMeta = getRowInfo(res.getMetaData(), false, false); row = getRow(res); res.close(); } pstmt.close(); pstmt=null; } catch(SQLException ex) { throw new KettleDatabaseException("Unable to obtain last logdate from table "+logtable, ex); } return row; } public synchronized Long getNextValue(Hashtable<String,Counter> counters, String tableName, String val_key) throws KettleDatabaseException { return getNextValue(counters, null, tableName, val_key); } public synchronized Long getNextValue(Hashtable<String,Counter> counters, String schemaName, String tableName, String val_key) throws KettleDatabaseException { Long nextValue = null; String schemaTable = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName); String lookup = schemaTable+"."+databaseMeta.quoteField(val_key); // Try to find the previous sequence value... Counter counter = null; if (counters!=null) counter=counters.get(lookup); if (counter==null) { RowMetaAndData rmad = getOneRow("SELECT MAX("+databaseMeta.quoteField(val_key)+") FROM "+schemaTable); if (rmad!=null) { long previous; try { Long tmp = rmad.getRowMeta().getInteger(rmad.getData(), 0); // A "select max(x)" on a table with no matching rows will return null. if ( tmp != null ) previous = tmp.longValue(); else previous = 0L; } catch (KettleValueException e) { throw new KettleDatabaseException("Error getting the first long value from the max value returned from table : "+schemaTable); } counter = new Counter(previous+1, 1); nextValue = Long.valueOf( counter.next() ); if (counters!=null) counters.put(lookup, counter); } else { throw new KettleDatabaseException("Couldn't find maximum key value from table "+schemaTable); } } else { nextValue = Long.valueOf( counter.next() ); } return nextValue; } public String toString() { if (databaseMeta!=null) return databaseMeta.getName(); else return "-"; } public boolean isSystemTable(String table_name) { if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MSSQL) { if ( table_name.startsWith("sys")) return true; if ( table_name.equals("dtproperties")) return true; } else if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_GUPTA) { if ( table_name.startsWith("SYS")) return true; } return false; } /** Reads the result of an SQL query into an ArrayList * * @param sql The SQL to launch * @param limit <=0 means unlimited, otherwise this specifies the maximum number of rows read. * @return An ArrayList of rows. * @throws KettleDatabaseException if something goes wrong. */ public List<Object[]> getRows(String sql, int limit) throws KettleDatabaseException { return getRows(sql, limit, null); } /** Reads the result of an SQL query into an ArrayList * * @param sql The SQL to launch * @param limit <=0 means unlimited, otherwise this specifies the maximum number of rows read. * @param monitor The progress monitor to update while getting the rows. * @return An ArrayList of rows. * @throws KettleDatabaseException if something goes wrong. */ public List<Object[]> getRows(String sql, int limit, ProgressMonitorListener monitor) throws KettleDatabaseException { if (monitor!=null) monitor.setTaskName("Opening query..."); ResultSet rset = openQuery(sql); return getRows(rset, limit, monitor); } /** Reads the result of a ResultSet into an ArrayList * * @param rset the ResultSet to read out * @param limit <=0 means unlimited, otherwise this specifies the maximum number of rows read. * @param monitor The progress monitor to update while getting the rows. * @return An ArrayList of rows. * @throws KettleDatabaseException if something goes wrong. */ public List<Object[]> getRows(ResultSet rset, int limit, ProgressMonitorListener monitor) throws KettleDatabaseException { try { List<Object[]> result = new ArrayList<Object[]>(); boolean stop=false; int i=0; if (rset!=null) { if (monitor!=null && limit>0) monitor.beginTask("Reading rows...", limit); while ((limit<=0 || i<limit) && !stop) { Object[] row = getRow(rset); if (row!=null) { result.add(row); i++; } else { stop=true; } if (monitor!=null && limit>0) monitor.worked(1); } closeQuery(rset); if (monitor!=null) monitor.done(); } return result; } catch(Exception e) { throw new KettleDatabaseException("Unable to get list of rows from ResultSet : ", e); } } public List<Object[]> getFirstRows(String table_name, int limit) throws KettleDatabaseException { return getFirstRows(table_name, limit, null); } /** * Get the first rows from a table (for preview) * @param table_name The table name (or schema/table combination): this needs to be quoted properly * @param limit limit <=0 means unlimited, otherwise this specifies the maximum number of rows read. * @param monitor The progress monitor to update while getting the rows. * @return An ArrayList of rows. * @throws KettleDatabaseException in case something goes wrong */ public List<Object[]> getFirstRows(String table_name, int limit, ProgressMonitorListener monitor) throws KettleDatabaseException { String sql = "SELECT"; if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_NEOVIEW) { sql+=" [FIRST " + limit +"]"; } sql += " * FROM "+table_name; if (limit>0) { sql+=databaseMeta.getLimitClause(limit); } return getRows(sql, limit, monitor); } public RowMetaInterface getReturnRowMeta() { return rowMeta; } public String[] getTableTypes() throws KettleDatabaseException { try { ArrayList<String> types = new ArrayList<String>(); ResultSet rstt = getDatabaseMetaData().getTableTypes(); while(rstt.next()) { String ttype = rstt.getString("TABLE_TYPE"); types.add(ttype); } return types.toArray(new String[types.size()]); } catch(SQLException e) { throw new KettleDatabaseException("Unable to get table types from database!", e); } } public String[] getTablenames() throws KettleDatabaseException { return getTablenames(false); } public String[] getTablenames(boolean includeSchema) throws KettleDatabaseException { String schemaname = null; if (databaseMeta.useSchemaNameForTableList()) schemaname = databaseMeta.getUsername().toUpperCase(); List<String> names = new ArrayList<String>(); ResultSet alltables=null; try { alltables = getDatabaseMetaData().getTables(null, schemaname, null, databaseMeta.getTableTypes() ); while (alltables.next()) { String table = alltables.getString("TABLE_NAME"); String schema = alltables.getString("TABLE_SCHEM"); if (Const.isEmpty(schema)) schema = alltables.getString("TABLE_CAT"); // retry for the catalog. String schemaTable; if (includeSchema) schemaTable = databaseMeta.getQuotedSchemaTableCombination(schema, table); else schemaTable = table; if (log.isRowLevel()) log.logRowlevel(toString(), "got table from meta-data: "+schemaTable); names.add(schemaTable); } } catch(SQLException e) { log.logError(toString(), "Error getting tablenames from schema ["+schemaname+"]"); } finally { try { if (alltables!=null) alltables.close(); } catch(SQLException e) { throw new KettleDatabaseException("Error closing resultset after getting views from schema ["+schemaname+"]", e); } } log.logDetailed(toString(), "read :"+names.size()+" table names from db meta-data."); return names.toArray(new String[names.size()]); } public String[] getViews() throws KettleDatabaseException { return getViews(false); } public String[] getViews(boolean includeSchema) throws KettleDatabaseException { if (!databaseMeta.supportsViews()) return new String[] {}; String schemaname = null; if (databaseMeta.useSchemaNameForTableList()) schemaname=databaseMeta.getUsername().toUpperCase(); ArrayList<String> names = new ArrayList<String>(); ResultSet alltables=null; try { alltables = dbmd.getTables(null, schemaname, null, databaseMeta.getViewTypes() ); while (alltables.next()) { String table = alltables.getString("TABLE_NAME"); String schema = alltables.getString("TABLE_SCHEM"); if (Const.isEmpty(schema)) schema = alltables.getString("TABLE_CAT"); // retry for the catalog. String schemaTable; if (includeSchema) schemaTable = databaseMeta.getQuotedSchemaTableCombination(schema, table); else schemaTable = table; if (log.isRowLevel()) log.logRowlevel(toString(), "got view from meta-data: "+schemaTable); names.add(schemaTable); } } catch(SQLException e) { throw new KettleDatabaseException("Error getting views from schema ["+schemaname+"]", e); } finally { try { if (alltables!=null) alltables.close(); } catch(SQLException e) { throw new KettleDatabaseException("Error closing resultset after getting views from schema ["+schemaname+"]", e); } } log.logDetailed(toString(), "read :"+names.size()+" views from db meta-data."); return names.toArray(new String[names.size()]); } public String[] getSynonyms() throws KettleDatabaseException { return getViews(false); } public String[] getSynonyms(boolean includeSchema) throws KettleDatabaseException { if (!databaseMeta.supportsSynonyms()) return new String[] {}; String schemaname = null; if (databaseMeta.useSchemaNameForTableList()) schemaname=databaseMeta.getUsername().toUpperCase(); ArrayList<String> names = new ArrayList<String>(); ResultSet alltables=null; try { alltables = dbmd.getTables(null, schemaname, null, databaseMeta.getSynonymTypes() ); while (alltables.next()) { String table = alltables.getString("TABLE_NAME"); String schema = alltables.getString("TABLE_SCHEM"); if (Const.isEmpty(schema)) schema = alltables.getString("TABLE_CAT"); // retry for the catalog. String schemaTable; if (includeSchema) schemaTable = databaseMeta.getQuotedSchemaTableCombination(schema, table); else schemaTable = table; if (log.isRowLevel()) log.logRowlevel(toString(), "got view from meta-data: "+schemaTable); names.add(schemaTable); } } catch(SQLException e) { throw new KettleDatabaseException("Error getting synonyms from schema ["+schemaname+"]", e); } finally { try { if (alltables!=null) alltables.close(); } catch(SQLException e) { throw new KettleDatabaseException("Error closing resultset after getting synonyms from schema ["+schemaname+"]", e); } } log.logDetailed(toString(), "read :"+names.size()+" views from db meta-data."); return names.toArray(new String[names.size()]); } public String[] getProcedures() throws KettleDatabaseException { String sql = databaseMeta.getSQLListOfProcedures(); if (sql!=null) { //System.out.println("SQL= "+sql); List<Object[]> procs = getRows(sql, 1000); //System.out.println("Found "+procs.size()+" rows"); String[] str = new String[procs.size()]; for (int i=0;i<procs.size();i++) { str[i] = ((Object[])procs.get(i))[0].toString(); } return str; } else { ResultSet rs = null; try { DatabaseMetaData dbmd = getDatabaseMetaData(); rs = dbmd.getProcedures(null, null, null); List<Object[]> rows = getRows(rs, 0, null); String result[] = new String[rows.size()]; for (int i=0;i<rows.size();i++) { Object[] row = (Object[])rows.get(i); String procCatalog = rowMeta.getString(row, "PROCEDURE_CAT", null); String procSchema = rowMeta.getString(row, "PROCEDURE_SCHEMA", null); String procName = rowMeta.getString(row, "PROCEDURE_NAME", ""); String name = ""; if (procCatalog!=null) name+=procCatalog+"."; else if (procSchema!=null) name+=procSchema+"."; name+=procName; result[i] = name; } return result; } catch(Exception e) { throw new KettleDatabaseException("Unable to get list of procedures from database meta-data: ", e); } finally { if (rs!=null) try { rs.close(); } catch(Exception e) {} } } } public boolean isAutoCommit() { return commitsize<=0; } /** * @return Returns the databaseMeta. */ public DatabaseMeta getDatabaseMeta() { return databaseMeta; } /** * Lock a tables in the database for write operations * @param tableNames The tables to lock * @throws KettleDatabaseException */ public void lockTables(String tableNames[]) throws KettleDatabaseException { if (Const.isEmpty(tableNames)) return; // Quote table names too... String[] quotedTableNames = new String[tableNames.length]; for (int i=0;i<tableNames.length;i++) quotedTableNames[i] = databaseMeta.quoteField(tableNames[i]); // Get the SQL to lock the (quoted) tables String sql = databaseMeta.getSQLLockTables(quotedTableNames); if (sql!=null) { execStatements(sql); } } /** * Unlock certain tables in the database for write operations * @param tableNames The tables to unlock * @throws KettleDatabaseException */ public void unlockTables(String tableNames[]) throws KettleDatabaseException { if (Const.isEmpty(tableNames)) return; // Quote table names too... String[] quotedTableNames = new String[tableNames.length]; for (int i=0;i<tableNames.length;i++) quotedTableNames[i] = databaseMeta.quoteField(tableNames[i]); // Get the SQL to unlock the (quoted) tables String sql = databaseMeta.getSQLUnlockTables(quotedTableNames); if (sql!=null) { execStatement(sql); } } /** * @return the opened */ public int getOpened() { return opened; } /** * @param opened the opened to set */ public void setOpened(int opened) { this.opened = opened; } /** * @return the connectionGroup */ public String getConnectionGroup() { return connectionGroup; } /** * @param connectionGroup the connectionGroup to set */ public void setConnectionGroup(String connectionGroup) { this.connectionGroup = connectionGroup; } /** * @return the partitionId */ public String getPartitionId() { return partitionId; } /** * @param partitionId the partitionId to set */ public void setPartitionId(String partitionId) { this.partitionId = partitionId; } /** * @return the copy */ public int getCopy() { return copy; } /** * @param copy the copy to set */ public void setCopy(int copy) { this.copy = copy; } public void copyVariablesFrom(VariableSpace space) { variables.copyVariablesFrom(space); } public String environmentSubstitute(String aString) { return variables.environmentSubstitute(aString); } public String[] environmentSubstitute(String aString[]) { return variables.environmentSubstitute(aString); } public VariableSpace getParentVariableSpace() { return variables.getParentVariableSpace(); } public void setParentVariableSpace(VariableSpace parent) { variables.setParentVariableSpace(parent); } public String getVariable(String variableName, String defaultValue) { return variables.getVariable(variableName, defaultValue); } public String getVariable(String variableName) { return variables.getVariable(variableName); } public boolean getBooleanValueOfVariable(String variableName, boolean defaultValue) { if (!Const.isEmpty(variableName)) { String value = environmentSubstitute(variableName); if (!Const.isEmpty(value)) { return ValueMeta.convertStringToBoolean(value); } } return defaultValue; } public void initializeVariablesFrom(VariableSpace parent) { variables.initializeVariablesFrom(parent); } public String[] listVariables() { return variables.listVariables(); } public void setVariable(String variableName, String variableValue) { variables.setVariable(variableName, variableValue); } public void shareVariablesWith(VariableSpace space) { variables = space; // Also share the variables with the meta data object // Make sure it's not the databaseMeta object itself. We would get an infinite loop in that case. if (space!=databaseMeta) databaseMeta.shareVariablesWith(space); } public void injectVariables(Map<String,String> prop) { variables.injectVariables(prop); } public RowMetaAndData callProcedure(String arg[], String argdir[], int argtype[], String resultname, int resulttype) throws KettleDatabaseException { RowMetaAndData ret; try { cstmt.execute(); ret = new RowMetaAndData(); int pos = 1; if (resultname != null && resultname.length() != 0) { ValueMeta vMeta = new ValueMeta(resultname, resulttype); Object v =null; switch (resulttype) { case ValueMetaInterface.TYPE_BOOLEAN: v=Boolean.valueOf(cstmt.getBoolean(pos)); break; case ValueMetaInterface.TYPE_NUMBER: v=new Double(cstmt.getDouble(pos)); break; case ValueMetaInterface.TYPE_BIGNUMBER: v=cstmt.getBigDecimal(pos); break; case ValueMetaInterface.TYPE_INTEGER: v=Long.valueOf(cstmt.getLong(pos)); break; case ValueMetaInterface.TYPE_STRING: v=cstmt.getString(pos); break; case ValueMetaInterface.TYPE_DATE: v=cstmt.getDate(pos); break; } ret.addValue(vMeta, v); pos++; } for (int i = 0; i < arg.length; i++) { if (argdir[i].equalsIgnoreCase("OUT") || argdir[i].equalsIgnoreCase("INOUT")) { ValueMeta vMeta = new ValueMeta(arg[i], argtype[i]); Object v=null; switch (argtype[i]) { case ValueMetaInterface.TYPE_BOOLEAN: v=Boolean.valueOf(cstmt.getBoolean(pos + i)); break; case ValueMetaInterface.TYPE_NUMBER: v=new Double(cstmt.getDouble(pos + i)); break; case ValueMetaInterface.TYPE_BIGNUMBER: v=cstmt.getBigDecimal(pos + i); break; case ValueMetaInterface.TYPE_INTEGER: v=Long.valueOf(cstmt.getLong(pos + i)); break; case ValueMetaInterface.TYPE_STRING: v=cstmt.getString(pos + i); break; case ValueMetaInterface.TYPE_DATE: v=cstmt.getTimestamp(pos + i); break; } ret.addValue(vMeta, v); } } return ret; } catch (SQLException ex) { throw new KettleDatabaseException("Unable to call procedure", ex); } } /** * Return SQL CREATION statement for a Table * @param tableName The table to create * @throws KettleDatabaseException */ public String getDDLCreationTable(String tableName, RowMetaInterface fields) throws KettleDatabaseException { String retval; // First, check for reserved SQL in the input row r... databaseMeta.quoteReservedWords(fields); String quotedTk=databaseMeta.quoteField(null); retval=getCreateTableStatement(tableName, fields, quotedTk, false, null, true); return retval; } /** * Return SQL TRUNCATE statement for a Table * @param schema The schema * @param tableName The table to create * @throws KettleDatabaseException */ public String getDDLTruncateTable(String schema, String tablename) throws KettleDatabaseException { if (Const.isEmpty(connectionGroup)) { return(databaseMeta.getTruncateTableStatement(schema, tablename)); } else { return("DELETE FROM "+databaseMeta.getQuotedSchemaTableCombination(schema, tablename)); } } /** * Return SQL statement (INSERT INTO TableName ... * @param schemaName tableName The schema * @param tableName * @param fields * @param dateFormat date format of field * @throws KettleDatabaseException */ public String getSQLOutput(String schemaName, String tableName, RowMetaInterface fields, Object[] r,String dateFormat) throws KettleDatabaseException { StringBuffer ins=new StringBuffer(128); try{ String schemaTable = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName); ins.append("INSERT INTO ").append(schemaTable).append('('); // now add the names in the row: for (int i=0;i<fields.size();i++) { if (i>0) ins.append(", "); String name = fields.getValueMeta(i).getName(); ins.append(databaseMeta.quoteField(name)); } ins.append(") VALUES ("); // new add values ... for (int i=0;i<fields.size();i++) { if (i>0) ins.append(","); { if (fields.getValueMeta(i).getType()==ValueMeta.TYPE_STRING) ins.append("'" + fields.getString(r,i) + "'") ; else if (fields.getValueMeta(i).getType()==ValueMeta.TYPE_DATE) { if (Const.isEmpty(dateFormat)) ins.append("'" + fields.getString(r,i)+ "'") ; else { try { java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(dateFormat); ins.append("'" + formatter.format(fields.getDate(r,i))+ "'") ; } catch(Exception e) { throw new KettleDatabaseException("Error : ", e); } } } else { ins.append( fields.getString(r,i)) ; } } } ins.append(')'); }catch (Exception e) { throw new KettleDatabaseException(e); } return ins.toString(); } public Savepoint setSavepoint() throws KettleDatabaseException { try { return connection.setSavepoint(); } catch (SQLException e) { throw new KettleDatabaseException(Messages.getString("Database.Exception.UnableToSetSavepoint"), e); } } public Savepoint setSavepoint(String savePointName) throws KettleDatabaseException { try { return connection.setSavepoint(savePointName); } catch (SQLException e) { throw new KettleDatabaseException(Messages.getString("Database.Exception.UnableToSetSavepointName", savePointName), e); } } public void releaseSavepoint(Savepoint savepoint) throws KettleDatabaseException { try { connection.releaseSavepoint(savepoint); } catch (SQLException e) { throw new KettleDatabaseException(Messages.getString("Database.Exception.UnableToReleaseSavepoint"), e); } } public void rollback(Savepoint savepoint) throws KettleDatabaseException { try { connection.rollback(savepoint); } catch (SQLException e) { throw new KettleDatabaseException(Messages.getString("Database.Exception.UnableToRollbackToSavepoint"), e); } } }
package org.opencms.ui.editors; import org.opencms.file.CmsObject; import org.opencms.file.CmsResource; import org.opencms.file.types.I_CmsResourceType; import org.opencms.i18n.CmsEncoder; import org.opencms.main.CmsException; import org.opencms.main.CmsLog; import org.opencms.main.OpenCms; import org.opencms.ui.A_CmsUI; import org.opencms.ui.CmsVaadinUtils; import org.opencms.ui.apps.I_CmsAppUIContext; import org.opencms.ui.apps.Messages; import org.opencms.ui.components.CmsBrowserFrame; import org.opencms.ui.components.CmsConfirmationDialog; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.logging.Log; import com.vaadin.navigator.Navigator; import com.vaadin.navigator.ViewChangeListener; import com.vaadin.server.ExternalResource; /** * Class to extended by frame based editors.<p> */ public abstract class A_CmsFrameEditor implements I_CmsEditor, ViewChangeListener { /** Log instance for this class. */ private static final Log LOG = CmsLog.getLog(A_CmsFrameEditor.class); /** The serial version id. */ private static final long serialVersionUID = 6944345583913510988L; /** The editor state. */ protected CmsEditorStateExtension m_editorState; /** Flag indicating a view change. */ boolean m_leaving; /** The currently edited resource. */ CmsResource m_resource; /** The frame component. */ private CmsBrowserFrame m_frame; /** * @see com.vaadin.navigator.ViewChangeListener#afterViewChange(com.vaadin.navigator.ViewChangeListener.ViewChangeEvent) */ public void afterViewChange(ViewChangeEvent event) { // nothing to do } /** * @see com.vaadin.navigator.ViewChangeListener#beforeViewChange(com.vaadin.navigator.ViewChangeListener.ViewChangeEvent) */ public boolean beforeViewChange(final ViewChangeEvent event) { if (!m_leaving && m_editorState.hasChanges()) { final String target = event.getViewName(); CmsConfirmationDialog.show( CmsVaadinUtils.getMessageText(Messages.GUI_EDITOR_CLOSE_CAPTION_0), CmsVaadinUtils.getMessageText(Messages.GUI_EDITOR_CLOSE_TEXT_0), new Runnable() { public void run() { leaveEditor(event.getNavigator(), target); } }); return false; } else if (!m_leaving) { tryUnlock(); } return true; } /** * @see org.opencms.ui.editors.I_CmsEditor#initUI(org.opencms.ui.apps.I_CmsAppUIContext, org.opencms.file.CmsResource, java.lang.String, java.util.Map) */ public void initUI(I_CmsAppUIContext context, CmsResource resource, String backLink, Map<String, String> params) { m_resource = resource; CmsObject cms = A_CmsUI.getCmsObject(); String sitepath = m_resource != null ? cms.getSitePath(m_resource) : ""; String link = OpenCms.getLinkManager().substituteLinkForRootPath(cms, getEditorUri()); m_frame = new CmsBrowserFrame(); m_frame.setDescription("Editor"); m_frame.setName("edit"); link += "?resource=" + sitepath + "&backlink=" + backLink; if (params != null) { for (Entry<String, String> entry : params.entrySet()) { try { link += "&" + entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), CmsEncoder.ENCODING_UTF_8); } catch (UnsupportedEncodingException e) { LOG.error(e.getLocalizedMessage(), e); } } } m_frame.setSource(new ExternalResource(link)); m_frame.setSizeFull(); context.showInfoArea(false); context.hideToolbar(); m_frame.addStyleName("o-editor-frame"); context.setAppContent(m_frame); context.setAppTitle( CmsVaadinUtils.getMessageText( Messages.GUI_CONTENT_EDITOR_TITLE_2, resource == null ? "new resource" : resource.getName(), CmsResource.getParentFolder(sitepath))); m_editorState = new CmsEditorStateExtension(m_frame); } /** * @see org.opencms.ui.editors.I_CmsEditor#matchesResource(org.opencms.file.CmsResource, boolean) */ public boolean matchesResource(CmsResource resource, boolean plainText) { I_CmsResourceType type = OpenCms.getResourceManager().getResourceType(resource); return matchesType(type, plainText); } /** * Returns the editor URI.<p> * * @return the editor URI */ protected abstract String getEditorUri(); /** * Leaves the editor view.<p> * * @param navigator the navigator instance * @param target the target view */ void leaveEditor(Navigator navigator, String target) { m_leaving = true; tryUnlock(); navigator.navigateTo(target); } /** * Tries to unlock the current resource.<p> */ private void tryUnlock() { if (m_resource != null) { try { A_CmsUI.getCmsObject().unlockResource(m_resource); } catch (CmsException e) { LOG.debug("Unlocking resource " + m_resource.getRootPath() + " failed", e); } } } }
package com.edinarobotics.zed.vision; import com.sun.squawk.util.Arrays; import com.sun.squawk.util.MathUtils; import com.sun.squawk.util.StringTokenizer; public class TargetCollection { private Target[] targets; public TargetCollection(String targetData) { if(!(targetData.equals(""))) { StringTokenizer targetTokenizer = new StringTokenizer(targetData, ":"); targets = new Target[targetTokenizer.countTokens()]; int currentTarget = 0; try { while(targetTokenizer.hasMoreTokens()) { StringTokenizer targetDataTokenizer = new StringTokenizer(targetTokenizer.nextToken(), ","); double x = Double.parseDouble(targetDataTokenizer.nextToken()); double y = Double.parseDouble(targetDataTokenizer.nextToken()); double distance = Double.parseDouble(targetDataTokenizer.nextToken()); boolean isCenter = targetDataTokenizer.nextToken().equals("1"); targets[currentTarget] = new Target(x, y, distance, isCenter); currentTarget++; } } catch(Exception e) { e.printStackTrace(); } } } /** * Returns a copy of the internal Target array used by this TargetCollection. * @return A Target array equivalent to that used internally by TargetCollection. */ public Target[] getTargets(){ return (Target[])Arrays.copy(targets); } /** * Returns an array of all targets of the specified type. * If {@code centerTarget} is {@code true}, this method returns all center * (high) goals. If {@code centerTarget} is {@code false}, this method * returns all non-center (middle) goals. * @param centerTarget A boolean value indicating whether to return * high or medium Target objects. * @return An array of all targets meeting the specified criteria. */ public Target[] filterByType(boolean centerTarget){ int count = 0; for(int i = 0; i < targets.length; i++){ Target target = targets[i]; if(target.isCenter() == centerTarget){ count++; } } Target[] foundTargets = new Target[count]; int index = 0; for(int i = 0; i < targets.length; i++){ Target target = targets[i]; if(target.isCenter() == centerTarget){ foundTargets[index] = target; index++; } } return foundTargets; } /** * Returns the closest Target object to the given point. The distance * from the point to the center of all Target objects in this TargetCollection * is computed and the target with the smallest such distance is returned. * @param x The x-coordinate of the point to which the distance is computed. * @param y The y-coordinate of the point to which the distance is computed. * @return The target with the smallest distance to the specified point * or {@code null} if this TargetCollection is empty. */ public Target getClosestTarget(double x, double y){ double minDistance = Double.MAX_VALUE; Target foundTarget = null; for(int i = 0; i < targets.length; i++){ Target target = targets[i]; double sqDistance = MathUtils.pow(target.getX() - x, 2)+MathUtils.pow(target.getY() - y, 2); if(sqDistance < minDistance){ minDistance = sqDistance; foundTarget = target; } } return foundTarget; } /** * Returns the closest Target object to the given point and with the given * type. The distance from the point to the center of all Target objects of the proper * type is computed and the target with the smallest such distance is returned. * @param x The x-coordinate of the point to which the distance is computed. * @param y The y-coordinate of the point to which the distance is computed. * @param centerTarget The type of target to return. {@code true} indicates * a high, center target and {@code false} indicates a low, non-center target. * @return The target with the smallest distance to the specified point * or {@code null} if no such target exists. */ public Target getClosestTarget(double x, double y, boolean centerTarget){ double minDistance = Double.MAX_VALUE; Target foundTarget = null; for(int i = 0; i < targets.length; i++){ Target target = targets[i]; if(target.isCenter() == centerTarget){ double sqDistance = MathUtils.pow(target.getX() - x, 2)+MathUtils.pow(target.getY() - y, 2); if(sqDistance < minDistance){ minDistance = sqDistance; foundTarget = target; } } } return foundTarget; } }
package org.phoenix.assetdatabase; import java.io.IOException; import java.util.Collection; import java.util.Map; /** * * @author Vince */ public interface AssetDatabase { public void save() throws IOException; public void load() throws IOException; public boolean contains(TypeGroupInstance tgi); public Subfile loadSubfile(TypeGroupInstance tgi) throws IOException; public Map<TypeGroupInstance, Subfile> loadSubfiles(Collection<TypeGroupInstance> tgis) throws IOException; public void putSubfile(IndexEntry ie, Subfile sf); public void putSubfiles(Map<IndexEntry,Subfile> files); public void removeSubfile(TypeGroupInstance tgi); public Index getIndex(); public MetadataList getMetadata(); public void clear(); }
package org.prx.android.playerhater; import java.io.FileDescriptor; import java.io.IOException; import android.app.Activity; import android.media.MediaPlayer.OnBufferingUpdateListener; import android.media.MediaPlayer.OnCompletionListener; import android.media.MediaPlayer.OnErrorListener; import android.media.MediaPlayer.OnInfoListener; import android.media.MediaPlayer.OnPreparedListener; import android.media.MediaPlayer.OnSeekCompleteListener; import android.net.Uri; import android.os.Bundle; public interface PlayerHater { void seekTo(int position); boolean pause(); boolean stop(); boolean play() throws IllegalStateException, IOException; boolean play(String fileOrUrl) throws IllegalStateException, IllegalArgumentException, SecurityException, IOException; boolean play(String fileOrUrl, boolean isUrl) throws IllegalStateException, IllegalArgumentException, SecurityException, IOException; boolean play(String fileOrUrl, boolean isUrl, Activity activityTriggeredOnNotificationTouch) throws IllegalStateException, IllegalArgumentException, SecurityException, IOException; boolean play(String fileOrUrl, boolean isUrl, Activity activityTriggeredOnNotificationTouch, int notificationView) throws IllegalStateException, IllegalArgumentException, SecurityException, IOException; boolean play(FileDescriptor fd) throws IllegalStateException, IllegalArgumentException, SecurityException, IOException; boolean play(FileDescriptor fd, Activity activityTriggeredOnNotificationTouch) throws IllegalStateException, IllegalArgumentException, SecurityException, IOException; boolean play(FileDescriptor fd, Activity activityTriggeredOnNotificationTouch, int notificationView) throws IllegalStateException, IllegalArgumentException, SecurityException, IOException; boolean play(Uri url) throws IllegalStateException, IllegalArgumentException, SecurityException, IOException; boolean play(Uri url, Activity activityTriggeredOnNotificationTouch) throws IllegalStateException, IllegalArgumentException, SecurityException, IOException; boolean play(Uri url, Activity activityTriggeredOnNotificationTouch, int notificationView) throws IllegalStateException, IllegalArgumentException, SecurityException, IOException; TransientPlayer transientPlay(String fileOrUrl); TransientPlayer transientPlay(String fileOrUrl, boolean isDuckable); TransientPlayer transientPlay(FileDescriptor file); TransientPlayer transientPlay(FileDescriptor file, boolean isDuckable); void setNotificationIntentActivity(Activity activityTriggeredOnNotificationTouch); void setNotificationIcon(int notificationIcon); void setNotificationView(int notificationView); void setNotificationTitle(String notificationTitle); void setNotificationText(String notificationText); void setAutoNotify(boolean autoNotify); void startForeground(); void stopForeground(); int getCurrentPosition(); int getDuration(); void setOnBufferingUpdateListener(OnBufferingUpdateListener listener); void setOnCompletionListener(OnCompletionListener listener); void setOnInfoListener(OnInfoListener listener); void setOnSeekCompleteListener(OnSeekCompleteListener listener); void setOnErrorListener(OnErrorListener listener); void setOnPreparedListener(OnPreparedListener listener); void setListener(PlayerHaterListener listener); String getNowPlaying(); boolean isPlaying(); public boolean isLoading(); int getState(); Bundle getBundle(); void commitBundle(Bundle icicle); }
package com.github.klondike.android.campfire; import android.app.ListActivity; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.github.klondike.java.campfire.Campfire; import com.github.klondike.java.campfire.CampfireException; import com.github.klondike.java.campfire.Room; public class RoomList extends ListActivity { private static final int MENU_PREFS = 0; private static final int MENU_LOGOUT = 1; private ProgressDialog dialog; private Campfire campfire; private Room[] rooms; private boolean forResult = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.room_list); Bundle extras = getIntent().getExtras(); if (extras != null) forResult = extras.getBoolean("for_result", false); verifyLogin(); } @Override public Object onRetainNonConfigurationInstance() { return rooms; } @Override public void onSaveInstanceState(Bundle state) { if (dialog != null && dialog.isShowing()) dialog.dismiss(); super.onSaveInstanceState(state); } // will only be run after we are assured of being logged in public void onLogin() { loadRooms(); } public void selectRoom(Room room) { if (forResult) { Intent intent = new Intent(); Bundle extras = new Bundle(); extras.putString("room_id", room.id); intent.putExtras(extras); setResult(RESULT_OK, intent); finish(); } else { Intent intent = new Intent(Intent.ACTION_MAIN); intent.setClassName("com.github.klondike.android.campfire", "com.github.klondike.android.campfire.RoomView"); Bundle extras = new Bundle(); extras.putString("room_id", room.id); intent.putExtras(extras); startActivity(intent); } } public void displayRooms() { if (rooms.length <= 0) ((TextView) findViewById(R.id.rooms_empty)).setVisibility(View.VISIBLE); setListAdapter(new ArrayAdapter<Room>(RoomList.this, android.R.layout.simple_list_item_1, rooms)); } public void onListItemClick(ListView parent, View v, int position, long id) { Room room = (Room) parent.getItemAtPosition(position); selectRoom(room); } public void loadRooms() { rooms = (Room[]) getLastNonConfigurationInstance(); if (rooms == null) new LoadRoomsTask().execute(); else displayRooms(); } public void verifyLogin() { campfire = Login.getCampfire(this); if (campfire.loggedIn()) onLogin(); else startActivityForResult(new Intent(this, Login.class), Login.RESULT_LOGIN); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case Login.RESULT_LOGIN: if (resultCode == RESULT_OK) { alert("You have been logged in successfully."); campfire = Login.getCampfire(this); onLogin(); } else finish(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { boolean result = super.onCreateOptionsMenu(menu); menu.add(0, MENU_PREFS, 0, "Preferences").setIcon(android.R.drawable.ic_menu_preferences); menu.add(0, MENU_LOGOUT, 0, "Log Out").setIcon(android.R.drawable.ic_menu_close_clear_cancel); return result; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case MENU_PREFS: startActivity(new Intent(this, Preferences.class)); return true; case MENU_LOGOUT: getSharedPreferences("campfire", 0).edit().putString("session", null).commit(); finish(); } return super.onOptionsItemSelected(item); } public void alert(String msg) { Toast.makeText(RoomList.this, msg, Toast.LENGTH_SHORT).show(); } private class LoadRoomsTask extends AsyncTask<Void,Void,Room[]> { @Override protected void onPreExecute() { dialog = new ProgressDialog(RoomList.this); dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); dialog.setCancelable(false); dialog.setMessage("Loading rooms..."); dialog.show(); } @Override protected Room[] doInBackground(Void... nothing) { try { return campfire.getRooms(); } catch (CampfireException e) { return null; } } @Override protected void onPostExecute(Room[] rooms) { dialog.dismiss(); if (rooms != null) { RoomList.this.rooms = rooms; displayRooms(); } else { alert("Error connecting to Campfire. Please try again later."); finish(); } } } }
package org.jboss.as.patching.cli; import static java.lang.System.getProperty; import static java.lang.System.getSecurityManager; import static java.lang.System.getenv; import static java.security.AccessController.doPrivileged; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.ZipFile; import java.util.zip.ZipInputStream; import javax.xml.stream.XMLStreamException; import org.jboss.as.cli.CommandContext; import org.jboss.as.cli.CommandFormatException; import org.jboss.as.cli.CommandLineException; import org.jboss.as.cli.Util; import org.jboss.as.cli.handlers.CommandHandlerWithHelp; import org.jboss.as.cli.handlers.DefaultFilenameTabCompleter; import org.jboss.as.cli.handlers.FilenameTabCompleter; import org.jboss.as.cli.handlers.SimpleTabCompleter; import org.jboss.as.cli.handlers.WindowsFilenameTabCompleter; import org.jboss.as.cli.impl.ArgumentWithValue; import org.jboss.as.cli.impl.ArgumentWithoutValue; import org.jboss.as.cli.impl.DefaultCompleter; import org.jboss.as.cli.impl.FileSystemPathArgument; import org.jboss.as.cli.operation.ParsedCommandLine; import org.jboss.as.cli.util.SimpleTable; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.patching.Constants; import org.jboss.as.patching.IoUtils; import org.jboss.as.patching.PatchingException; import org.jboss.as.patching.logging.PatchLogger; import org.jboss.as.patching.metadata.BundledPatch.BundledPatchEntry; import org.jboss.as.patching.metadata.Identity; import org.jboss.as.patching.metadata.Patch; import org.jboss.as.patching.metadata.PatchBundleXml; import org.jboss.as.patching.metadata.PatchElement; import org.jboss.as.patching.metadata.PatchXml; import org.jboss.as.patching.tool.PatchOperationBuilder; import org.jboss.as.patching.tool.PatchOperationTarget; import org.jboss.dmr.ModelNode; import org.wildfly.security.manager.action.ReadEnvironmentPropertyAction; import org.wildfly.security.manager.action.ReadPropertyAction; public class PatchHandler extends CommandHandlerWithHelp { static final String PATCH = "patch"; static final String APPLY = "apply"; static final String ROLLBACK = "rollback"; static final String HISTORY = "history"; static final String INFO = "info"; static final String INSPECT = "inspect"; private final ArgumentWithValue host; private final ArgumentWithValue action; private final ArgumentWithoutValue path; private final ArgumentWithValue patchId; private final ArgumentWithValue patchStream; private final ArgumentWithoutValue rollbackTo; private final ArgumentWithValue resetConfiguration; private final ArgumentWithoutValue overrideModules; private final ArgumentWithoutValue overrideAll; private final ArgumentWithValue override; private final ArgumentWithValue preserve; private final ArgumentWithoutValue distribution; private final ArgumentWithoutValue modulePath; private final ArgumentWithoutValue bundlePath; private final ArgumentWithoutValue verbose; private final ArgumentWithoutValue streams; /** whether the output should be displayed in a human friendly form or JSON - tools friendly */ private final ArgumentWithoutValue jsonOutput; private static final String lineSeparator = getSecurityManager() == null ? getProperty("line.separator") : doPrivileged(new ReadPropertyAction("line.separator")); public PatchHandler(final CommandContext context) { super(PATCH, false); action = new ArgumentWithValue(this, new SimpleTabCompleter(new String[]{APPLY, ROLLBACK, HISTORY, INFO, INSPECT}), 0, "--action"); host = new ArgumentWithValue(this, new DefaultCompleter(CandidatesProviders.HOSTS), "--host") { @Override public boolean canAppearNext(CommandContext ctx) throws CommandFormatException { boolean connected = ctx.getControllerHost() != null; return connected && ctx.isDomainMode() && super.canAppearNext(ctx); } }; // apply & rollback arguments overrideModules = new ArgumentWithoutValue(this, "--override-modules") { @Override public boolean canAppearNext(CommandContext ctx) throws CommandFormatException { if (canOnlyAppearAfterActions(ctx, APPLY, ROLLBACK)) { return super.canAppearNext(ctx); } return false; } }; overrideModules.addRequiredPreceding(action); overrideAll = new ArgumentWithoutValue(this, "--override-all") { @Override public boolean canAppearNext(CommandContext ctx) throws CommandFormatException { if (canOnlyAppearAfterActions(ctx, APPLY, ROLLBACK)) { return super.canAppearNext(ctx); } return false; } }; overrideAll.addRequiredPreceding(action); override = new ArgumentWithValue(this, "--override") { @Override public boolean canAppearNext(CommandContext ctx) throws CommandFormatException { if (canOnlyAppearAfterActions(ctx, APPLY, ROLLBACK)) { return super.canAppearNext(ctx); } return false; } }; override.addRequiredPreceding(action); preserve = new ArgumentWithValue(this, "--preserve") { @Override public boolean canAppearNext(CommandContext ctx) throws CommandFormatException { if (canOnlyAppearAfterActions(ctx, APPLY, ROLLBACK)) { return super.canAppearNext(ctx); } return false; } }; preserve.addRequiredPreceding(action); // apply arguments final FilenameTabCompleter pathCompleter = Util.isWindows() ? new WindowsFilenameTabCompleter(context) : new DefaultFilenameTabCompleter(context); path = new FileSystemPathArgument(this, pathCompleter, 1, "--path") { @Override public boolean canAppearNext(CommandContext ctx) throws CommandFormatException { if (canOnlyAppearAfterActions(ctx, APPLY, INSPECT)) { return super.canAppearNext(ctx); } return false; } }; path.addRequiredPreceding(action); // rollback arguments patchId = new ArgumentWithValue(this, 1, "--patch-id") { @Override public boolean canAppearNext(CommandContext ctx) throws CommandFormatException { if (canOnlyAppearAfterActions(ctx, INFO, ROLLBACK)) { return super.canAppearNext(ctx); } return false; } }; patchId.addRequiredPreceding(action); patchStream = new ArgumentWithValue(this, "--patch-stream") { @Override public boolean canAppearNext(CommandContext ctx) throws CommandFormatException { if (canOnlyAppearAfterActions(ctx, HISTORY, INFO, ROLLBACK)) { return super.canAppearNext(ctx); } return false; } }; patchStream.addRequiredPreceding(action); rollbackTo = new ArgumentWithoutValue(this, "--rollback-to") { @Override public boolean canAppearNext(CommandContext ctx) throws CommandFormatException { if (canOnlyAppearAfterActions(ctx, ROLLBACK)) { return super.canAppearNext(ctx); } return false; } }; rollbackTo.addRequiredPreceding(action); resetConfiguration = new ArgumentWithValue(this, SimpleTabCompleter.BOOLEAN, "--reset-configuration") { @Override public boolean canAppearNext(CommandContext ctx) throws CommandFormatException { if (canOnlyAppearAfterActions(ctx, ROLLBACK)) { return super.canAppearNext(ctx); } return false; } }; resetConfiguration.addRequiredPreceding(action); distribution = new FileSystemPathArgument(this, pathCompleter, "--distribution") { @Override public boolean canAppearNext(CommandContext ctx) throws CommandFormatException { if (ctx.getModelControllerClient() == null && canOnlyAppearAfterActions(ctx, APPLY, ROLLBACK, HISTORY, INFO)) { return super.canAppearNext(ctx); } return false; } }; modulePath = new FileSystemPathArgument(this, pathCompleter, "--module-path") { @Override public boolean canAppearNext(CommandContext ctx) throws CommandFormatException { if (ctx.getModelControllerClient() == null && canOnlyAppearAfterActions(ctx, APPLY, ROLLBACK, HISTORY, INFO)) { return super.canAppearNext(ctx); } return false; } }; bundlePath = new FileSystemPathArgument(this, pathCompleter, "--bundle-path") { @Override public boolean canAppearNext(CommandContext ctx) throws CommandFormatException { if (ctx.getModelControllerClient() == null && canOnlyAppearAfterActions(ctx, APPLY, ROLLBACK, HISTORY, INFO)) { return super.canAppearNext(ctx); } return false; } }; verbose = new ArgumentWithoutValue(this, "--verbose", "-v") { @Override public boolean canAppearNext(CommandContext ctx) throws CommandFormatException { if (canOnlyAppearAfterActions(ctx, INFO, INSPECT)) { return super.canAppearNext(ctx); } return false; } }; verbose.addRequiredPreceding(action); jsonOutput = new ArgumentWithoutValue(this, "--json-output") { @Override public boolean canAppearNext(CommandContext ctx) throws CommandFormatException { // if (canOnlyAppearAfterActions(ctx, INFO)) { // return super.canAppearNext(ctx); // hide from the tab-completion for now return false; } }; streams = new ArgumentWithoutValue(this, "--streams") { @Override public boolean canAppearNext(CommandContext ctx) throws CommandFormatException { if (canOnlyAppearAfterActions(ctx, INFO)) { return super.canAppearNext(ctx); } return false; } }; streams.addRequiredPreceding(action); streams.addCantAppearAfter(verbose); verbose.addCantAppearAfter(streams); streams.addCantAppearAfter(patchStream); patchStream.addCantAppearAfter(streams); streams.addCantAppearAfter(patchId); patchId.addCantAppearAfter(streams); } private boolean canOnlyAppearAfterActions(CommandContext ctx, String... actions) { final String actionStr = this.action.getValue(ctx.getParsedCommandLine()); if(actionStr == null || actions.length == 0) { return false; } return Arrays.asList(actions).contains(actionStr); } @Override protected void doHandle(CommandContext ctx) throws CommandLineException { final ParsedCommandLine parsedLine = ctx.getParsedCommandLine(); if(host.isPresent(parsedLine) && !ctx.isDomainMode()) { throw new CommandFormatException("The --host option is not available in the current context. Connection to the controller might be unavailable or not running in domain mode."); } final String action = this.action.getValue(parsedLine); if(INSPECT.equals(action)) { doInspect(ctx); return; } final PatchOperationTarget target = createPatchOperationTarget(ctx); final PatchOperationBuilder builder = createPatchOperationBuilder(parsedLine); final ModelNode response; try { response = builder.execute(target); } catch (Exception e) { throw new CommandLineException(action + " failed", e); } if (!Util.isSuccess(response)) { final ModelNode fd = response.get(ModelDescriptionConstants.FAILURE_DESCRIPTION); if(!fd.isDefined()) { throw new CommandLineException("Failed to apply patch: " + response.asString()); } if(fd.has(Constants.CONFLICTS)) { final StringBuilder buf = new StringBuilder(); buf.append(fd.get(Constants.MESSAGE).asString()).append(": "); final ModelNode conflicts = fd.get(Constants.CONFLICTS); String title = ""; if(conflicts.has(Constants.BUNDLES)) { formatConflictsList(buf, conflicts, "", Constants.BUNDLES); title = ", "; } if(conflicts.has(Constants.MODULES)) { formatConflictsList(buf, conflicts, title, Constants.MODULES); title = ", "; } if(conflicts.has(Constants.MISC)) { formatConflictsList(buf, conflicts, title, Constants.MISC); } buf.append(lineSeparator).append("Use the --override-all, --override=[] or --preserve=[] arguments in order to resolve the conflict."); throw new CommandLineException(buf.toString()); } else { throw new CommandLineException(Util.getFailureDescription(response)); } } if(INFO.equals(action)) { if(patchId.getValue(parsedLine) != null) { final ModelNode result = response.get(ModelDescriptionConstants.RESULT); if(!result.isDefined()) { return; } SimpleTable table = new SimpleTable(2); table.addLine(new String[]{"Patch ID:", result.get(Constants.PATCH_ID).asString()}); table.addLine(new String[]{"Type:", result.get(Constants.TYPE).asString()}); table.addLine(new String[]{"Identity name:", result.get(Constants.IDENTITY_NAME).asString()}); table.addLine(new String[]{"Identity version:", result.get(Constants.IDENTITY_VERSION).asString()}); table.addLine(new String[]{"Description:", result.get(Constants.DESCRIPTION).asString()}); if (result.hasDefined(Constants.LINK)) { table.addLine(new String[]{"Link:", result.get(Constants.LINK).asString()}); } ctx.printLine(table.toString(false)); final ModelNode elements = result.get(Constants.ELEMENTS); if(elements.isDefined()) { ctx.printLine(""); ctx.printLine("ELEMENTS"); for(ModelNode e : elements.asList()) { table = new SimpleTable(2); table.addLine(new String[]{"Patch ID:", e.get(Constants.PATCH_ID).asString()}); table.addLine(new String[]{"Name:", e.get(Constants.NAME).asString()}); table.addLine(new String[]{"Type:", e.get(Constants.TYPE).asString()}); table.addLine(new String[]{"Description:", e.get(Constants.DESCRIPTION).asString()}); ctx.printLine(""); ctx.printLine(table.toString(false)); } } } else if(jsonOutput.isPresent(parsedLine)) { ctx.printLine(response.toJSONString(false)); } else if(streams.isPresent(parsedLine)) { final List<ModelNode> list = response.get(ModelDescriptionConstants.RESULT).asList(); if(list.size() == 1) { ctx.printLine(list.get(0).asString()); } else { final List<String> streams = new ArrayList<String>(list.size()); for(ModelNode stream : list) { streams.add(stream.asString()); } ctx.printColumns(streams); } } else { final ModelNode result = response.get(ModelDescriptionConstants.RESULT); if(!result.isDefined()) { return; } SimpleTable table = new SimpleTable(2); table.addLine(new String[]{"Version:", result.get(Constants.VERSION).asString()}); addPatchesInfo(result, table); ctx.printLine(table.toString(false)); if(verbose.isPresent(parsedLine)) { printLayerPatches(ctx, result, Constants.ADD_ON); printLayerPatches(ctx, result, Constants.LAYER); } } } else { ctx.printLine(response.toJSONString(false)); } } protected void printLayerPatches(CommandContext ctx, final ModelNode result, final String type) { ModelNode layer = result.get(type); if(layer.isDefined()) { final String header = Character.toUpperCase(type.charAt(0)) + type.substring(1) + ':'; for(String name : layer.keys()) { final ModelNode node = layer.get(name); final SimpleTable table = new SimpleTable(2); table.addLine(new String[]{header, name}); addPatchesInfo(node, table); ctx.printLine(lineSeparator + table.toString(false)); } } } protected void addPatchesInfo(final ModelNode result, SimpleTable table) { table.addLine(new String[]{"Cumulative patch ID:", result.get(Constants.CUMULATIVE).asString()}); final List<ModelNode> patches = result.get(Constants.PATCHES).asList(); final String patchesStr; if(patches.isEmpty()) { patchesStr = "none"; } else { final StringBuilder buf = new StringBuilder(); buf.append(patches.get(0).asString()); for (int i = 1; i < patches.size(); ++i) { buf.append(',').append(patches.get(i).asString()); } patchesStr = buf.toString(); } table.addLine(new String[]{"One-off patches:", patchesStr}); } protected void doInspect(CommandContext ctx) throws CommandLineException { final ParsedCommandLine parsedLine = ctx.getParsedCommandLine(); final String patchPath = path.getValue(parsedLine, true); final File patchFile = new File(patchPath); if(!patchFile.exists()) { throw new CommandLineException("Failed to locate " + patchFile.getAbsolutePath()); } ZipFile patchZip = null; InputStream is = null; try { patchZip = new ZipFile(patchFile); ZipEntry patchXmlEntry = patchZip.getEntry(PatchBundleXml.MULTI_PATCH_XML); if(patchXmlEntry == null) { patchXmlEntry = patchZip.getEntry(PatchXml.PATCH_XML); if(patchXmlEntry == null) { throw new CommandLineException("Neither " + PatchBundleXml.MULTI_PATCH_XML + " nor " + PatchXml.PATCH_XML+ " were found in " + patchFile.getAbsolutePath()); } is = patchZip.getInputStream(patchXmlEntry); final Patch patch = PatchXml.parse(is).resolvePatch(null, null); displayPatchXml(ctx, patch); } else { is = patchZip.getInputStream(patchXmlEntry); final List<BundledPatchEntry> patches = PatchBundleXml.parse(is).getPatches(); displayPatchBundleXml(ctx, patches, patchZip); } } catch (ZipException e) { throw new CommandLineException("Failed to open " + patchFile.getAbsolutePath(), e); } catch (IOException e) { throw new CommandLineException("Failed to open " + patchFile.getAbsolutePath(), e); } catch (PatchingException e) { throw new CommandLineException("Failed to resolve parsed patch", e); } catch (XMLStreamException e) { throw new CommandLineException("Failed to parse patch.xml", e); } finally { if(is != null) { try { is.close(); } catch (IOException e) { } } if (patchZip != null) { try { patchZip.close(); } catch (IOException e) { } } } } private void displayPatchBundleXml(CommandContext ctx, List<BundledPatchEntry> patches, ZipFile patchZip) throws CommandLineException { if(patches.isEmpty()) { return; } for(BundledPatchEntry bundledPatch : patches) { final ZipEntry bundledZip = patchZip.getEntry(bundledPatch.getPatchPath()); if(bundledZip == null) { throw new CommandLineException("Patch file not found in the bundle: " + bundledPatch.getPatchPath()); } InputStream is = null; ZipInputStream bundledPatchIs = null; try { is = patchZip.getInputStream(bundledZip); bundledPatchIs = new ZipInputStream(is); ZipEntry bundledPatchXml = bundledPatchIs.getNextEntry(); while(bundledPatchXml != null) { if(PatchXml.PATCH_XML.equals(bundledPatchXml.getName())) { break; } bundledPatchXml = bundledPatchIs.getNextEntry(); } if(bundledPatchXml == null) { throw new CommandLineException("Failed to locate " + PatchXml.PATCH_XML + " in bundled patch " + bundledPatch.getPatchPath()); } final Patch patch = PatchXml.parse(bundledPatchIs).resolvePatch(null, null); if(verbose.isPresent(ctx.getParsedCommandLine())) { // to make the separation better in the verbose mode ctx.printLine("CONTENT OF " + bundledPatch.getPatchPath() + ':' + Util.LINE_SEPARATOR); } displayPatchXml(ctx, patch); ctx.printLine(""); } catch (Exception e) { throw new CommandLineException("Failed to inspect " + bundledPatch.getPatchPath(), e); } finally { IoUtils.safeClose(bundledPatchIs); IoUtils.safeClose(is); } } } private void displayPatchXml(CommandContext ctx, Patch patch) throws CommandLineException { final Identity identity = patch.getIdentity(); SimpleTable table = new SimpleTable(2); table.addLine(new String[]{"Patch ID:", patch.getPatchId()}); table.addLine(new String[]{"Type:", identity.getPatchType().getName()}); table.addLine(new String[]{"Identity name:", identity.getName()}); table.addLine(new String[]{"Identity version:", identity.getVersion()}); table.addLine(new String[]{"Description:", patch.getDescription() == null ? "n/a" : patch.getDescription()}); if (patch.getLink() != null) { table.addLine(new String[]{"Link:", patch.getLink()}); } ctx.printLine(table.toString(false)); if(verbose.isPresent(ctx.getParsedCommandLine())) { ctx.printLine(""); ctx.printLine("ELEMENTS"); for(PatchElement e : patch.getElements()) { table = new SimpleTable(2); table.addLine(new String[]{"Patch ID:", e.getId()}); table.addLine(new String[]{"Name:", e.getProvider().getName()}); table.addLine(new String[]{"Type:", e.getProvider().isAddOn() ? Constants.ADD_ON : Constants.LAYER}); table.addLine(new String[]{"Description:", e.getDescription()}); ctx.printLine(""); ctx.printLine(table.toString(false)); } } } protected void formatConflictsList(final StringBuilder buf, final ModelNode conflicts, String title, String contentType) { buf.append(title); final List<ModelNode> list = conflicts.get(contentType).asList(); int i = 0; while(i < list.size()) { final ModelNode item = list.get(i++); buf.append(item.asString()); if(i < list.size()) { buf.append(", "); } } } private PatchOperationBuilder createPatchOperationBuilder(ParsedCommandLine args) throws CommandFormatException { final String action = this.action.getValue(args, true); PatchOperationBuilder builder; if (APPLY.equals(action)) { final String path = this.path.getValue(args, true); final File f = new File(path); if(!f.exists()) { // i18n is never used for CLI exceptions throw new CommandFormatException("Path " + f.getAbsolutePath() + " doesn't exist."); } if(f.isDirectory()) { throw new CommandFormatException(f.getAbsolutePath() + " is a directory."); } builder = PatchOperationBuilder.Factory.patch(f); } else if (ROLLBACK.equals(action)) { String resetConfigValue = resetConfiguration.getValue(args, true); boolean resetConfig; if(Util.TRUE.equalsIgnoreCase(resetConfigValue)) { resetConfig = true; } else if(Util.FALSE.equalsIgnoreCase(resetConfigValue)) { resetConfig = false; } else { throw new CommandFormatException("Unexpected value for --reset-configuration (only true and false are allowed): " + resetConfigValue); } final String patchStream = this.patchStream.getValue(args); if(patchId.isPresent(args)) { final String id = patchId.getValue(args, true); final boolean rollbackTo = this.rollbackTo.isPresent(args); builder = PatchOperationBuilder.Factory.rollback(patchStream, id, rollbackTo, resetConfig); } else { builder = PatchOperationBuilder.Factory.rollbackLast(patchStream, resetConfig); } } else if (INFO.equals(action)) { if(streams.isPresent(args)) { return PatchOperationBuilder.Factory.streams(); } final String patchStream = this.patchStream.getValue(args); final String pId = patchId.getValue(args); if(pId == null) { builder = PatchOperationBuilder.Factory.info(patchStream); } else { builder = PatchOperationBuilder.Factory.info(patchStream, pId, verbose.isPresent(args)); } return builder; } else if (HISTORY.equals(action)) { final String patchStream = this.patchStream.getValue(args); builder = PatchOperationBuilder.Factory.history(patchStream); return builder; } else { throw new CommandFormatException("Unrecognized action '" + action + "'"); } if (overrideModules.isPresent(args)) { builder.ignoreModuleChanges(); } if (overrideAll.isPresent(args)) { builder.overrideAll(); } if (override.isPresent(args)) { final String overrideList = override.getValue(args); if(overrideList == null || overrideList.isEmpty()) { throw new CommandFormatException(override.getFullName() + " is missing value."); } for (String path : overrideList.split(",+")) { builder.overrideItem(path); } } if (preserve.isPresent(args)) { final String preserveList = preserve.getValue(args); if(preserveList == null || preserveList.isEmpty()) { throw new CommandFormatException(preserve.getFullName() + " is missing value."); } for (String path : preserveList.split(",+")) { builder.preserveItem(path); } } return builder; } private PatchOperationTarget createPatchOperationTarget(CommandContext ctx) throws CommandLineException { final PatchOperationTarget target; final ParsedCommandLine args = ctx.getParsedCommandLine(); if (ctx.getModelControllerClient() != null) { if(distribution.isPresent(args)) { throw new CommandFormatException(distribution.getFullName() + " is not allowed when connected to the controller."); } if(modulePath.isPresent(args)) { throw new CommandFormatException(modulePath.getFullName() + " is not allowed when connected to the controller."); } if(bundlePath.isPresent(args)) { throw new CommandFormatException(bundlePath.getFullName() + " is not allowed when connected to the controller."); } if (ctx.isDomainMode()) { String hostName = host.getValue(args, true); target = PatchOperationTarget.createHost(hostName, ctx.getModelControllerClient()); } else { target = PatchOperationTarget.createStandalone(ctx.getModelControllerClient()); } } else { final String jbossHome = getJBossHome(args); final File root = new File(jbossHome); final List<File> modules = getFSArgument(modulePath, args, root, "modules"); final List<File> bundles = getFSArgument(bundlePath, args, root, "bundles"); try { target = PatchOperationTarget.createLocal(root, modules, bundles); } catch (Exception e) { throw new CommandLineException("Unable to apply patch to local JBOSS_HOME=" + jbossHome, e); } } return target; } private static final String HOME = "JBOSS_HOME"; private static final String HOME_DIR = "jboss.home.dir"; private String getJBossHome(final ParsedCommandLine args) { final String targetDistro = distribution.getValue(args); if(targetDistro != null) { return targetDistro; } String resolved = getSecurityManager() == null ? getenv(HOME) : doPrivileged(new ReadEnvironmentPropertyAction(HOME)); if (resolved == null) { resolved = getSecurityManager() == null ? getProperty(HOME_DIR) : doPrivileged(new ReadPropertyAction(HOME_DIR)); } if (resolved == null) { throw PatchLogger.ROOT_LOGGER.cliFailedToResolveDistribution(); } return resolved; } private static List<File> getFSArgument(final ArgumentWithoutValue arg, final ParsedCommandLine args, final File root, final String param) { final String value = arg.getValue(args); if (value != null) { final String[] values = value.split(Pattern.quote(File.pathSeparator)); if (values.length == 1) { return Collections.singletonList(new File(value)); } final List<File> resolved = new ArrayList<File>(values.length); for (final String path : values) { resolved.add(new File(path)); } return resolved; } return Collections.singletonList(new File(root, param)); } }
package com.hp.hpl.jena.vocabulary; import com.hp.hpl.jena.rdf.model.*; import com.hp.hpl.jena.reasoner.ReasonerRegistry; public class ReasonerVocabulary { /** The namespace used for system level descriptive properties of any reasoner */ public static String JenaReasonerNS = "http://www.hpl.hp.com/semweb/2003/JenaReasoner /** The RDF class to which all Reasoners belong */ public static Resource ReasonerClass = ResourceFactory.createResource(JenaReasonerNS + "ReasonerClass"); /** Reasoner description property: name of the reasoner */ public static Property nameP; /** Reasoner description property: text description of the reasoner */ public static Property descriptionP; /** Reasoner description property: version of the reasoner */ public static Property versionP; /** Reasoner description property: a schema property supported by the reasoner */ public static Property supportsP; /** Reasoner description property: a configuration property supported by the reasoner */ public static Property configurationP; /** The property that represents the direct/minimal version of the subClassOf relationship */ public static Property directSubClassOf; /** The property that represents the direct/minimal version of the subPropertyOf relationship */ public static Property directSubPropertyOf; /** Base URI used for configuration properties for rule reasoners */ public static final String PropURI = "http: /** Property used to configure the derivation logging behaviour of a reasoner. * Set to "true" to enable logging of derivations. */ public static Property PROPderivationLogging; /** Property used to configure the tracing behaviour of a reasoner. * Set to "true" to enable internal trace message to be sent to Logger.info . */ public static Property PROPtraceOn; /** Property used to set the mode of a generic rule reasoner. * Valid values are the strings "forward", "backward" or "hybrid" */ public static Property PROPruleMode; /** Property used to attach a file a rules to a generic rule reasoner. * Value should a URI giving the rule set to use. */ public static Property PROPruleSet; /** Property used to switch on/off OWL schema translation on a generic rule reasoner. * Value should be "true" to enable OWL translation */ public static Property PROPenableOWLTranslation; /** Property used to switch on/off use of the dedicated subclass/subproperty * caching in a generic rule reasoner. Set to "true" to enable caching. */ public static Property PROPenableTGCCaching; /** Property used to switch on/off scanning of data for container membership * properties in RDFS preprocessing. */ public static Property PROPenableCMPScan; /** A namespace used for Rubric specific properties */ public static final String RBNamespace = "urn:x-hp-jena:rubrik/"; // Method versions of key namespaces which are more initializer friendly /** Return namespace used for Rubric specific properties */ public static final String getRBNamespace() { return RBNamespace; } /** Return namespace used for system level descriptive properties of any reasoner */ public static final String getJenaReasonerNS() { return JenaReasonerNS; } // Initializers static { try { nameP = ResourceFactory.createProperty(JenaReasonerNS, "name"); descriptionP = ResourceFactory.createProperty(JenaReasonerNS, "description"); versionP = ResourceFactory.createProperty(JenaReasonerNS, "version"); supportsP = ResourceFactory.createProperty(JenaReasonerNS, "supports"); configurationP = ResourceFactory.createProperty(JenaReasonerNS, "configurationProperty"); directSubClassOf = ResourceFactory.createProperty(ReasonerRegistry.makeDirect(RDFS.subClassOf.getNode()).getURI()); directSubPropertyOf = ResourceFactory.createProperty(ReasonerRegistry.makeDirect(RDFS.subPropertyOf.getNode()).getURI()); PROPderivationLogging = ResourceFactory.createProperty(PropURI+"#", "derivationLogging"); PROPtraceOn = ResourceFactory.createProperty(PropURI+"#", "traceOn"); PROPruleMode = ResourceFactory.createProperty(PropURI+"#", "ruleMode"); PROPruleSet = ResourceFactory.createProperty(PropURI+"#", "ruleSet"); PROPenableOWLTranslation = ResourceFactory.createProperty(PropURI+"#", "enableOWLTranslation"); PROPenableTGCCaching = ResourceFactory.createProperty(PropURI+"#", "enableTGCCaching"); PROPenableCMPScan = ResourceFactory.createProperty(PropURI+"#", "enableCMPScan"); } catch (Exception e) { System.err.println("Initialization error: " + e); e.printStackTrace(System.err); } } }
package org.twak.siteplan.campskeleton; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.GridLayout; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.Set; import java.util.Vector; import javax.imageio.ImageIO; import javax.swing.DefaultComboBoxModel; import javax.swing.DefaultListModel; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JToggleButton; import javax.swing.Popup; import javax.swing.PopupFactory; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.vecmath.Matrix4d; import javax.vecmath.Point2d; import javax.vecmath.Point3d; import javax.vecmath.Vector3d; import org.twak.camp.Output; import org.twak.camp.Skeleton; import org.twak.camp.Tag; import org.twak.camp.debug.DebugDevice; import org.twak.camp.ui.Bar; import org.twak.camp.ui.Marker; import org.twak.camp.ui.PointEditor; import org.twak.siteplan.anchors.Anchor; import org.twak.siteplan.anchors.NaturalStepShip; import org.twak.siteplan.anchors.Ship; import org.twak.siteplan.anim.APlanBoxes; import org.twak.siteplan.anim.OverhangPlan; import org.twak.siteplan.anim.PioneerPlan; import org.twak.siteplan.anim.RenderAnimFrame; import org.twak.siteplan.jme.Jme; import org.twak.siteplan.jme.PillarFeature; import org.twak.siteplan.jme.Preview; import org.twak.siteplan.junk.ForcedStep; import org.twak.siteplan.tags.PlanTag; import org.twak.utils.LContext; import org.twak.utils.Pair; import org.twak.utils.WeakListener; import org.twak.utils.collections.ConsecutivePairs; import org.twak.utils.collections.Loop; import org.twak.utils.collections.LoopL; import org.twak.utils.ui.ListDownLayout; import org.twak.utils.ui.SaveLoad; import org.twak.utils.ui.SimpleFileChooser; import org.twak.utils.ui.WindowManager; import com.jme3.math.Vector3f; import com.jme3.scene.Spatial; import com.jme3.scene.shape.Box; /** * User interface for editing the skeleton * * @author twak */ public class Siteplan extends javax.swing.JFrame { private static final String GO = "go"; public final static String toolKey = "related tool"; public final static boolean Is_User = false; // dev flag public static Siteplan instance; public final WeakListener selectedAnchorListeners = new WeakListener(); public final WeakListener somethingChangedListeners = new WeakListener(); public final WeakListener profileListChangedListeners = new WeakListener(); public Tool mode = Tool.Vertex; public Plan plan; // field accessed via reflection for SaveLoad public Bar selectedEdge; ProfileUI profileUI; PlanUI planUI; boolean fireEvents = true; public Tag selectedTag; public Preview preview; private SaveLoad saveLoad; public Tag wall = new Tag( "wall" ), roof = new Tag( "roof" ), weakEdge = new Tag( "weak edge" ); // what we're currently working on public Object threadKey; boolean autoup = true; // has input changed recently? boolean dirty = true; public BufferedImage bgImage = null; public double gridSize = -1; // frame for showing tags and features public JFrame tagFeatureFrame = null; // animation frame we're on int frame = 0; public Siteplan() { this( null, true ); } /** Creates new form CampSkeleton */ public Siteplan( Plan plan, boolean showPreview ) { instance = this; if (showPreview) preview = new Preview(); initComponents(); centralPanel.setLayout( new ListDownLayout() ); centralPanel.setPreferredSize( new Dimension( 200, 300 ) ); centralPanel.setMaximumSize( new Dimension( 200, 30000 ) ); for ( Tool tl : Tool.values() ) { if ( tl == Tool.Anchor ) // not needed for now continue; final Tool ft = tl; final JToggleButton tb = new JToggleButton( ft.name().toLowerCase() ); tb.putClientProperty( this, ft ); paletteGroup.add( tb ); tb.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { if ( tb.isSelected() ) setTool( ft ); } } ); palettePanel.add( tb ); } // select first button for ( Component c : palettePanel.getComponents() ) { ( (JToggleButton) c ).setSelected( true ); break; } saveLoad = new SaveLoad() { @Override public void afterLoad() { loadPlan( plan ); // flush all tool state setTool( Tool.Vertex ); setImage( null ); showRoot(); updateTitle(); killTagFeature(); } @Override public void makeNew() { setDefaultPlan(); setImage( null ); setTool( Tool.Vertex ); reset(); setPlan( plan ); saveLoad.saveAs = null; updateTitle(); killTagFeature(); } @Override public void afterSave() { updateTitle(); } @Override public void beforeSave() { // clean plan.profiles Set<Bar> used = plan.findBars(); Iterator<Bar> itb = plan.profiles.keySet().iterator(); while ( itb.hasNext() ) if ( !used.contains( itb.next() ) ) itb.remove(); if ( profileUI != null ) profileUI.flushtoProfile(); } }; saveLoad.addSaveLoadMenuItems( fileMenu, "plan", this ); // reflective reference to field plan if ( plan == null ) setDefaultPlan(); else setPlan( plan ); setupProfileCombo(); updateTitle(); showRoot(); setSize( 800, 800 ); setLocation( 700, 100 ); rootPanel.revalidate(); // something to look at :) goButtonActionPerformed( null ); } /** * Call this to refresh the profile list in the UI */ public void profileListChanged() { setupProfileCombo(); profileListChangedListeners.fire(); } void updateTitle() { setTitle( "siteplan" ); } public void setTool( Tool mode ) { nowSelectingFor( null ); Siteplan.instance.highlightFor( new ArrayList() ); this.mode = mode; toolPanel.removeAll(); toolPanel.setLayout( new GridLayout( 1, 1 ) ); for ( MarkerUI mui : new MarkerUI[] { planUI, profileUI } ) { if ( mui == null ) continue; // still in setup flushMarkersToUI( mui ); } if ( mode == Tool.Anchor ) { // don't like this, maybe we want a "goto root" button and only put features in the combo? if ( selectedTag == null && plan.tags.size() > 0 ) planCombo.setSelectedItem( plan.tags.get( 0 ) ); } else if ( mode == Tool.Features ) { showTagFeature(); // toolPanel.add( new FeatureUI(plan)); } else if ( mode == Tool.Tag ) { showTagFeature(); // toolPanel.add ( new TagListUI(plan) );//new TagFeatureList (roof, weakEdge) ); } centralPanel.revalidate(); // quick and dirty for ( Component c : palettePanel.getComponents() ) { if ( c instanceof JToggleButton ) { JToggleButton j = (JToggleButton) c; if ( mode == j.getClientProperty( this ) && !j.isSelected() ) j.doClick(); } } } public void showTagFeature() { if ( tagFeatureFrame == null ) { tagFeatureFrame = new JFrame( "features and tags" ); tagFeatureFrame.setContentPane( new TagsFeaturesUI( plan ) ); WindowManager.register( tagFeatureFrame ); } if ( !tagFeatureFrame.isVisible() ) { tagFeatureFrame.setSize( 800, 600 ); tagFeatureFrame.setVisible( true ); // position to right of main frame. vey annoying on laptop. // Point p = new Point( jPanel4.getWidth(), 0 ); // SwingUtilities.convertPointToScreen( p, jPanel4 ); // tagFeatureFrame.setLocation( p );//p.x+getWidth(), p.y); } tagFeatureFrame.toFront(); } public void killTagFeature() { if ( tagFeatureFrame == null ) return; tagFeatureFrame.setVisible( false ); tagFeatureFrame.dispose(); tagFeatureFrame = null; } public void setProfile( Profile profile ) { if ( profileUI != null ) { if ( profileUI.profile == profile ) return; else profileUI.flushtoProfile(); flushMarkersToUI( profileUI ); } if ( machineCombo.getSelectedItem() != profile ) { fireEvents = false; machineCombo.setSelectedItem( profile ); // this occurs if we select an edge from a profile if ( machineCombo.getSelectedItem() != profile ) machineCombo.setSelectedItem( null ); fireEvents = true; } profilePanel.removeAll(); profilePanel.setLayout( new GridLayout( 1, 1 ) ); machineCombo.setEnabled( profile != null ); if ( profile != null ) { profileUI = new ProfileUI( profile, plan, new ProfileEdgeSelected() ) { /** * Quick hacky solutions until the ui is finalized... */ @Override public void releasePoint( Point2d pt, LContext<Bar> ctx, MouseEvent evt ) { super.releasePoint( pt, ctx, evt ); if ( planUI != null ) planUI.repaint(); } @Override public void paint( Graphics g ) { super.paint( g ); if ( planUI != null ) planUI.somethingChanged( null ); } }; flushMarkersToUI( profileUI ); profilePanel.add( profileUI ); profileUI.revalidate(); } else { profileUI = null; profilePanel.add( new JLabel( "Select an edge to edit the profile", JLabel.CENTER ) ); profilePanel.revalidate(); } } public void setEdge( Bar edge ) { selectedEdge = edge; Profile profile = plan.profiles.get( edge ); setProfile( profile ); } private void reset() { selectedEdge = null; profileUI = null; planUI = null; selectedTag = null; setupProfileCombo(); } private void setDefaultPlan() { plan = new Plan(); plan.name = "root-plan"; Profile defaultProf = new Profile( 50 ); defaultProf.points.get(0).append(new Bar( defaultProf.points.get(0).start.get().end, new Point2d (50,-100) ) ); // defaultProf.points.get( 0 ).start.get().end.x += 20; createCross( plan, defaultProf ); plan.addLoop( defaultProf.points.get( 0 ), plan.root, defaultProf ); } public void somethingChanged() { if ( autoupdateButtom != null ) // if used in dummy mode, this'll be true if ( autoupdateButtom.isSelected() ) { dirty = true; goButtonActionPerformed( null ); } somethingChangedListeners.fire(); } private void setImage( BufferedImage read ) { bgImage = read; if ( planUI != null ) { planUI.bgImage = read; planUI.repaint(); } } private void flushMarkersToUI( MarkerUI mui ) { mui.showMarkers( mode == Tool.Anchor || mode == Tool.Features ); mui.showTags( mode == Tool.Tag ); } void setSelectedFeature( Tag f ) { selectedTag = f; if ( planUI != null ) planUI.repaint(); if ( profileUI != null ) profileUI.repaint(); } private class ProfileEdgeSelected implements PointEditor.BarSelected { public void barSelected( LContext<Bar> ctx ) { // JOptionPane.showMessageDialog( CampSkeleton.this, "not implemented in campskeleton" ); } } public class PlanEdgeSelected implements PointEditor.BarSelected { public void barSelected( LContext<Bar> ctx ) { setEdge( ctx == null ? null : ctx.get() ); } } private int countMarkerMatches( Object generator, Set<Profile> profiles ) { int count = 0; for ( Loop<Bar> loop : plan.points ) for ( Bar b : loop ) for ( Marker m : b.mould.markersOn( b ) ) if ( m.generator.equals( generator ) ) count++; for ( Profile p : new HashSet<Profile>( profiles ) ) for ( Bar b : p.points.eIterator() ) for ( Marker m : b.mould.markersOn( b ) ) if ( m.generator.equals( generator ) ) count++; // todo: each feature may also have nested markers? for ( Ship s : plan.ships ) count += s.countMarkerMatches( generator ); return count; } public void loadPlan( Plan plan ) { Siteplan.this.reset(); int nSteps = 0, nInstances = 0; Set<Profile> usedProf = new HashSet(); for ( Bar b : plan.points.eIterator() ) usedProf.add( plan.profiles.get( b ) ); for ( Ship s : plan.ships ) if ( s instanceof NaturalStepShip ) { NaturalStepShip ss = (NaturalStepShip) s; for ( Bar b : ss.shape.eIterator() ) usedProf.add( plan.profiles.get( b ) ); } for ( Ship s : plan.ships ) if ( s instanceof NaturalStepShip ) { nInstances += s.getInstances().size(); if ( !s.getInstances().isEmpty() ) nSteps++; } statusLabel.setText( "loops:" + plan.points.size() + " verts:" + plan.points.count() + " profiles:" + usedProf.size() + " n/steps:" + nSteps + " n/instances:" + nInstances + " globals:" + ( plan.globals.size() - 1 ) ); setPlan( plan ); for ( Tag f : plan.tags ) { meshItem.setEnabled( false ); if ( f.name.compareTo( "wall" ) == 0 ) wall = f; if ( f.name.compareTo( "roof" ) == 0 ) roof = f; if ( f.name.compareTo( "weak edge" ) == 0 ) weakEdge = f; // if ( f.name.compareTo( "pillar" ) == 0 ) // pillar = (PillarFeature) f; } } public void setPlan( PlanUI selected ) { PlanUI pu = (PlanUI) selected; pu.setGridSize( gridSize ); planPanel.removeAll(); planPanel.setLayout( new GridLayout( 1, 1 ) ); planPanel.add( planUI = pu ); planUI.barSelected = new PlanEdgeSelected(); exportButton.setVisible( pu.canExport() ); importButton.setVisible( pu.canImport() ); flushMarkersToUI( pu ); repaint(); } public void setPlan( Plan selected ) { // nothing to do? this.plan = (Plan) selected; setPlan( planUI = new PlanUI( (Plan) selected, new PlanEdgeSelected() ) ); setImage( bgImage ); setEdge( null ); setupProfileCombo(); } public void setupProfileCombo() { machineCombo.setModel( new DefaultComboBoxModel( new Vector( plan.findProfiles() ) ) ); if ( selectedEdge != null ) machineCombo.setSelectedItem( plan.profiles.get( selectedEdge ) ); } public void assignProfileToBar( Bar bar, Profile profile ) { plan.profiles.put( bar, profile ); repaint(); } // Camp skeleton currently coordinates modes, & takes responsibility for the anchor that we're currently working on public Anchor selectedAnchor = null; List<Anchor> highlitAnchors = new ArrayList(); public void setAnchorPlan( Marker m ) { if ( selectedAnchor != null ) { selectedAnchor.setPlanGen( m.generator ); selectedAnchorListeners.fire(); } } public void setAnchorProfile( Marker m ) { if ( selectedAnchor != null ) { selectedAnchor.setProfileGen( m.generator ); selectedAnchorListeners.fire(); } } public void nowSelectingFor( Anchor anchor ) { selectedAnchor = anchor; selectedAnchorListeners.fire(); if ( planUI != null ) planUI.repaint(); if ( profileUI != null ) profileUI.repaint(); } public void highlightFor( List<Anchor> anchors ) { highlitAnchors = anchors; if ( planUI != null ) planUI.repaint(); if ( profileUI != null ) profileUI.repaint(); } public void showRoot() { planPanel.removeAll(); planPanel.setLayout( new GridLayout( 1, 1 ) ); setPlan( new PlanUI( plan, new PlanEdgeSelected() ) ); setTool( mode ); setImage( bgImage ); planPanel.add( planUI ); planUI.revalidate(); repaint(); } public void setGrid( double val ) { this.gridSize = val; if ( planUI != null ) planUI.setGridSize( gridSize ); } public void update( int f ) { update( f, true ); } public void update( int f, boolean recalculate ) { int nFrame = Math.max( 0, f ); int delta = nFrame - frame; if ( delta != 0 ) { plan.update( nFrame, delta ); frame = nFrame; // assign profiles based on our new shape // if ( plan.buildFromPlan != null ) // plan.buildFromPlan.buildFromPlan(); setPlan( plan ); // <- not sure about this, can planUI repain on demand? or not be edited? if ( recalculate ) somethingChanged(); // <- this'll redo the 3d output if "udpate" is selected statusLabel.setText( "f:" + frame ); frameSpinner.setValue( nFrame ); } } /** * 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() { paletteGroup = new javax.swing.ButtonGroup(); planCombo = new javax.swing.JComboBox(); editPlanButton = new javax.swing.JButton(); newFeatureButton = new javax.swing.JButton(); gridGroup = new javax.swing.ButtonGroup(); setMachineButton = new javax.swing.JButton(); jPanel3 = new javax.swing.JPanel(); goButton = new javax.swing.JButton(); autoupdateButtom = new javax.swing.JToggleButton(); statusLabel = new javax.swing.JLabel(); playButton = new javax.swing.JButton(); jToggleButton1 = new javax.swing.JToggleButton(); frameSpinner = new javax.swing.JSpinner(); rootPanel = new javax.swing.JPanel(); planBorder = new javax.swing.JPanel(); planPanel = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); showRootButton = new javax.swing.JButton(); importButton = new javax.swing.JButton(); exportButton = new javax.swing.JButton(); jPanel5 = new javax.swing.JPanel(); profileBorder = new javax.swing.JPanel(); jPanel1 = new javax.swing.JPanel(); profileCard = new javax.swing.JPanel(); addMachineButton = new javax.swing.JButton(); machineCombo = new javax.swing.JComboBox(); profilePanel = new javax.swing.JPanel(); centralPanel = new javax.swing.JPanel(); palettePanel = new javax.swing.JPanel(); toolPanel = new javax.swing.JPanel(); jMenuBar1 = new javax.swing.JMenuBar(); fileMenu = new javax.swing.JMenu(); objDumpItem = new javax.swing.JMenuItem(); meshItem = new javax.swing.JMenuItem(); jMenu1 = new javax.swing.JMenu(); backgroundItem = new javax.swing.JMenuItem(); clearImageButton = new javax.swing.JMenuItem(); jMenu3 = new javax.swing.JMenu(); gridOff = new javax.swing.JRadioButtonMenuItem(); gridSmall = new javax.swing.JRadioButtonMenuItem(); gridMedium = new javax.swing.JRadioButtonMenuItem(); gridHuge = new javax.swing.JRadioButtonMenuItem(); jMenu2 = new javax.swing.JMenu(); jMenu4 = new javax.swing.JMenu(); aPlanItem = new javax.swing.JMenuItem(); pioneersPlanItem = new javax.swing.JMenuItem(); overhangPlanItem = new javax.swing.JMenuItem(); timeBackItem = new javax.swing.JMenuItem(); timeForwardItem = new javax.swing.JMenuItem(); zeroTimeItem = new javax.swing.JMenuItem(); editClassifier = new javax.swing.JMenuItem(); renderAnimItem = new javax.swing.JMenuItem(); jSeparator1 = new javax.swing.JPopupMenu.Separator(); clearPlanItem = new javax.swing.JMenuItem(); svgImport = new javax.swing.JMenuItem(); reversePlanItem = new javax.swing.JMenuItem(); jMenu5 = new javax.swing.JMenu(); aboutItem = new javax.swing.JMenuItem(); planCombo.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent evt ) { planComboActionPerformed( evt ); } } ); editPlanButton.setText( "set plan" ); editPlanButton.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent evt ) { editPlanButtonActionPerformed( evt ); } } ); newFeatureButton.setText( "new feature" ); newFeatureButton.addMouseListener( new java.awt.event.MouseAdapter() { public void mousePressed( java.awt.event.MouseEvent evt ) { newFeatureButtonMousePressed( evt ); } } ); newFeatureButton.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent evt ) { newFeatureButtonActionPerformed( evt ); } } ); setMachineButton.setText( "set" ); setMachineButton.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent evt ) { setMachineButtonActionPerformed( evt ); } } ); setDefaultCloseOperation( javax.swing.WindowConstants.EXIT_ON_CLOSE ); goButton.setText( GO ); goButton.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent evt ) { goButtonActionPerformed( evt ); } } ); autoupdateButtom.setText( "updates" ); autoupdateButtom.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent evt ) { autoupdateButtomActionPerformed( evt ); } } ); playButton.setText( ">" ); playButton.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent evt ) { playButtonActionPerformed( evt ); } } ); jToggleButton1.setText( "random" ); jToggleButton1.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent evt ) { jToggleButton1ActionPerformed( evt ); } } ); frameSpinner.setModel( new javax.swing.SpinnerNumberModel( Integer.valueOf( 0 ), Integer.valueOf( 0 ), null, Integer.valueOf( 1 ) ) ); frameSpinner.addChangeListener( new javax.swing.event.ChangeListener() { public void stateChanged( javax.swing.event.ChangeEvent evt ) { frameSpinnerStateChanged( evt ); } } ); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout( jPanel3 ); jPanel3.setLayout( jPanel3Layout ); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING ).addGroup( javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup().addContainerGap().addComponent( frameSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE ).addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED ).addComponent( statusLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 340, Short.MAX_VALUE ).addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED ).addComponent( jToggleButton1 ).addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED ).addComponent( playButton ).addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED ).addComponent( autoupdateButtom ).addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED ).addComponent( goButton, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE ).addContainerGap() ) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING ).addGroup( jPanel3Layout.createSequentialGroup().addContainerGap().addGroup( jPanel3Layout.createParallelGroup( javax.swing.GroupLayout.Alignment.TRAILING, false ).addComponent( frameSpinner, javax.swing.GroupLayout.Alignment.LEADING ).addComponent( goButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE ).addComponent( autoupdateButtom, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE ).addComponent( playButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE ).addComponent( jToggleButton1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE ).addGroup( jPanel3Layout.createParallelGroup( javax.swing.GroupLayout.Alignment.BASELINE ).addComponent( statusLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE ) ) ).addContainerGap( 14, Short.MAX_VALUE ) ) ); getContentPane().add( jPanel3, java.awt.BorderLayout.SOUTH ); rootPanel.setLayout( new java.awt.BorderLayout( 3, 0 ) ); planBorder.setBorder( javax.swing.BorderFactory.createLineBorder( new java.awt.Color( 0, 0, 0 ) ) ); planBorder.setPreferredSize( new java.awt.Dimension( 200, 800 ) ); planBorder.setLayout( new java.awt.BorderLayout() ); planPanel.setBorder( javax.swing.BorderFactory.createEmptyBorder( 1, 1, 1, 1 ) ); javax.swing.GroupLayout planPanelLayout = new javax.swing.GroupLayout( planPanel ); planPanel.setLayout( planPanelLayout ); planPanelLayout.setHorizontalGroup( planPanelLayout.createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING ).addGap( 0, 276, Short.MAX_VALUE ) ); planPanelLayout.setVerticalGroup( planPanelLayout.createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING ).addGap( 0, 484, Short.MAX_VALUE ) ); planBorder.add( planPanel, java.awt.BorderLayout.CENTER ); showRootButton.setText( "root" ); showRootButton.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent evt ) { showRootBurronActionPerformed( evt ); } } ); importButton.setText( "import" ); importButton.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent evt ) { importButtonActionPerformed( evt ); } } ); exportButton.setText( "export" ); exportButton.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent evt ) { exportButtonActionPerformed( evt ); } } ); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout( jPanel2 ); jPanel2.setLayout( jPanel2Layout ); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING ).addGroup( jPanel2Layout.createSequentialGroup().addComponent( showRootButton ).addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED, 91, Short.MAX_VALUE ).addComponent( exportButton ).addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED ).addComponent( importButton ) ) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING ).addGroup( jPanel2Layout.createParallelGroup( javax.swing.GroupLayout.Alignment.BASELINE ).addComponent( showRootButton ).addComponent( importButton ).addComponent( exportButton ) ) ); planBorder.add( jPanel2, java.awt.BorderLayout.NORTH ); rootPanel.add( planBorder, java.awt.BorderLayout.CENTER ); jPanel5.setPreferredSize( new java.awt.Dimension( 450, 518 ) ); jPanel5.setLayout( new java.awt.GridLayout( 1, 2 ) ); profileBorder.setBorder( javax.swing.BorderFactory.createLineBorder( new java.awt.Color( 0, 0, 0 ) ) ); profileBorder.setPreferredSize( new java.awt.Dimension( 200, 300 ) ); profileBorder.setLayout( new java.awt.BorderLayout() ); jPanel1.setLayout( new java.awt.BorderLayout() ); addMachineButton.setText( "+" ); addMachineButton.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent evt ) { addMachineButtonActionPerformed( evt ); } } ); machineCombo.addItemListener( new java.awt.event.ItemListener() { public void itemStateChanged( java.awt.event.ItemEvent evt ) { machineComboItemStateChanged( evt ); } } ); javax.swing.GroupLayout profileCardLayout = new javax.swing.GroupLayout( profileCard ); profileCard.setLayout( profileCardLayout ); profileCardLayout.setHorizontalGroup( profileCardLayout.createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING ).addGroup( javax.swing.GroupLayout.Alignment.TRAILING, profileCardLayout.createSequentialGroup().addComponent( machineCombo, 0, 176, Short.MAX_VALUE ).addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED ).addComponent( addMachineButton ) ) ); profileCardLayout.setVerticalGroup( profileCardLayout.createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING ).addGroup( profileCardLayout.createParallelGroup( javax.swing.GroupLayout.Alignment.BASELINE ).addComponent( machineCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE ).addComponent( addMachineButton ) ) ); jPanel1.add( profileCard, java.awt.BorderLayout.CENTER ); profileBorder.add( jPanel1, java.awt.BorderLayout.NORTH ); javax.swing.GroupLayout profilePanelLayout = new javax.swing.GroupLayout( profilePanel ); profilePanel.setLayout( profilePanelLayout ); profilePanelLayout.setHorizontalGroup( profilePanelLayout.createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING ).addGap( 0, 223, Short.MAX_VALUE ) ); profilePanelLayout.setVerticalGroup( profilePanelLayout.createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING ).addGap( 0, 486, Short.MAX_VALUE ) ); profileBorder.add( profilePanel, java.awt.BorderLayout.CENTER ); jPanel5.add( profileBorder ); centralPanel.setPreferredSize( new java.awt.Dimension( 200, 800 ) ); centralPanel.setLayout( new java.awt.GridLayout( 0, 1 ) ); palettePanel.setLayout( new java.awt.GridLayout( 0, 1 ) ); centralPanel.add( palettePanel ); toolPanel.setBorder( javax.swing.BorderFactory.createLineBorder( new java.awt.Color( 0, 0, 0 ) ) ); toolPanel.setLayout( new java.awt.GridLayout( 1, 1 ) ); centralPanel.add( toolPanel ); jPanel5.add( centralPanel ); rootPanel.add( jPanel5, java.awt.BorderLayout.EAST ); // rootPanel.add( preview.getPanel(), java.awt.BorderLayout.WEST ); getContentPane().add( rootPanel, java.awt.BorderLayout.CENTER ); fileMenu.setText( "file" ); objDumpItem.setAccelerator( javax.swing.KeyStroke.getKeyStroke( java.awt.event.KeyEvent.VK_D, java.awt.event.InputEvent.CTRL_MASK ) ); objDumpItem.setText( "output obj" ); objDumpItem.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent evt ) { objDumpItemActionPerformed( evt ); } } ); fileMenu.add( objDumpItem ); meshItem.setAccelerator( javax.swing.KeyStroke.getKeyStroke( java.awt.event.KeyEvent.VK_M, java.awt.event.InputEvent.CTRL_MASK ) ); meshItem.setText( "add meshes" ); meshItem.setEnabled( false ); meshItem.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent evt ) { meshItemActionPerformed( evt ); } } ); fileMenu.add( meshItem ); jMenuBar1.add( fileMenu ); jMenu1.setText( "view" ); backgroundItem.setAccelerator( javax.swing.KeyStroke.getKeyStroke( java.awt.event.KeyEvent.VK_B, java.awt.event.InputEvent.CTRL_MASK ) ); backgroundItem.setText( "set background image" ); backgroundItem.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent evt ) { backgroundItemActionPerformed( evt ); } } ); jMenu1.add( backgroundItem ); clearImageButton.setText( "clear background image" ); clearImageButton.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent evt ) { clearImageButtonActionPerformed( evt ); } } ); jMenu1.add( clearImageButton ); jMenu3.setText( "grid" ); gridGroup.add( gridOff ); gridOff.setSelected( true ); gridOff.setText( "off" ); gridOff.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent evt ) { gridOffActionPerformed( evt ); } } ); jMenu3.add( gridOff ); gridGroup.add( gridSmall ); gridSmall.setText( "small" ); gridSmall.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent evt ) { gridSmallActionPerformed( evt ); } } ); jMenu3.add( gridSmall ); gridGroup.add( gridMedium ); gridMedium.setText( "medium" ); gridMedium.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent evt ) { gridMediumActionPerformed( evt ); } } ); jMenu3.add( gridMedium ); gridGroup.add( gridHuge ); gridHuge.setText( "big" ); gridHuge.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent evt ) { gridHugeActionPerformed( evt ); } } ); jMenu3.add( gridHuge ); jMenu1.add( jMenu3 ); jMenuBar1.add( jMenu1 ); jMenu2.setText( "plan" ); jMenu4.setText( "new plan" ); aPlanItem.setText( "animated plan" ); aPlanItem.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent evt ) { aPlanItemActionPerformed( evt ); } } ); jMenu4.add( aPlanItem ); pioneersPlanItem.setText( "pioneers demo mode" ); pioneersPlanItem.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent evt ) { pioneersPlanItemActionPerformed( evt ); } } ); jMenu4.add( pioneersPlanItem ); overhangPlanItem.setText( "overhang plan" ); overhangPlanItem.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent evt ) { overhangPlanItemActionPerformed( evt ); } } ); jMenu4.add( overhangPlanItem ); jMenu2.add( jMenu4 ); timeBackItem.setAccelerator( javax.swing.KeyStroke.getKeyStroke( java.awt.event.KeyEvent.VK_COMMA, 0 ) ); timeBackItem.setText( "time timeBackItem.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent evt ) { timeBackItemActionPerformed( evt ); } } ); jMenu2.add( timeBackItem ); timeForwardItem.setAccelerator( javax.swing.KeyStroke.getKeyStroke( java.awt.event.KeyEvent.VK_PERIOD, 0 ) ); timeForwardItem.setText( "time++" ); timeForwardItem.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent evt ) { timeForwardItemActionPerformed( evt ); } } ); jMenu2.add( timeForwardItem ); zeroTimeItem.setAccelerator( javax.swing.KeyStroke.getKeyStroke( java.awt.event.KeyEvent.VK_0, 0 ) ); zeroTimeItem.setText( "time to zero" ); zeroTimeItem.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent evt ) { zeroTimeItemActionPerformed( evt ); } } ); jMenu2.add( zeroTimeItem ); editClassifier.setAccelerator( javax.swing.KeyStroke.getKeyStroke( java.awt.event.KeyEvent.VK_K, java.awt.event.InputEvent.CTRL_MASK ) ); editClassifier.setText( "edit edge classifier" ); editClassifier.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent evt ) { editClassifierActionPerformed( evt ); } } ); jMenu2.add( editClassifier ); renderAnimItem.setText( "anim to .obj" ); renderAnimItem.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent evt ) { renderAnimItemActionPerformed( evt ); } } ); jMenu2.add( renderAnimItem ); jMenu2.add( jSeparator1 ); clearPlanItem.setText( "clear plan" ); clearPlanItem.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent evt ) { clearPlanItemActionPerformed( evt ); } } ); jMenu2.add( clearPlanItem ); svgImport.setText( "import svg plan..." ); svgImport.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent evt ) { svgImportActionPerformed( evt ); } } ); jMenu2.add( svgImport ); reversePlanItem.setText( "reverse plan direction" ); reversePlanItem.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent evt ) { reversePlanItemActionPerformed( evt ); } } ); jMenu2.add( reversePlanItem ); jMenuBar1.add( jMenu2 ); jMenu5.setText( "help" ); jMenu5.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent evt ) { jMenu5ActionPerformed( evt ); } } ); aboutItem.setAccelerator( javax.swing.KeyStroke.getKeyStroke( java.awt.event.KeyEvent.VK_F1, 0 ) ); aboutItem.setText( "about" ); aboutItem.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent evt ) { aboutItemActionPerformed( evt ); } } ); jMenu5.add( aboutItem ); jMenuBar1.add( jMenu5 ); setJMenuBar( jMenuBar1 ); pack(); }// </editor-fold>//GEN-END:initComponents private void machineComboItemStateChanged( java.awt.event.ItemEvent evt )//GEN-FIRST:event_machineComboItemStateChanged {//GEN-HEADEREND:event_machineComboItemStateChanged if ( !fireEvents ) return; Profile p = (Profile) machineCombo.getSelectedItem(); setProfile( p ); if ( p != null ) plan.profiles.put( selectedEdge, p ); repaint(); }//GEN-LAST:event_machineComboItemStateChanged private void addMachineButtonActionPerformed( java.awt.event.ActionEvent evt )//GEN-FIRST:event_addMachineButtonActionPerformed {//GEN-HEADEREND:event_addMachineButtonActionPerformed if ( selectedEdge == null ) { JOptionPane.showMessageDialog( this, "Please select an edge first, or middle click a plan to create one", "No selected edge", JOptionPane.ERROR_MESSAGE ); return; } Profile p = plan.createNewProfile( plan.profiles.get( selectedEdge ) ); plan.profiles.put( selectedEdge, p ); setProfile( p ); setupProfileCombo(); repaint(); }//GEN-LAST:event_addMachineButtonActionPerformed private void newFeatureButtonActionPerformed( java.awt.event.ActionEvent evt )//GEN-FIRST:event_newFeatureButtonActionPerformed {//GEN-HEADEREND:event_newFeatureButtonActionPerformed }//GEN-LAST:event_newFeatureButtonActionPerformed private void planComboActionPerformed( java.awt.event.ActionEvent evt )//GEN-FIRST:event_planComboActionPerformed {//GEN-HEADEREND:event_planComboActionPerformed if ( !fireEvents ) return; Object o = planCombo.getSelectedItem(); if ( o instanceof Tag ) { selectedTag = (Tag) o; if ( planUI != null ) planUI.repaint(); if ( o instanceof ForcedStep || o instanceof PillarFeature ) setTool( Tool.Anchor ); else setTool( Tool.Tag ); } }//GEN-LAST:event_planComboActionPerformed private void editPlanButtonActionPerformed( java.awt.event.ActionEvent evt )//GEN-FIRST:event_editPlanButtonActionPerformed {//GEN-HEADEREND:event_editPlanButtonActionPerformed setPlan( (Plan) planCombo.getSelectedItem() ); }//GEN-LAST:event_editPlanButtonActionPerformed private void meshItemActionPerformed( java.awt.event.ActionEvent evt )//GEN-FIRST:event_meshItemActionPerformed {//GEN-HEADEREND:event_meshItemActionPerformed if ( preview != null && output != null ) { preview.clear = true; show( output, (Skeleton) threadKey ); preview.display( output, true, true, true ); for ( PlanTag pt : plan.tags ) { pt.postProcess( output, preview, threadKey ); } ( (PlanSkeleton) output.skeleton ).addMeshesTo( preview ); // "this would be an eccumenical matter" // PlanSkeleton ps = (PlanSkeleton)threadKey; // if (ps.pillarFactory != null) // ps.pillarFactory.addTo (preview, threadKey); // if (ps.windowFactory != null) // ps.windowFactory.addTo (preview, threadKey); // if (ps.meshFactory != null) // ps.meshFactory.addTo (praview, threadKey); // JmeObjDump dump = new JmeObjDump(); // dump.add( preview.model ); // dump.allDone( new File ("out.obj")); } }//GEN-LAST:event_meshItemActionPerformed private void objDumpItemActionPerformed( java.awt.event.ActionEvent evt )//GEN-FIRST:event_objDumpItemActionPerformed {//GEN-HEADEREND:event_objDumpItemActionPerformed if ( preview != null ) preview.outputObj( this ); }//GEN-LAST:event_objDumpItemActionPerformed // public void addToOutput( Collection<Plan> plans, Object key, Tag roof ) // this.threadKey = key; // this.roof = roof; // preview.clear = true; // preview.threadKey = key; // Set<Face> allFaces = new HashSet(); // for ( Plan p : plans ) //plans.indexOf(p) // PlanSkeleton s = new PlanSkeleton( p ); // s.skeleton(); // if ( s.output.faces != null ) // preview.display( s.output ); // for ( Face f : s.output.faces.values() ) // if ( f.profile.contains( CampSkeleton.instance.roof ) ) // allFaces.add( f ); //allFaces.size() // // "this would be an eccumenical matter" // if ( s.pillarFactory != null ) // s.pillarFactory.addTo( preview, key ); // if ( s.windowFactory != null ) // s.windowFactory.addTo( preview, key ); // if ( s.meshFactory != null ) // s.meshFactory.addTo( preview, key ); // new Tiller( preview, allFaces, key ); boolean busy = false; private void goButtonActionPerformed( java.awt.event.ActionEvent evt )//GEN-FIRST:event_goButtonActionPerformed {//GEN-HEADEREND:event_goButtonActionPerformed if ( !busy ) { busy = true; dirty = false; goButton.setText( "[working]" ); new Thread() { @Override public void run() { try { DebugDevice.reset(); Skeleton s = new PlanSkeleton( plan ); s.skeleton(); if ( s.output.faces != null ) { Output output = s.output; show( output, s ); } // try { // Thread.sleep(200); // } catch (InterruptedException ex) { // ex.printStackTrace(); // while (preview.isPendingUpdate()); // preview.dump(new File ( "C:\\Users\\twak\\step_frames\\"+frame+".obj") ); } catch (Throwable th ) { th.printStackTrace(); } finally { busy = false; goButton.setText( GO ); // if something's changed since we started work, run again... if ( dirty ) SwingUtilities.invokeLater( new Runnable() { public void run() { goButtonActionPerformed( null ); } } ); } } }.start(); } }//GEN-LAST:event_goButtonActionPerformed // TODO add your handling code here: private void autoupdateButtomActionPerformed( java.awt.event.ActionEvent evt )//GEN-FIRST:event_autoupdateButtomActionPerformed {//GEN-HEADEREND:event_autoupdateButtomActionPerformed // autoup = autoupdateButtom.isSelected(); if ( autoupdateButtom.isSelected() ) somethingChanged(); }//GEN-LAST:event_autoupdateButtomActionPerformed private void newFeatureButtonMousePressed( java.awt.event.MouseEvent evt )//GEN-FIRST:event_newFeatureButtonMousePressed {//GEN-HEADEREND:event_newFeatureButtonMousePressed DefaultListModel dlm = new DefaultListModel(); abstract class Clickable { String name; public Clickable( String name ) { this.name = name; } public abstract Tag makeFeature(); @Override public String toString() { return name; } } dlm.addElement( new Clickable( "forced step" ) { @Override public Tag makeFeature() { return new ForcedStep( plan ); } } ); final JList list = new JList( dlm ); Point pt = evt.getPoint(); pt = SwingUtilities.convertPoint( newFeatureButton, pt, null ); final Popup pop = PopupFactory.getSharedInstance().getPopup( this, list, pt.x + getX(), pt.y + getY() ); pop.show(); list.addMouseListener( new MouseAdapter() { @Override public void mouseExited( MouseEvent e ) { pop.hide(); } } ); list.getSelectionModel().addListSelectionListener( new ListSelectionListener() { public void valueChanged( ListSelectionEvent e ) { Object o = list.getSelectedValue(); if ( o != null && o instanceof Clickable ) { // adds to plan! ( (Clickable) o ).makeFeature(); } pop.hide(); } } ); } enum PlaybackStatus { PLAY, PAUSE } PlaybackStatus playbackStatus = PlaybackStatus.PAUSE; PlaybackThread playbackThread; public class PlaybackThread extends Thread { public boolean run = false; @Override public void run() { while ( true ) { try { if ( run && !busy ) SwingUtilities.invokeLater( new Runnable() { @Override public void run() { int nF = frame + 1; if ( nF > 100 ) nF = 0; if ( jToggleButton1.isSelected() ) { nF = (int) ( Math.random() * 100 ); } update( nF ); } } ); Thread.sleep( 1000 ); } catch ( Throwable th ) { th.printStackTrace(); } } } } public void togglePlaybackStatus() { if (playbackThread == null) { playbackThread = new PlaybackThread(); playbackThread.start(); } if ( playbackStatus == PlaybackStatus.PLAY ) playbackStatus = playbackStatus.PAUSE; else playbackStatus = playbackStatus.PLAY; playbackThread.run = playbackStatus == playbackStatus.PLAY; }//GEN-LAST:event_newFeatureButtonMousePressed private void showRootBurronActionPerformed( java.awt.event.ActionEvent evt ) {//GEN-FIRST:event_showRootBurronActionPerformed showRoot(); }//GEN-LAST:event_showRootBurronActionPerformed File currentFolder = new File( "." ); private void backgroundItemActionPerformed( java.awt.event.ActionEvent evt )//GEN-FIRST:event_backgroundItemActionPerformed {//GEN-HEADEREND:event_backgroundItemActionPerformed new SimpleFileChooser( this, false, "select background image" ) { @Override public void heresTheFile( File f ) throws Throwable { setImage( ImageIO.read( f ) ); } }; }//GEN-LAST:event_backgroundItemActionPerformed private void clearImageButtonActionPerformed( java.awt.event.ActionEvent evt )//GEN-FIRST:event_clearImageButtonActionPerformed {//GEN-HEADEREND:event_clearImageButtonActionPerformed setImage( null ); }//GEN-LAST:event_clearImageButtonActionPerformed private void exportButtonActionPerformed( java.awt.event.ActionEvent evt )//GEN-FIRST:event_exportButtonActionPerformed {//GEN-HEADEREND:event_exportButtonActionPerformed new SimpleFileChooser( this, true, "save feature info" ) { @Override public void heresTheFile( File f ) { planUI.exportt( f ); } }; }//GEN-LAST:event_exportButtonActionPerformed private void importButtonActionPerformed( java.awt.event.ActionEvent evt )//GEN-FIRST:event_importButtonActionPerformed {//GEN-HEADEREND:event_importButtonActionPerformed new SimpleFileChooser( this, false, "load feature info" ) { @Override public void heresTheFile( File f ) { planUI.importt( f ); } }; }//GEN-LAST:event_importButtonActionPerformed private void gridOffActionPerformed( java.awt.event.ActionEvent evt )//GEN-FIRST:event_gridOffActionPerformed {//GEN-HEADEREND:event_gridOffActionPerformed setGrid( -1 ); }//GEN-LAST:event_gridOffActionPerformed private void gridSmallActionPerformed( java.awt.event.ActionEvent evt )//GEN-FIRST:event_gridSmallActionPerformed {//GEN-HEADEREND:event_gridSmallActionPerformed setGrid( 1 ); }//GEN-LAST:event_gridSmallActionPerformed private void gridMediumActionPerformed( java.awt.event.ActionEvent evt )//GEN-FIRST:event_gridMediumActionPerformed {//GEN-HEADEREND:event_gridMediumActionPerformed setGrid( 5 ); }//GEN-LAST:event_gridMediumActionPerformed private void gridHugeActionPerformed( java.awt.event.ActionEvent evt )//GEN-FIRST:event_gridHugeActionPerformed {//GEN-HEADEREND:event_gridHugeActionPerformed setGrid( 10 ); }//GEN-LAST:event_gridHugeActionPerformed private void setMachineButtonActionPerformed( java.awt.event.ActionEvent evt )//GEN-FIRST:event_setMachineButtonActionPerformed {//GEN-HEADEREND:event_setMachineButtonActionPerformed Profile p = (Profile) machineCombo.getSelectedItem(); if ( p != null ) plan.profiles.put( selectedEdge, p ); repaint(); }//GEN-LAST:event_setMachineButtonActionPerformed private void timeBackItemActionPerformed( java.awt.event.ActionEvent evt )//GEN-FIRST:event_timeBackItemActionPerformed {//GEN-HEADEREND:event_timeBackItemActionPerformed update( frame - 1 ); }//GEN-LAST:event_timeBackItemActionPerformed private void zeroTimeItemActionPerformed( java.awt.event.ActionEvent evt )//GEN-FIRST:event_zeroTimeItemActionPerformed {//GEN-HEADEREND:event_zeroTimeItemActionPerformed update( 0 ); }//GEN-LAST:event_zeroTimeItemActionPerformed private void timeForwardItemActionPerformed( java.awt.event.ActionEvent evt )//GEN-FIRST:event_timeForwardItemActionPerformed {//GEN-HEADEREND:event_timeForwardItemActionPerformed update( frame + ( evt.getModifiers() != 0 ? 10 : 1 ) ); }//GEN-LAST:event_timeForwardItemActionPerformed private void renderAnimItemActionPerformed( java.awt.event.ActionEvent evt )//GEN-FIRST:event_renderAnimItemActionPerformed {//GEN-HEADEREND:event_renderAnimItemActionPerformed new RenderAnimFrame(); }//GEN-LAST:event_renderAnimItemActionPerformed private void aPlanItemActionPerformed( java.awt.event.ActionEvent evt )//GEN-FIRST:event_aPlanItemActionPerformed {//GEN-HEADEREND:event_aPlanItemActionPerformed setPlan( new APlanBoxes() ); frame = 0; update( 1 ); update( 0 ); }//GEN-LAST:event_aPlanItemActionPerformed private void svgImportActionPerformed( java.awt.event.ActionEvent evt )//GEN-FIRST:event_svgImportActionPerformed {//GEN-HEADEREND:event_svgImportActionPerformed new SimpleFileChooser( this, false, "select svg to import as plan" ) { @Override public void heresTheFile( File f ) throws Throwable { // new ImportSVG( f, plan ); planUI.repaint(); } }; }//GEN-LAST:event_svgImportActionPerformed private void reversePlanItemActionPerformed( java.awt.event.ActionEvent evt )//GEN-FIRST:event_reversePlanItemActionPerformed {//GEN-HEADEREND:event_reversePlanItemActionPerformed Bar.reverse( plan.points ); planUI.repaint(); somethingChanged(); }//GEN-LAST:event_reversePlanItemActionPerformed private void clearPlanItemActionPerformed( java.awt.event.ActionEvent evt )//GEN-FIRST:event_clearPlanItemActionPerformed {//GEN-HEADEREND:event_clearPlanItemActionPerformed plan.points.clear(); planUI.repaint(); somethingChanged(); }//GEN-LAST:event_clearPlanItemActionPerformed private void editClassifierActionPerformed( java.awt.event.ActionEvent evt )//GEN-FIRST:event_editClassifierActionPerformed {//GEN-HEADEREND:event_editClassifierActionPerformed // if (plan.buildFromPlan != null) // plan.buildFromPlan.showUI(); // else JOptionPane.showMessageDialog( this, "Must be using a procedural floorplan", "Null editor not available", JOptionPane.ERROR_MESSAGE ); }//GEN-LAST:event_editClassifierActionPerformed private void pioneersPlanItemActionPerformed( java.awt.event.ActionEvent evt ) {//GEN-FIRST:event_pioneersPlanItemActionPerformed setPlan( new PioneerPlan() ); frame = 0; update( 0 ); }//GEN-LAST:event_pioneersPlanItemActionPerformed private void playButtonActionPerformed( java.awt.event.ActionEvent evt ) {//GEN-FIRST:event_playButtonActionPerformed togglePlaybackStatus(); if ( playbackStatus == PlaybackStatus.PAUSE ) playButton.setText( ">" ); else playButton.setText( "||" ); }//GEN-LAST:event_playButtonActionPerformed private void jToggleButton1ActionPerformed( java.awt.event.ActionEvent evt ) {//GEN-FIRST:event_jToggleButton1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jToggleButton1ActionPerformed private void jMenu5ActionPerformed( java.awt.event.ActionEvent evt ) {//GEN-FIRST:event_jMenu5ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jMenu5ActionPerformed private void aboutItemActionPerformed( java.awt.event.ActionEvent evt ) {//GEN-FIRST:event_aboutItemActionPerformed new AboutBox(); }//GEN-LAST:event_aboutItemActionPerformed private void overhangPlanItemActionPerformed( java.awt.event.ActionEvent evt ) {//GEN-FIRST:event_overhangPlanItemActionPerformed setPlan( new OverhangPlan() ); frame = 0; update( 0 ); }//GEN-LAST:event_overhangPlanItemActionPerformed private void frameSpinnerStateChanged( javax.swing.event.ChangeEvent evt ) {//GEN-FIRST:event_frameSpinnerStateChanged update( (Integer) frameSpinner.getValue() ); }//GEN-LAST:event_frameSpinnerStateChanged public static void main( String[] args ) { WindowManager.init( "siteplan", "/org/twak/siteplan/resources/icon256.png" ); try { UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() ); } catch ( Throwable ex ) { ex.printStackTrace(); } Siteplan cs = new Siteplan(); cs.setVisible( true ); WindowManager.register( cs ); // debug - show diaglog // CampSkeleton.instance.aPlanItemActionPerformed( null ); // CampSkeleton.instance.editClassifierActionPerformed( null ); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JMenuItem aPlanItem; private javax.swing.JMenuItem aboutItem; private javax.swing.JButton addMachineButton; private javax.swing.JToggleButton autoupdateButtom; private javax.swing.JMenuItem backgroundItem; private javax.swing.JPanel centralPanel; private javax.swing.JMenuItem clearImageButton; private javax.swing.JMenuItem clearPlanItem; private javax.swing.JMenuItem editClassifier; private javax.swing.JButton editPlanButton; private javax.swing.JButton exportButton; private javax.swing.JMenu fileMenu; private javax.swing.JSpinner frameSpinner; private javax.swing.JButton goButton; private javax.swing.ButtonGroup gridGroup; private javax.swing.JRadioButtonMenuItem gridHuge; private javax.swing.JRadioButtonMenuItem gridMedium; private javax.swing.JRadioButtonMenuItem gridOff; private javax.swing.JRadioButtonMenuItem gridSmall; private javax.swing.JButton importButton; private javax.swing.JMenu jMenu1; private javax.swing.JMenu jMenu2; private javax.swing.JMenu jMenu3; private javax.swing.JMenu jMenu4; private javax.swing.JMenu jMenu5; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel rootPanel; private javax.swing.JPanel jPanel5; private javax.swing.JPopupMenu.Separator jSeparator1; private javax.swing.JToggleButton jToggleButton1; private javax.swing.JComboBox machineCombo; private javax.swing.JMenuItem meshItem; private javax.swing.JButton newFeatureButton; private javax.swing.JMenuItem objDumpItem; private javax.swing.JMenuItem overhangPlanItem; private javax.swing.ButtonGroup paletteGroup; private javax.swing.JPanel palettePanel; private javax.swing.JMenuItem pioneersPlanItem; private javax.swing.JPanel planBorder; private javax.swing.JComboBox planCombo; private javax.swing.JPanel planPanel; private javax.swing.JButton playButton; private javax.swing.JPanel profileBorder; private javax.swing.JPanel profileCard; private javax.swing.JPanel profilePanel; private javax.swing.JMenuItem renderAnimItem; private javax.swing.JMenuItem reversePlanItem; private javax.swing.JButton setMachineButton; private javax.swing.JButton showRootButton; private javax.swing.JLabel statusLabel; private javax.swing.JMenuItem svgImport; private javax.swing.JMenuItem timeBackItem; private javax.swing.JMenuItem timeForwardItem; private javax.swing.JPanel toolPanel; private javax.swing.JMenuItem zeroTimeItem; // End of variables declaration//GEN-END:variables /** * Bootstrap method - template should come from file? */ public static LoopL<Bar> createCircularPoints( int count, int x, int y, int rad, Profile profile, Plan plan ) { double delta = Math.PI * 2 / count; LoopL<Bar> loopl = new LoopL(); Loop<Bar> loop = new Loop(); loopl.add( loop ); Point2d prev = null, start = null; // boolean odd = true; for ( int i = 0; i < count; i++ ) { Point2d c = new Point2d( x + (int) ( Math.cos( ( i - 0.5 ) * delta ) * rad ), y + (int) ( Math.sin( ( i - 0.5 ) * delta ) * rad ) ); if ( prev != null ) { Bar e = new Bar( prev, c ); loop.append( e ); plan.profiles.put( e, profile ); } else start = c; prev = c; // odd = !odd; // if (odd) // double r = Math.sqrt( 2* rad* rad - 2 * rad * rad * Math.cos (Math.PI/8) ); // double d2 = r * Math.sin( Math.toRadians( 135 )) / (Math.cos (Math.toRadians( 45)) * Math.sin (Math.toRadians( 45./2. ))); // Point2d d = new Point2d( // x + (int) ( Math.cos( (i+0.5) * delta ) * d2/2 ), // y + (int) ( Math.sin( (i+0.5) * delta ) * d2/2 ) ); // Bar e = new Bar (prev, d); // loop.append(e); // plan.profiles.put(e,profile); // prev = d; } Bar e = new Bar( prev, start ); loop.append( e ); plan.profiles.put( e, profile ); return loopl; } public static LoopL<Bar> createfourSqaures( Plan plan, Profile profile ) { LoopL<Bar> loopl = new LoopL(); List<Point2d> pts = Arrays.asList( // new Point2d (100, 250), // new Point2d (250,250), // new Point2d (250,100), // new Point2d (350,100), // new Point2d (400,600) new Point2d( 0, 0 ), new Point2d( -50, 0 ), new Point2d( -50, -50 ), new Point2d( 0, -50 ) ); // for (Point2d p : pts) // p.scale( 0.3 ); List<List<Point2d>> stp = new ArrayList(); for ( Point2d offset : new Point2d[] { new Point2d( 0, 150 ), new Point2d( 0, -150 ), new Point2d( 150, 0 ), new Point2d( -150, 0 ) } ) { List<Point2d> t = new ArrayList(); stp.add( t ); for ( Point2d pt : pts ) t.add( new Point2d( offset.x + pt.x, offset.y + pt.y ) ); } for ( List<Point2d> pts2 : stp ) { Loop<Bar> loop = new Loop(); loopl.add( loop ); for ( Pair<Point2d, Point2d> pair : new ConsecutivePairs<Point2d>( pts2, true ) ) { Bar b; loop.append( b = new Bar( pair.first(), pair.second() ) ); plan.profiles.put( b, profile ); } } return loopl; } public static void createCross( Plan plan, Profile profile ) { LoopL<Bar> loopl = new LoopL(); Loop<Bar> loop = new Loop(); loopl.add( loop ); List<Point2d> pts = Arrays.asList( // new Point2d (100, 250), // new Point2d (250,250), // new Point2d (250,100), // new Point2d (350,100), // new Point2d (400,600) new Point2d( 250, 100 ), new Point2d( 350, 100 ), new Point2d( 350, 250 ), new Point2d( 500, 250 ), new Point2d( 500, 350 ), new Point2d( 350, 350 ), new Point2d( 350, 500 ), new Point2d( 250, 500 ), new Point2d( 250, 350 ), new Point2d( 100, 350 ), new Point2d( 100, 250 ), new Point2d( 250, 250 ) ); for ( Point2d p : pts ) p.scale( 0.3 ); for ( Pair<Point2d, Point2d> pair : new ConsecutivePairs<Point2d>( pts, true ) ) { Bar b; loop.append( b = new Bar( pair.first(), pair.second() ) ); plan.profiles.put( b, profile ); } plan.points = loopl; } /** * Debug locations, only use this method before the skeleton is complete * * @param mat */ List<Spatial> markers = new ArrayList(); public void addDebugMarker( Matrix4d mat ) { Point3d loc = Jme.convert( new Vector3d( mat.getM03(), mat.getM13(), mat.getM23() ) ); System.out.println( mat ); System.out.println( loc ); Box box = new Box( new Vector3f( (float) loc.x, (float) loc.y, (float) loc.z ), 0.3f, 0.3f, 0.3f ); } /** * Thread key ensures that only additional meshes (tiles, pillars) that were * designed for the current input are added */ Output output; public void show( Output output, Skeleton threadKey ) { this.threadKey = threadKey; meshItem.setEnabled( true ); this.output = output; if ( preview != null ) // might take a while... { preview.clear = true; Point2d pt = getMiddle( plan.points ); preview.display( output, true, true, true ); // preview.setViewStats( pt.x / Jme.scale, threadKey.height / Jme.scale, pt.y / Jme.scale, threadKey ); // if ( !markers.isEmpty() ) { // for ( Spatial s : markers ) // preview.display( s, threadKey ); markers.clear(); } } public static Point2d getMiddle( LoopL<Bar> plan ) { Point2d middle = new Point2d(); int count = 0; for ( Bar b : plan.eIterator() ) { middle.add( b.start ); count++; } middle.scale( 1. / count ); return middle; } public static void removeParallel( LoopL<Bar> loopL ) { Set<Bar> toRemove = new HashSet(); for ( Loop<Bar> loop : loopL ) { Bar last = loop.start.getPrev().get(); for ( Bar e : loop ) if ( e.start.distance( e.end ) < 0.1 ) { // remove current toRemove.add( e ); last.end = e.end; // last.end.nextC = e.end.nextC; // e.end.nextC.prevC = last.end; // last.end.nextL = e.end.nextL; } else last = e; for ( Bar e : toRemove ) loop.remove( e ); } } public void addedBar( Bar bar ) { } }
package com.jayantkrish.jklol.ccg.lambda2; import java.io.Serializable; import java.util.Arrays; import java.util.List; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.primitives.Ints; public class Expression2 implements Serializable, Comparable<Expression2> { private static final long serialVersionUID = 1L; protected final String constantName; protected final List<Expression2> subexpressions; protected final int size; private Expression2(String constantName, List<Expression2> subexpressions, int size) { Preconditions.checkArgument(constantName == null || subexpressions == null); this.constantName = constantName; this.subexpressions = subexpressions; this.size = size; } public static Expression2 constant(String constantName) { return new Expression2(constantName, null, 1); } public static Expression2 stringValue(String value) { return new Expression2("\"" + value.replaceAll("\"", "\\\\\"") + "\"", null, 1); } public static List<Expression2> constants(List<String> constantNames) { List<Expression2> constants = Lists.newArrayList(); for (String constantName : constantNames) { constants.add(Expression2.constant(constantName)); } return constants; } public static List<Expression2> stringValues(List<String> values) { List<Expression2> constants = Lists.newArrayList(); for (String value : values) { constants.add(Expression2.stringValue(value)); } return constants; } public static Expression2 nested(Expression2... subexpressions) { return nested(Arrays.asList(subexpressions)); } public static Expression2 nested(List<Expression2> subexpressions) { int size = 1; for (Expression2 subexpression : subexpressions) { size += subexpression.size(); } return new Expression2(null, ImmutableList.copyOf(subexpressions), size); } public static Expression2 lambda(List<String> argNames, Expression2 body) { List<Expression2> lambdaBody = Lists.newArrayList(); lambdaBody.add(Expression2.constant(StaticAnalysis.LAMBDA)); lambdaBody.add(Expression2.nested(Expression2.constants(argNames))); lambdaBody.add(body); return Expression2.nested(lambdaBody); } public boolean isConstant() { return constantName != null; } public String getConstant() { return constantName; } public boolean isStringValue() { return constantName != null && constantName.matches("\".*\""); } public String getStringValue() { if (isStringValue()) { return constantName.substring(1, constantName.length()-1).replaceAll("\\\\\"", "\""); } else { return null; } } public List<Expression2> getSubexpressions() { return subexpressions; } public int size() { return size; } private int[] findSubexpression(int index) { Preconditions.checkArgument(index < size, "Cannot get index %s of expression %s", index, this); int startIndex = 1; for (int i = 0; i < subexpressions.size(); i++) { Expression2 subexpression = subexpressions.get(i); int endIndex = startIndex + subexpression.size(); if (index < endIndex) { return new int[] {i, index - startIndex, startIndex}; } else { startIndex += subexpression.size(); } } // This should never happen due to the preconditions // check at the beginning. throw new IllegalArgumentException("Something bad happened."); } /** * Gets the subexpression of {@code this} at position * {@code index} in the syntax tree. Index 0 always * returns {@code this}. * * @param index * @return */ public Expression2 getSubexpression(int index) { Preconditions.checkArgument(index < size); if (index == 0) { return this; } else { int[] parts = findSubexpression(index); return subexpressions.get(parts[0]).getSubexpression(parts[1]); } } /** * Get the index of the parent expression that contains the given index. * Returns -1 if the indexed expression has no parent. * * @param index * @return */ public int getParentExpressionIndex(int index) { if (index == 0) { return -1; } else { int[] parts = findSubexpression(index); int parentIndex = subexpressions.get(parts[0]).getParentExpressionIndex(parts[1]); if (parentIndex == -1) { // index refers to a child of this expression. return 0; } else { // Return the index into this expression of the chosen child, // plus the index into that expression. return parentIndex + parts[2]; } } } /** * Gets an array of indexes to the children of the expression * given by {@code index}. * * @param index * @return */ public int[] getChildIndexes(int index) { if (index == 0) { if (isConstant()) { return new int[0]; } else { int[] result = new int[subexpressions.size()]; int startIndex = 1; for (int i = 0; i < subexpressions.size(); i++) { result[i] = startIndex; startIndex += subexpressions.get(i).size(); } return result; } } else { int[] parts = findSubexpression(index); int[] result = subexpressions.get(parts[0]).getChildIndexes(parts[1]); for (int i = 0; i < result.length; i++) { result[i] += parts[2]; } return result; } } /** * Gets the depth of the subexpression pointed to by {@code index} * in the tree. The root is at depth of 0, each of its children * at depth 1, etc. * * @param index * @return */ public int getDepth(int index) { if (index == 0) { return 0; } else { int[] parts = findSubexpression(index); return 1 + subexpressions.get(parts[0]).getDepth(parts[1]); } } /** * Replaces the expression at {@code index} in this expression * with {@code newConstantExpression} (as a constant expression). * * @param index * @param newConstantExpression * @return */ public Expression2 substitute(int index, String newConstantExpression) { return substitute(index, Expression2.constant(newConstantExpression)); } /** * Replaces the expression at {@code index} in this expression * with {@code newExpression}. * * @param index * @param newExpression * @return */ public Expression2 substitute(int index, Expression2 newExpression) { Preconditions.checkArgument(index < size); if (index == 0) { return newExpression; } else { int[] parts = findSubexpression(index); Expression2 substituted = subexpressions.get(parts[0]).substitute(parts[1], newExpression); List<Expression2> newSubexpressions = Lists.newArrayList(subexpressions); newSubexpressions.set(parts[0], substituted); return Expression2.nested(newSubexpressions); } } /** * Replaces all occurrences of {@code value} in this * expression with {@code replacement}. * * @param value * @param replacement * @return */ public Expression2 substitute(String value, String replacement) { return substitute(Expression2.constant(value), Expression2.constant(replacement)); } /** * Replaces all occurrences of {@code value} in this * expression with {@code replacement}. * * @param value * @param replacement * @return */ public Expression2 substitute(String value, Expression2 replacement) { return substitute(Expression2.constant(value), replacement); } /** * Replaces all occurrences of {@code value} in this * expression with {@code replacement}. * * @param value * @param replacement * @return */ public Expression2 substitute(Expression2 value, Expression2 replacement) { if (this.equals(value)) { return replacement; } else if (this.isConstant()) { return this; } else { List<Expression2> newSubexpressions = Lists.newArrayList(); for (Expression2 sub : subexpressions) { newSubexpressions.add(sub.substitute(value, replacement)); } return Expression2.nested(newSubexpressions); } } public Expression2 substituteInline(String value, List<Expression2> replacement) { if (this.isConstant()) { return this; } else { List<Expression2> newSubexpressions = Lists.newArrayList(); for (Expression2 sub : subexpressions) { if (sub.isConstant() && sub.getConstant().equals(value)) { newSubexpressions.addAll(replacement); } else { newSubexpressions.add(sub.substituteInline(value, replacement)); } } return Expression2.nested(newSubexpressions); } } /** * Returns {@code true} if this expression contains {@code subexpression}. * * @param subexpression * @return */ public boolean hasSubexpression(Expression2 subexpression) { return find(subexpression) >= 0; } /** * Returns the index of the first occurrence of {@code expression} * within {@code this} expression. Returns -1 if {@code expression} * is not found. * * @param expression * @return */ public int find(Expression2 expression) { return findHelper(expression, 0); } public int[] findAll(Expression2 expression) { List<Integer> indexes = Lists.newArrayList(); for (int i = 0; i < size(); i++) { Expression2 sub = getSubexpression(i); if (sub.equals(expression)) { indexes.add(i); } } return Ints.toArray(indexes); } private int findHelper(Expression2 expression, int index) { if (this.equals(expression)) { return index; } else if (this.isConstant()) { return -1; } else { int[] childIndexes = getChildIndexes(0); for (int i = 0; i < subexpressions.size(); i++) { int subexpressionIndex = subexpressions.get(i).findHelper(expression, childIndexes[i]); if (subexpressionIndex >= 0) { return subexpressionIndex; } } return -1; } } @Override public String toString() { if (isConstant()) { return constantName; } else { return "(" + Joiner.on(" ").join(subexpressions) + ")"; } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((constantName == null) ? 0 : constantName.hashCode()); result = prime * result + size; result = prime * result + ((subexpressions == null) ? 0 : subexpressions.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Expression2 other = (Expression2) obj; if (size != other.size) return false; if (constantName == null) { if (other.constantName != null) return false; } else if (!constantName.equals(other.constantName)) return false; if (subexpressions == null) { if (other.subexpressions != null) return false; } else if (!subexpressions.equals(other.subexpressions)) return false; return true; } @Override public int compareTo(Expression2 arg0) { return this.toString().compareTo(arg0.toString()); } }
package ar.renderers; import java.awt.Rectangle; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.RecursiveTask; import ar.Aggregates; import ar.Aggregator; import ar.Glyph; import ar.Glyphset; import ar.aggregates.ConstantAggregates; import ar.aggregates.FlatAggregates; import ar.util.Util; import ar.Renderer; import ar.Transfer; /**Task-stealing renderer that works on a per-glyph basis, designed for use with a linear stored glyph-set. * Iterates the glyphs and produces many aggregate sets that are then combined * (i.e., glyph-driven iteration). */ public class ParallelGlyphs implements Renderer { private static final long serialVersionUID = 1103433143653202677L; /**Default task size for parallel operations.**/ public static int DEFAULT_TASK_SIZE = 100000; /**Thread pool size used for parallel operations.**/ public static int THREAD_POOL_SIZE = Runtime.getRuntime().availableProcessors(); private final ForkJoinPool pool = new ForkJoinPool(THREAD_POOL_SIZE); private final int taskSize; private final RenderUtils.Progress recorder = RenderUtils.recorder(); /**Render with task-size determined by DEFAULT_TASK_SIZE.**/ public ParallelGlyphs() {this(DEFAULT_TASK_SIZE);} /**Render with task-size determined by the passed parameter.**/ public ParallelGlyphs(int taskSize) { this.taskSize = taskSize; } protected void finalize() {pool.shutdownNow();} @Override public <V,A> Aggregates<A> aggregate(Glyphset<? extends V> glyphs, Aggregator<V,A> op, AffineTransform inverseView, int width, int height) { AffineTransform view; try {view = inverseView.createInverse();} catch (Exception e) {throw new RuntimeException("Error inverting the inverse-view transform....");} recorder.reset(glyphs.size()); ReduceTask<V,A> t = new ReduceTask<V,A>( glyphs, view, op, width, height, taskSize, recorder, 0, glyphs.segments()); Aggregates<A> a= pool.invoke(t); return a; } public <IN,OUT> Aggregates<OUT> transfer(Aggregates<? extends IN> aggregates, Transfer<IN,OUT> t) { return new SerialSpatial().transfer(aggregates, t); } public double progress() {return recorder.percent();} private static final class ReduceTask<V,A> extends RecursiveTask<Aggregates<A>> { private static final long serialVersionUID = 705015978061576950L; private final int taskSize; private final long low; private final long high; private final Glyphset<? extends V> glyphs; private final AffineTransform view; private final int width; private final int height; private final Aggregator<V,A> op; private final RenderUtils.Progress recorder; public ReduceTask(Glyphset<? extends V> glyphs, AffineTransform view, Aggregator<V,A> op, int width, int height, int taskSize, RenderUtils.Progress recorder, long low, long high) { this.glyphs = glyphs; this.view = view; this.op = op; this.width = width; this.height = height; this.taskSize = taskSize; this.recorder = recorder; this.low = low; this.high = high; } protected Aggregates<A> compute() { if ((high-low) > taskSize) {return split();} else {return local();} } private final Aggregates<A> split() { long mid = low+((high-low)/2); ReduceTask<V,A> top = new ReduceTask<V,A>(glyphs, view, op, width,height, taskSize, recorder, low, mid); ReduceTask<V,A> bottom = new ReduceTask<V,A>(glyphs, view, op, width,height, taskSize, recorder, mid, high); invokeAll(top, bottom); Aggregates<A> aggs = AggregationStrategies.horizontalRollup(top.getRawResult(), bottom.getRawResult(), op); return aggs; } //TODO: Consider the actual shape. Currently assumes that the bounds box matches the actual item bounds.. private final Aggregates<A> local() { Glyphset<? extends V> subset = glyphs.segment(low, high); Rectangle bounds = view.createTransformedShape(Util.bounds(subset)).getBounds(); bounds = bounds.intersection(new Rectangle(0,0,width,height)); if (bounds.isEmpty()) { int x2 = bounds.x+bounds.width; int y2 = bounds.y+bounds.height; return new ConstantAggregates<A>(Math.min(x2, bounds.x), Math.min(y2, bounds.y), Math.max(x2, bounds.x), Math.min(y2, bounds.y), op.identity()); } Aggregates<A> aggregates = new FlatAggregates<A>(bounds.x, bounds.y, bounds.x+bounds.width, bounds.y+bounds.height, op.identity()); Point2D lowP = new Point2D.Double(); Point2D highP = new Point2D.Double(); int count=0; for (Glyph<? extends V> g: subset) { //Discretize the glyph into the aggregates array Rectangle2D b = g.shape().getBounds2D(); lowP.setLocation(b.getMinX(), b.getMinY()); highP.setLocation(b.getMaxX(), b.getMaxY()); view.transform(lowP, lowP); view.transform(highP, highP); int lowx = (int) Math.floor(lowP.getX()); int lowy = (int) Math.floor(lowP.getY()); int highx = (int) Math.ceil(highP.getX()); int highy = (int) Math.ceil(highP.getY()); V v = g.value(); for (int x=Math.max(0,lowx); x<highx && x<width; x++){ for (int y=Math.max(0, lowy); y<highy && y<height; y++) { A existing = aggregates.get(x,y); A update = op.combine(x,y,existing, v); aggregates.set(x, y, update); } } count++; } recorder.update(count); return aggregates; } } }
package com.nokia.dempsy; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.junit.Ignore; import com.nokia.dempsy.config.ClusterId; import com.nokia.dempsy.mpcluster.MpCluster; import com.nokia.dempsy.mpcluster.MpClusterException; import com.nokia.dempsy.mpcluster.MpClusterSession; import com.nokia.dempsy.mpcluster.MpClusterSlot; import com.nokia.dempsy.router.ClusterInformation; import com.nokia.dempsy.router.DefaultRoutingStrategy; import com.nokia.dempsy.router.SlotInformation; @Ignore public class TestUtils { public static interface Condition<T> { public boolean conditionMet(T o); } public static <T> boolean poll(long timeoutMillis, T userObject, Condition<T> condition) throws InterruptedException { for (long endTime = System.currentTimeMillis() + timeoutMillis; endTime > System.currentTimeMillis() && !condition.conditionMet(userObject);) Thread.sleep(1); return condition.conditionMet(userObject); } public static boolean waitForClustersToBeInitialized(long timeoutMillis, final int numSlotsPerCluster, Dempsy dempsy) throws InterruptedException { try { final List<ClusterId> clusters = new ArrayList<ClusterId>(); // find out all of the ClusterIds for (Dempsy.Application app : dempsy.applications) { for (Dempsy.Application.Cluster cluster : app.appClusters) if (!cluster.clusterDefinition.isRouteAdaptorType()) clusters.add(new ClusterId(cluster.clusterDefinition.getClusterId())); } MpClusterSession<ClusterInformation, SlotInformation> session = dempsy.clusterSessionFactory.createSession(); boolean ret = poll(timeoutMillis, session, new Condition<MpClusterSession<ClusterInformation, SlotInformation>>() { @Override public boolean conditionMet(MpClusterSession<ClusterInformation, SlotInformation> session) { try { for (ClusterId c : clusters) { MpCluster<ClusterInformation, SlotInformation> cluster = session.getCluster(c); Collection<MpClusterSlot<SlotInformation>> slots = cluster.getActiveSlots(); if (slots == null || slots.size() != numSlotsPerCluster) return false; } } catch(MpClusterException e) { return false; } return DefaultRoutingStrategy.allOutboundsInitialized(); } }); session.stop(); return ret; } catch (MpClusterException e) { return false; } } }
package com.menny.android.anysoftkeyboard; import java.lang.reflect.Field; import android.util.Log; import android.view.inputmethod.EditorInfo; public class Workarounds { //Determine whether this device has the fix for RTL in the suggestions list private static final boolean ms_requiresRtlWorkaround; private static final boolean ms_isDonut; private static final boolean ms_isEclair; private static final String TAG = "ASK Workaround"; static { //checking f/w API is a bit tricky, we need to do it by reflection boolean isDonut = false; boolean isEclair = false; int sdkVersion = 1; try { Field sdkInt = android.os.Build.VERSION.class.getField("SDK_INT"); if (sdkInt != null) { //NOTE: I can not use the field here, since this code MAY run in cupcake, and therefore //fail in JIT compile. I need to perform this function with reflection... sdkVersion = sdkInt.getInt(null); isDonut = (sdkVersion >= 4); isEclair = (sdkVersion >= 5); } } catch(Exception ex) { } ms_isDonut = isDonut; ms_isEclair = isEclair; boolean requiresRtlWorkaround = true;//all devices required this fix (in 2.1 it is still required) //from 2.1 we'll default to RTL supported! //but there are many versions which patched it. //it is fixed in 2.2 if (sdkVersion >= 6) { requiresRtlWorkaround = false; } if (!android.os.Build.USER.toLowerCase().contains("root"))//there is no rooted ROM with a fix. { if (android.os.Build.MODEL.toLowerCase().contains("galaxy")) { //see issue 132 //and issue 285 //no fix: 1251851795000 //fix: 1251970876000 //no fix: 1251851795000 //fix: 1251970876000 //fix: 1261367883000 // //final int buildInc = Integer.parseInt(android.os.Build.VERSION.INCREMENTAL); // //requiresRtlWorkaround = (buildInc < 20090831); requiresRtlWorkaround = (android.os.Build.TIME <= 1251851795000l); } else if (android.os.Build.DEVICE.toLowerCase().contains("spica")) { //(see issue 285): //fixed: 1263807011000 requiresRtlWorkaround = (android.os.Build.TIME < 1263807011000l);//this is a lower "L" at the end } } ms_requiresRtlWorkaround = requiresRtlWorkaround; } public static boolean isRightToLeftCharacter(final char key) { final byte direction = Character.getDirectionality(key); switch(direction) { case Character.DIRECTIONALITY_RIGHT_TO_LEFT: case Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC: case Character.DIRECTIONALITY_RIGHT_TO_LEFT_EMBEDDING: case Character.DIRECTIONALITY_RIGHT_TO_LEFT_OVERRIDE: return true; default: return false; } } // public static int workaroundParenthesisDirectionFix(int primaryCode) // //Android does not support the correct direction of parenthesis in right-to-left langs. // if (!getRtlWorkaround()) // return primaryCode;//I hope Galaxy has the fix... // if (primaryCode == (int)')') // return '('; // else if (primaryCode == (int)'(') // return ')'; // return primaryCode; public static CharSequence workaroundCorrectStringDirection(CharSequence suggestion) { //Hebrew letters are to be drawn in the other direction. //Also, this is not valid for Galaxy (Israel's Cellcom Android) if (!getRtlWorkaround()) return suggestion; //this function is a workaround! In the official 1.5 firmware, there is a RTL bug. if (isRightToLeftCharacter(suggestion.charAt(0))) { String reveresed = ""; for(int charIndex = suggestion.length() - 1; charIndex>=0; charIndex { reveresed = reveresed + suggestion.charAt(charIndex); } return reveresed; } else return suggestion; } private static boolean getRtlWorkaround() { String configRtlWorkaround = AnySoftKeyboardConfiguration.getInstance().getRtlWorkaroundConfiguration(); if (configRtlWorkaround.equals("auto")) return ms_requiresRtlWorkaround; else if (configRtlWorkaround.equals("workaround")) return true; else return false; } public static boolean isAltSpaceLangSwitchNotPossible(){ String model = android.os.Build.MODEL.toLowerCase(); if(model.equals("milestone") || model.equals("droid")){ return true; } return false; } public static boolean isDonut() { return ms_isDonut; } public static boolean isEclair() { return ms_isEclair; } public static boolean doubleActionKeyDisableWorkAround(EditorInfo editor) { if (editor != null) { //package: com.android.mms, id:2131361817 //in firmware 2, 2.1 if (ms_isEclair && editor.packageName.contentEquals("com.android.mms") && (editor.fieldId == 2131361817)) { Log.d(TAG, "Android Ecliar Messaging MESSAGE field"); return true; } } return false; } }
package com.ramblingwood.minecraft.jsonapi; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.ArrayList; import java.util.Enumeration; import java.util.Hashtable; import java.util.List; import java.util.Properties; import java.util.logging.Logger; import org.json.simpleForBukkit.JSONArray; import org.json.simpleForBukkit.JSONAware; import org.json.simpleForBukkit.JSONObject; import org.json.simpleForBukkit.parser.JSONParser; import com.ramblingwood.minecraft.jsonapi.dynamic.Caller; import com.ramblingwood.minecraft.jsonapi.streams.ChatMessage; import com.ramblingwood.minecraft.jsonapi.streams.ConnectionMessage; import com.ramblingwood.minecraft.jsonapi.streams.ConsoleMessage; import com.ramblingwood.minecraft.jsonapi.streams.JSONAPIStream; import com.ramblingwood.minecraft.jsonapi.streams.StreamingResponse; public class JSONServer extends NanoHTTPD { Hashtable<String, Object> methods = new Hashtable<String, Object>(); Hashtable<String, String> logins = new Hashtable<String, String>(); private JSONAPI inst; private Logger outLog = Logger.getLogger("JSONAPI"); private Caller caller; private ArrayList<ChatMessage> chat = new ArrayList<ChatMessage>(); private ArrayList<ConsoleMessage> console = new ArrayList<ConsoleMessage>(); private ArrayList<ConnectionMessage> connections = new ArrayList<ConnectionMessage>(); public JSONServer(Hashtable<String, String> logins, JSONAPI plugin) throws IOException { super(plugin.port); inst = plugin; caller = new Caller(inst); caller.loadFile(new File(inst.getDataFolder()+File.separator+"methods.json")); File[] files = (new File(inst.getDataFolder()+File.separator+"methods"+File.separator)).listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".json"); } }); if(files != null && files.length > 0) { for(File f : files) { caller.loadFile(f); } } this.logins = logins; } public Caller getCaller() { return caller; } public void logChat(String player, String message) { chat.add(new ChatMessage(player, message)); if(chat.size() > 50) { chat.remove(0); chat.trimToSize(); } } public void logConsole(String line) { console.add(new ConsoleMessage(line)); if(console.size() > 50) { console.remove(0); console.trimToSize(); } } public void logConnected(String player) { connections.add(new ConnectionMessage(player, true)); if(connections.size() > 50) { connections.remove(0); connections.trimToSize(); } } public void logDisconnected(String player) { connections.add(new ConnectionMessage(player, false)); if(connections.size() > 50) { connections.remove(0); connections.trimToSize(); } } public boolean testLogin (String method, String hash) { try { boolean valid = false; Enumeration<String> e = logins.keys(); while(e.hasMoreElements()) { String user = e.nextElement(); String pass = logins.get(user); String thishash = JSONAPI.SHA256(user+method+pass+inst.salt); if(thishash.equals(hash)) { valid = true; break; } } return valid; } catch (Exception e) { return false; } } public static String callback (String callback, String json) { if(callback == null || callback.equals("")) return json; return callback.concat("(").concat(json).concat(")"); } public void info (final String log) { if(inst.logging || !inst.logFile.equals("false")) { outLog.info("[JSONAPI] " +log); } } public void warning (final String log) { if(inst.logging || !inst.logFile.equals("false")) { outLog.warning("[JSONAPI] " +log); } } @SuppressWarnings("unchecked") @Override public Response serve( String uri, String method, Properties header, Properties parms ) { String callback = parms.getProperty("callback"); if(inst.whitelist.size() > 0 && !inst.whitelist.contains(header.get("X-REMOTE-ADDR"))) { outLog.warning("[JSONAPI] An API call from "+ header.get("X-REMOTE-ADDR") +" was blocked because "+header.get("X-REMOTE-ADDR")+" is not on the whitelist."); return jsonRespone(returnAPIError("You are not allowed to make API calls."), callback, HTTP_FORBIDDEN); } if(uri.equals("/api/subscribe")) { String source = parms.getProperty("source"); String key = parms.getProperty("key"); if(!testLogin(source, key)) { info("[Streaming API] "+header.get("X-REMOTE-ADDR")+": Invalid API Key."); return jsonRespone(returnAPIError("Invalid API key."), callback, HTTP_FORBIDDEN); } info("[Streaming API] "+header.get("X-REMOTE-ADDR")+": source="+ source); try { if(source == null) { throw new Exception(); } ArrayList<? extends JSONAPIStream> arr; if(source.equals("chat")) { arr = chat; } else if(source.equals("connections")) { arr = connections; } else if(source.equals("console")) { arr = console; } else { throw new Exception(); } StreamingResponse out = new StreamingResponse(source, arr, callback); return new NanoHTTPD.Response( HTTP_OK, MIME_PLAINTEXT, out); } catch (Exception e) { e.printStackTrace(); return jsonRespone(returnAPIError("'"+source+"' is not a valid stream source!"), callback, HTTP_NOTFOUND); } } if(!uri.equals("/api/call") && !uri.equals("/api/call-multiple")) { return new NanoHTTPD.Response(HTTP_NOTFOUND, MIME_PLAINTEXT, "File not found."); } Object args = parms.getProperty("args","[]"); String calledMethod = (String)parms.getProperty("method"); if(calledMethod == null) { info("[API Call] "+header.get("X-REMOTE-ADDR")+": Parameter 'method' was not defined."); return jsonRespone(returnAPIError("Parameter 'method' was not defined."), callback, HTTP_NOTFOUND); } String key = parms.getProperty("key"); if(!testLogin(calledMethod, key)) { info("[API Call] "+header.get("X-REMOTE-ADDR")+": Invalid API Key."); return jsonRespone(returnAPIError("Invalid API key."), callback, HTTP_FORBIDDEN); } info("[API Call] "+header.get("X-REMOTE-ADDR")+": method="+ parms.getProperty("method").concat("?args=").concat((String) args)); if(args == null || calledMethod == null) { return jsonRespone(returnAPIError("You need to pass a method and an array of arguments."), callback, HTTP_NOTFOUND); } else { try { JSONParser parse = new JSONParser(); args = parse.parse((String) args); if(uri.equals("/api/call-multiple")) { List<String> methods = new ArrayList<String>(); List<Object> arguments = new ArrayList<Object>(); Object o = parse.parse(calledMethod); if (o instanceof List<?> && args instanceof List<?>) { methods = (List<String>)o; arguments = (List<Object>)args; } else { return jsonRespone(returnAPIException(new Exception("method and args both need to be arrays for /api/call-multiple")), callback); } int size = methods.size(); JSONArray arr = new JSONArray(); for(int i = 0; i < size; i++) { arr.add(serveAPICall(methods.get(i), (arguments.size()-1 >= i ? arguments.get(i) : new ArrayList<Object>()))); } return jsonRespone(returnAPISuccess(o, arr), callback); } else { return jsonRespone(serveAPICall(calledMethod, args), callback); } } catch (Exception e) { return jsonRespone(returnAPIException(e), callback); } } } public JSONObject returnAPIException (Exception e) { JSONObject r = new JSONObject(); r.put("result", "error"); StringWriter pw = new StringWriter(); e.printStackTrace(new PrintWriter( pw )); e.printStackTrace(); r.put("error", "Caught exception: "+pw.toString().replaceAll("\\n", "\n").replaceAll("\\r", "\r")); return r; } public JSONObject returnAPIError (String error) { JSONObject r = new JSONObject(); r.put("result", "error"); r.put("error", error); return r; } public JSONObject returnAPISuccess (Object calledMethod, Object result) { JSONObject r = new JSONObject(); r.put("result", "success"); r.put("source", calledMethod); r.put("success", result); return r; } public NanoHTTPD.Response jsonRespone (JSONAware o, String callback, String code) { return new NanoHTTPD.Response(code, MIME_JSON, callback(callback, o.toJSONString())); } public NanoHTTPD.Response jsonRespone (JSONAware o, String callback) { return jsonRespone(o, callback, HTTP_OK); } @SuppressWarnings("unchecked") public JSONObject serveAPICall(String calledMethod, Object args) { try { if(caller.methodExists(calledMethod)) { if(args instanceof JSONArray) { Object result = caller.call(calledMethod, (Object[]) ((ArrayList) args).toArray(new Object[((ArrayList) args).size()])); return returnAPISuccess(calledMethod, result); } } else { warning("The method '"+calledMethod+"' does not exist!"); return returnAPIError("The method '"+calledMethod+"' does not exist!"); } } catch (Exception e) { return returnAPIException(e); } return returnAPIError("You need to pass a method and an array of arguments."); } }
package hudson.cli; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.codec.binary.Base64; /** * Creates a capacity-unlimited bi-directional {@link InputStream}/{@link OutputStream} pair over * HTTP, which is a request/response protocol. * * @author Kohsuke Kawaguchi */ public class FullDuplexHttpStream { private final URL target; /** * Authorization header value needed to get through the HTTP layer. */ private final String authorization; private final OutputStream output; private final InputStream input; public InputStream getInputStream() { return input; } public OutputStream getOutputStream() { return output; } public FullDuplexHttpStream(URL target) throws IOException { this(target,basicAuth(target.getUserInfo())); } private static String basicAuth(String userInfo) { if (userInfo != null) return "Basic "+new String(new Base64().encodeBase64(userInfo.getBytes())); return null; } /** * @param target * The endpoint that we are making requests to. * @param authorization * The value of the authorization header, if non-null. */ public FullDuplexHttpStream(URL target, String authorization) throws IOException { this.target = target; this.authorization = authorization; CrumbData crumbData = new CrumbData(); UUID uuid = UUID.randomUUID(); // so that the server can correlate those two connections // server->client HttpURLConnection con = (HttpURLConnection) target.openConnection(); con.setDoOutput(true); // request POST to avoid caching con.setRequestMethod("POST"); con.addRequestProperty("Session", uuid.toString()); con.addRequestProperty("Side","download"); if (authorization != null) { con.addRequestProperty("Authorization", authorization); } if(crumbData.isValid) { con.addRequestProperty(crumbData.crumbName, crumbData.crumb); } con.getOutputStream().close(); input = con.getInputStream(); // make sure we hit the right URL if(con.getHeaderField("Hudson-Duplex")==null) throw new IOException(target+" doesn't look like Jenkins"); // client->server uses chunked encoded POST for unlimited capacity. con = (HttpURLConnection) target.openConnection(); con.setDoOutput(true); // request POST con.setRequestMethod("POST"); con.setChunkedStreamingMode(0); con.setRequestProperty("Content-type","application/octet-stream"); con.addRequestProperty("Session", uuid.toString()); con.addRequestProperty("Side","upload"); if (authorization != null) { con.addRequestProperty ("Authorization", authorization); } if(crumbData.isValid) { con.addRequestProperty(crumbData.crumbName, crumbData.crumb); } output = con.getOutputStream(); } static final int BLOCK_SIZE = 1024; static final Logger LOGGER = Logger.getLogger(FullDuplexHttpStream.class.getName()); private final class CrumbData { String crumbName; String crumb; boolean isValid; private CrumbData() { this.crumbName = ""; this.crumb = ""; this.isValid = false; getData(); } private void getData() { try { String base = createCrumbUrlBase(); crumbName = readData(base+"?xpath=/*/crumbRequestField/text()"); crumb = readData(base+"?xpath=/*/crumb/text()"); isValid = true; LOGGER.fine("Crumb data: "+crumbName+"="+crumb); } catch (IOException e) { // presumably this Hudson doesn't use crumb LOGGER.log(Level.FINE,"Failed to get crumb data",e); } } private String createCrumbUrlBase() { String url = target.toExternalForm(); return new StringBuilder(url.substring(0, url.lastIndexOf("/cli"))).append("/crumbIssuer/api/xml/").toString(); } private String readData(String dest) throws IOException { HttpURLConnection con = (HttpURLConnection) new URL(dest).openConnection(); if (authorization != null) { con.addRequestProperty("Authorization", authorization); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream())); return reader.readLine(); } finally { con.disconnect(); } } } }
package com.simplegeo.android.service; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; import org.apache.http.client.ClientProtocolException; import org.json.JSONArray; import org.json.JSONException; import android.app.Application; import android.app.Service; import android.content.Intent; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Binder; import android.os.Bundle; import android.os.IBinder; import android.util.Log; import com.simplegeo.android.cache.CommitLog; import com.simplegeo.client.SimpleGeoClient; import com.simplegeo.client.encoder.GeoJSONEncoder; import com.simplegeo.client.geojson.GeoJSONObject; import com.simplegeo.client.model.DefaultRecord; import com.simplegeo.client.model.GeoJSONRecord; import com.simplegeo.client.model.IRecord; import com.simplegeo.client.model.Region; public class LocationService extends Service implements LocationListener { private static final String TAG = LocationService.class.getCanonicalName(); private long minTime = 120000; private float minDistance = 10.0f; private String username = null; private String cachePath = null; public boolean cacheUpdates = false; public boolean enableRegionUpdates = true; private Location previousLocation = null; private List<Region> regions = null; private List<ILocationHandler> locationHandlers = new ArrayList<ILocationHandler>(); private CommitLog commitLog = null; public List<IRecord> trackedRecords = new ArrayList<IRecord>(); public class LocationBinder extends Binder { LocationService getService() { return LocationService.this; } } private final LocationBinder locationBinder = new LocationBinder(); @Override public IBinder onBind(Intent intent) { return locationBinder; } @Override public void onCreate() { Application application = getApplication(); // There seems to be a bug when retreiving the cache // directory from the ContextWrapper where a NPE is // thrown. This only happens in testing. try { File cacheDir = application.getApplicationContext().getCacheDir(); cachePath = cacheDir.getAbsolutePath(); } catch (Exception e) { Log.e(TAG, e.toString(), e); cachePath = "/sdcard/"; } try { username = application.getApplicationContext().getPackageName(); } catch (Exception e) { Log.e(TAG, e.toString(), e); username = "com.simplegeo.android.cache"; } setCacheValues(cachePath, username); updateProviders(); } @Override public void onDestroy() { commitLog.flush(); } public void updateProviders() { updateProviders(null); } public void addLocationHandler(ILocationHandler locationHandler) { locationHandlers.add(locationHandler); } public void removeLocationHandler(ILocationHandler locationHandler) { locationHandlers.remove(locationHandler); } public void updateProviders(Criteria criteria) { if(criteria == null) criteria = generateCriteria(); LocationManager locationManager = (LocationManager)getSystemService(LOCATION_SERVICE); List<String> providerNames = locationManager.getProviders(criteria, true); for(String providerName : providerNames) locationManager.requestLocationUpdates(providerName, minTime, minDistance, this); } private Criteria generateCriteria() { Criteria criteria = new Criteria(); // Do some setup of the criteria. return criteria; } public void onLocationChanged(Location location) { Log.d(TAG, "location updated to " + location.toString()); for(ILocationHandler handler : locationHandlers) handler.onLocationChanged(previousLocation, location); updateRecordsFromLocation(location); updateRegionsFromLocation(location); previousLocation = location; } public void onProviderDisabled(String provider) { // Don't really care... } public void onProviderEnabled(String provider) { // Possibly add as a listener? } public void onStatusChanged(String provider, int status, Bundle extras) { LocationManager locationManager = (LocationManager)getSystemService(LOCATION_SERVICE); locationManager.requestLocationUpdates(provider, minTime, minDistance, this); } private void updateRegionsFromLocation(Location location) { JSONArray boundaries = fetchRegions(location); if(boundaries != null && enableRegionUpdates) { List<Region> regions = Region.getRegions(boundaries); List<Region> enteredRegions = new ArrayList<Region>(); List<Region> exitedRegions = new ArrayList<Region>(); if(this.regions == null) { enteredRegions = regions; } else { exitedRegions.addAll(Region.difference(this.regions, regions)); for(Region region : regions) if(!region.contained(this.regions)) enteredRegions.add(region); } if(enteredRegions != null && enteredRegions.size() > 0) for(ILocationHandler handler : locationHandlers) handler.onRegionsEntered(enteredRegions, previousLocation, location); if(exitedRegions != null && exitedRegions.size() > 0) for(ILocationHandler handler : locationHandlers) handler.onRegionsExited(exitedRegions, previousLocation, location); this.regions = regions; } } private JSONArray fetchRegions(Location location) { JSONArray boundaries = null; try { SimpleGeoClient client = SimpleGeoClient.getInstance(); Object returnObject = client.contains(location.getLatitude(), location.getLongitude()); // There are two possible return values from the client // depending on the value of futureTask if(client.futureTask) boundaries = (JSONArray)((FutureTask)returnObject).get(); else boundaries = (JSONArray)returnObject; } catch (ClientProtocolException e) { Log.e(TAG, e.toString(), e); } catch (IOException e) { Log.e(TAG, e.toString(), e); } catch (InterruptedException e) { Log.e(TAG, e.toString(), e); } catch (ExecutionException e) { Log.e(TAG, e.toString(), e); } return boundaries; } private void updateRecordsFromLocation(Location location) { List<IRecord> updateRecords = new ArrayList<IRecord>(); List<IRecord> cacheRecords = new ArrayList<IRecord>(); for(IRecord record : trackedRecords) { if((record instanceof DefaultRecord) || (record instanceof GeoJSONRecord)) { ((DefaultRecord)record).setLatitude(location.getLatitude()); ((DefaultRecord)record).setLongitude(location.getLongitude()); } } if(locationHandlers.isEmpty()) { if(cacheUpdates) cacheRecords.addAll(trackedRecords); else updateRecords.addAll(trackedRecords); } for(ILocationHandler locationHandler : locationHandlers) { List<IRecord> records = locationHandler.getRecords(location, trackedRecords); if(records != null && !records.isEmpty()) if(cacheUpdates) cacheRecords.addAll(records); else updateRecords.addAll(records); } if(!updateRecords.isEmpty()) updateRecords(updateRecords); if(!cacheRecords.isEmpty()) cacheRecords(cacheRecords); } public void updateRecords(List<IRecord> records) { if(!records.isEmpty()) try { Log.d(TAG, String.format("updating %d records", records.size())); SimpleGeoClient.getInstance().update(records); } catch (ClientProtocolException e) { Log.e(TAG, e.toString(), e); } catch (IOException e) { Log.e(TAG, e.toString(), e); } } public void cacheRecords(List<IRecord> records) { if(records != null && records.size() > 0) { Log.d(TAG, String.format("cacheing %d records", records.size())); GeoJSONObject geoJSON = GeoJSONEncoder.getGeoJSONRecord(records); commitLog.commit("update_records", geoJSON.toString()); } } public void replayCommitLog() { List<String> commits = commitLog.getCommits("update_records"); List<IRecord> recordsToUpdate = new ArrayList<IRecord>(); for(String commit : commits) { GeoJSONObject geoJSON; try { geoJSON = new GeoJSONObject("FeatureCollection", commit); List<DefaultRecord> records = GeoJSONEncoder.getRecords(geoJSON); if(records != null) recordsToUpdate.addAll(records); } catch (JSONException e) { Log.e(TAG, e.toString(), e); } } if(!recordsToUpdate.isEmpty()) updateRecords(recordsToUpdate); } public void addHandler(ILocationHandler handler) { locationHandlers.add(handler); } public void removeHandler(ILocationHandler handler) { locationHandlers.remove(handler); } /** * @return the cacheUpdates */ public boolean cacheUpdates() { return cacheUpdates; } /** * @param cacheUpdates the cacheUpdates to set */ public void setCacheUpdates(boolean cacheUpdates) { this.cacheUpdates = cacheUpdates; } /** * @return the minTime */ public long getMinTime() { return minTime; } /** * @param minTime the minTime to set */ public void setMinTime(long minTime) { this.minTime = minTime; } /** * @return the minDistance */ public float getMinDistance() { return minDistance; } /** * @param minDistance the minDistance to set */ public void setMinDistance(float minDistance) { this.minDistance = minDistance; } public List<Region> getRegions() { return this.regions; } public void setCacheValues(String cachePath, String username) { this.cachePath = cachePath; this.username = username; this.commitLog = new CommitLog(cachePath, username); replayCommitLog(); } }
package mitzi; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; public class NaiveBoard implements IBoard { protected static Side[] initial_side_board = { Side.BLACK, Side.BLACK, Side.BLACK, Side.BLACK, Side.BLACK, Side.BLACK, Side.BLACK, Side.BLACK, Side.BLACK, Side.BLACK, Side.BLACK, Side.BLACK, Side.BLACK, Side.BLACK, Side.BLACK, Side.BLACK, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, Side.WHITE, Side.WHITE, Side.WHITE, Side.WHITE, Side.WHITE, Side.WHITE, Side.WHITE, Side.WHITE, Side.WHITE, Side.WHITE, Side.WHITE, Side.WHITE, Side.WHITE, Side.WHITE, Side.WHITE, Side.WHITE, null }; protected static Piece[] initial_piece_board = { Piece.ROOK, Piece.KNIGHT, Piece.BISHOP, Piece.QUEEN, Piece.KING, Piece.BISHOP, Piece.KNIGHT, Piece.ROOK, Piece.PAWN, Piece.PAWN, Piece.PAWN, Piece.PAWN, Piece.PAWN, Piece.PAWN, Piece.PAWN, Piece.PAWN, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, Piece.PAWN, Piece.PAWN, Piece.PAWN, Piece.PAWN, Piece.PAWN, Piece.PAWN, Piece.PAWN, Piece.PAWN, Piece.ROOK, Piece.KNIGHT, Piece.BISHOP, Piece.QUEEN, Piece.KING, Piece.BISHOP, Piece.KNIGHT, Piece.ROOK, null }; private Side[] side_board = new Side[65]; private Piece[] piece_board = new Piece[65]; protected static int[] square_to_array_index = { 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 56, 48, 40, 32, 24, 16, 8, 0, 64, 64, 57, 49, 41, 33, 25, 17, 9, 1, 64, 64, 58, 50, 42, 34, 26, 18, 10, 2, 64, 64, 59, 51, 43, 35, 27, 19, 11, 3, 64, 64, 60, 52, 44, 36, 28, 20, 12, 4, 64, 64, 61, 53, 45, 37, 29, 21, 13, 5, 64, 64, 62, 54, 46, 38, 30, 22, 14, 6, 64, 64, 63, 55, 47, 39, 31, 23, 15, 7, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64 }; private int full_move_clock; private int half_move_clock; // squares c1, g1, c8 and g8 in ICCF numeric notation // do not change the squares' order or bad things will happen! // set to -1 if castling not allowed private int[] castling = { -1, -1, -1, -1 }; private int en_passant_target = -1; private Side active_color; // The following class members are used to prevent multiple computations private Set<IMove> possible_moves; // Set of all possible moves private Boolean is_check; // using the class Boolean, which can be null! private Boolean is_mate; private Boolean is_stale_mate; // the following maps takes and Integer, representing the color, type or // PieceValue and returns the set of squares or the number of squares! private Map<Integer, Set<Integer>> occupied_squares_by_color_and_type = new HashMap<Integer, Set<Integer>>(); private Map<Side, Set<Integer>> occupied_squares_by_color = new HashMap<Side, Set<Integer>>(); private Map<Piece, Set<Integer>> occupied_squares_by_type = new HashMap<Piece, Set<Integer>>(); private Map<Integer, Integer> num_occupied_squares_by_color_and_type = new HashMap<Integer, Integer>(); private Map<Side, Integer> num_occupied_squares_by_color = new HashMap<Side, Integer>(); private Map<Piece, Integer> num_occupied_squares_by_type = new HashMap<Piece, Integer>(); private void resetCache() { possible_moves = null; is_check = null; is_mate = null; is_stale_mate = null; occupied_squares_by_color.clear(); occupied_squares_by_color_and_type.clear(); occupied_squares_by_type.clear(); num_occupied_squares_by_color.clear(); num_occupied_squares_by_color_and_type.clear(); num_occupied_squares_by_type.clear(); } private int squareToArrayIndex(int square) { if (square < 0) return 64; return square_to_array_index[square]; } private NaiveBoard returnCopy() { NaiveBoard newBoard = new NaiveBoard(); newBoard.active_color = active_color; newBoard.en_passant_target = en_passant_target; newBoard.full_move_clock = full_move_clock; newBoard.half_move_clock = half_move_clock; System.arraycopy(castling, 0, newBoard.castling, 0, 4); System.arraycopy(side_board, 0, newBoard.side_board, 0, 65); System.arraycopy(piece_board, 0, newBoard.piece_board, 0, 65); return newBoard; } private Side getSideFromBoard(int square) { int i = squareToArrayIndex(square); return side_board[i]; } private Piece getPieceFromBoard(int square) { int i = squareToArrayIndex(square); return piece_board[i]; } private void setOnBoard(int square, Side side, Piece piece) { int i = squareToArrayIndex(square); side_board[i] = side; piece_board[i] = piece; } public Side getOpponentsColor() { if (active_color == Side.BLACK) return Side.WHITE; else return Side.BLACK; } @Override public void setToInitial() { System.arraycopy(initial_side_board, 0, side_board, 0, 65); System.arraycopy(initial_piece_board, 0, piece_board, 0, 65); full_move_clock = 1; half_move_clock = 0; castling[0] = 31; castling[1] = 71; castling[2] = 38; castling[3] = 78; en_passant_target = -1; active_color = Side.WHITE; resetCache(); } @Override public void setToFEN(String fen) { side_board = new Side[65]; piece_board = new Piece[65]; castling[0] = -1; castling[1] = -1; castling[2] = -1; castling[3] = -1; en_passant_target = -1; resetCache(); String[] fen_parts = fen.split(" "); // populate the squares String[] fen_rows = fen_parts[0].split("/"); char[] pieces; for (int row = 1; row <= 8; row++) { int offset = 0; for (int column = 1; column + offset <= 8; column++) { pieces = fen_rows[8 - row].toCharArray(); int square = (column + offset) * 10 + row; switch (pieces[column - 1]) { case 'P': setOnBoard(square, Side.WHITE, Piece.PAWN); break; case 'R': setOnBoard(square, Side.WHITE, Piece.ROOK); break; case 'N': setOnBoard(square, Side.WHITE, Piece.KNIGHT); break; case 'B': setOnBoard(square, Side.WHITE, Piece.BISHOP); break; case 'Q': setOnBoard(square, Side.WHITE, Piece.QUEEN); break; case 'K': setOnBoard(square, Side.WHITE, Piece.KING); break; case 'p': setOnBoard(square, Side.BLACK, Piece.PAWN); break; case 'r': setOnBoard(square, Side.BLACK, Piece.ROOK); break; case 'n': setOnBoard(square, Side.BLACK, Piece.KNIGHT); break; case 'b': setOnBoard(square, Side.BLACK, Piece.BISHOP); break; case 'q': setOnBoard(square, Side.BLACK, Piece.QUEEN); break; case 'k': setOnBoard(square, Side.BLACK, Piece.KING); break; default: offset += Character.getNumericValue(pieces[column - 1]) - 1; break; } } } // set active color switch (fen_parts[1]) { case "b": active_color = Side.BLACK; break; case "w": active_color = Side.WHITE; break; } // set possible castling moves if (!fen_parts[2].equals("-")) { char[] castlings = fen_parts[2].toCharArray(); for (int i = 0; i < castlings.length; i++) { switch (castlings[i]) { case 'K': castling[1] = 71; break; case 'Q': castling[0] = 31; break; case 'k': castling[3] = 78; break; case 'q': castling[2] = 38; break; } } } // set en passant square if (!fen_parts[3].equals("-")) { en_passant_target = SquareHelper.fromString(fen_parts[3]); } // set half move clock half_move_clock = Integer.parseInt(fen_parts[4]); // set full move clock full_move_clock = Integer.parseInt(fen_parts[5]); } @Override public NaiveBoard doMove(IMove move) { NaiveBoard newBoard = this.returnCopy(); int src = move.getFromSquare(); int dest = move.getToSquare(); Side side = getSideFromBoard(src); Piece piece = getPieceFromBoard(src); // if promotion if (move.getPromotion() != null) { newBoard.setOnBoard(src, null, null); newBoard.setOnBoard(dest, active_color, move.getPromotion()); newBoard.half_move_clock = 0; } // If castling else if (piece == Piece.KING && Math.abs((src - dest)) == 20) { newBoard.setOnBoard(dest, active_color, Piece.KING); newBoard.setOnBoard(src, null, null); newBoard.setOnBoard((src + dest) / 2, active_color, Piece.ROOK); if (SquareHelper.getColumn(dest) == 3) newBoard.setOnBoard(src - 40, null, null); else newBoard.setOnBoard(src + 30, null, null); newBoard.half_move_clock++; } // If en passant else if (piece == Piece.PAWN && dest == this.getEnPassant()) { newBoard.setOnBoard(dest, active_color, Piece.PAWN); newBoard.setOnBoard(src, null, null); if (active_color == Side.WHITE) newBoard.setOnBoard(dest - 1, null, null); else newBoard.setOnBoard(dest + 1, null, null); newBoard.half_move_clock = 0; } // Usual move else { newBoard.setOnBoard(dest, side, piece); newBoard.setOnBoard(src, null, null); if (this.getSideFromBoard(dest) != null || piece == Piece.PAWN) newBoard.half_move_clock = 0; else newBoard.half_move_clock++; } // Change active_color after move newBoard.active_color = Side.getOppositeSide(side); if (active_color == Side.BLACK) newBoard.full_move_clock++; // Update en_passant if (piece == Piece.PAWN && Math.abs(dest - src) == 2) newBoard.en_passant_target = (dest + src) / 2; else newBoard.en_passant_target = -1; // Update castling if (piece == Piece.KING) { if (active_color == Side.WHITE && src == 51) { newBoard.castling[0] = -1; newBoard.castling[1] = -1; } else if (active_color == Side.BLACK && src == 58) { newBoard.castling[2] = -1; newBoard.castling[3] = -1; } } else if (piece == Piece.ROOK) { if (active_color == Side.WHITE) { if (src == 81) newBoard.castling[1] = -1; else if (src == 11) newBoard.castling[0] = -1; } else { if (src == 88) newBoard.castling[3] = -1; else if (src == 18) newBoard.castling[2] = -1; } } return newBoard; } @Override public int getEnPassant() { return en_passant_target; } @Override public boolean canCastle(int king_to) { if ((king_to == 31 && castling[0] != -1) || (king_to == 71 && castling[1] != -1) || (king_to == 38 && castling[2] != -1) || (king_to == 78 && castling[3] != -1)) { return true; } else { return false; } } @Override public Boolean colorCanCastle(Side color) { // Set the right color if (active_color != color) ; active_color = getOpponentsColor(); // check for castling if (!isCheckPosition()) { Move move; int off = 0; int square = 51; if (color == Side.BLACK) { off = 2; square = 58; } for (int i = 0; i < 2; i++) { int castle_flag = 0; Integer new_square = castling[i + off]; // castling must still be possible to this side if (new_square != -1) { Direction dir; if (i == 0) dir = Direction.WEST; else dir = Direction.EAST; List<Integer> line = SquareHelper.getAllSquaresInDirection( square, dir); // Check each square if it is empty for (Integer squ : line) { if (getSideFromBoard(squ) != null) { castle_flag = 1; break; } if (squ == new_square) break; } if (castle_flag == 1) continue; // Check each square if the king on it would be check for (Integer squ : line) { move = new Move(square, squ); NaiveBoard board = doMove(move); board.active_color = active_color; if (board.isCheckPosition()) break; if (squ == new_square) { // If the end is reached, then stop checking. // undoing change of color if (active_color == color) active_color = getOpponentsColor(); return true; } } } } } // undoing change of color if (active_color == color) active_color = getOpponentsColor(); return false; } @Override public Set<Integer> getOccupiedSquaresByColor(Side color) { if (occupied_squares_by_color.containsKey(color) == false) { int square; Set<Integer> set = new HashSet<Integer>(); for (int i = 1; i < 9; i++) for (int j = 1; j < 9; j++) { square = SquareHelper.getSquare(i, j); if (getSideFromBoard(square) == color) set.add(square); } occupied_squares_by_color.put(color, set); return set; } return occupied_squares_by_color.get(color); } @Override public Set<Integer> getOccupiedSquaresByType(Piece type) { if (occupied_squares_by_type.containsKey(type) == false) { int square; Set<Integer> set = new HashSet<Integer>(); for (int i = 1; i < 9; i++) for (int j = 1; j < 9; j++) { square = SquareHelper.getSquare(i, j); if (getPieceFromBoard(square) == type) set.add(square); } occupied_squares_by_type.put(type, set); return set; } return occupied_squares_by_type.get(type); } @Override public Set<Integer> getOccupiedSquaresByColorAndType(Side color, Piece type) { int value = color.ordinal() * 10 + type.ordinal(); if (occupied_squares_by_color_and_type.containsKey(value) == false) { int square; Set<Integer> set = new HashSet<Integer>(); for (int i = 1; i < 9; i++) for (int j = 1; j < 9; j++) { square = SquareHelper.getSquare(i, j); if (color == getSideFromBoard(square) && type == getPieceFromBoard(square)) set.add(square); } occupied_squares_by_color_and_type.put(value, set); return set; } return occupied_squares_by_color_and_type.get(value); } @Override public int getNumberOfPiecesByColor(Side color) { if (num_occupied_squares_by_color.containsKey(color) == false) { if (occupied_squares_by_color.containsKey(color) == false) { int square; int num = 0; for (int i = 1; i < 9; i++) for (int j = 1; j < 9; j++) { square = SquareHelper.getSquare(i, j); if (getSideFromBoard(square) == color) num++; } num_occupied_squares_by_color.put(color, num); return num; } num_occupied_squares_by_color.put(color, occupied_squares_by_color .get(color).size()); } return num_occupied_squares_by_color.get(color); } @Override public int getNumberOfPiecesByType(Piece type) { if (num_occupied_squares_by_type.containsKey(type) == false) { if (occupied_squares_by_type.containsKey(type) == false) { int square; int num = 0; for (int i = 1; i < 9; i++) for (int j = 1; j < 9; j++) { square = SquareHelper.getSquare(i, j); if (getPieceFromBoard(square) == type) num++; } num_occupied_squares_by_type.put(type, num); return num; } num_occupied_squares_by_type.put(type, occupied_squares_by_type .get(type).size()); } return num_occupied_squares_by_type.get(type); } @Override public int getNumberOfPiecesByColorAndType(Side color, Piece type) { int value = color.ordinal() * 10 + type.ordinal(); if (num_occupied_squares_by_color_and_type.containsKey(value) == false) { if (occupied_squares_by_color_and_type.containsKey(value) == false) { int square; int num = 0; for (int i = 1; i < 9; i++) for (int j = 1; j < 9; j++) { square = SquareHelper.getSquare(i, j); if (color == getSideFromBoard(square) && type == getPieceFromBoard(square)) num++; } num_occupied_squares_by_color_and_type.put(value, num); return num; } num_occupied_squares_by_color_and_type.put(value, occupied_squares_by_color_and_type.get(value).size()); } return num_occupied_squares_by_color_and_type.get(value); } @Override public Set<IMove> getPossibleMoves() { if (possible_moves == null) { Set<IMove> total_set = new HashSet<IMove>(); Set<IMove> temp_set; // all the active squares Set<Integer> squares = getOccupiedSquaresByColor(active_color); // loop over all squares for (int square : squares) { temp_set = getPossibleMovesFrom(square); total_set.addAll(temp_set); } possible_moves = total_set; } return possible_moves; } @Override public Set<IMove> getPossibleMovesFrom(int square) { // The case, that the destination is the opponents king cannot happen. Piece type = getPieceFromBoard(square); Side opp_color = getOpponentsColor(); List<Integer> squares; Set<IMove> moves = new HashSet<IMove>(); Move move; // Types BISHOP, QUEEN, ROOK if (type == Piece.BISHOP || type == Piece.QUEEN || type == Piece.ROOK) { // Loop over all directions and skip not appropriate ones for (Direction direction : Direction.values()) { // Skip N,W,E,W with BISHOP and skip NE,NW,SE,SW with ROOK if (((direction == Direction.NORTH || direction == Direction.EAST || direction == Direction.SOUTH || direction == Direction.WEST) && type == Piece.BISHOP) || ((direction == Direction.NORTHWEST || direction == Direction.NORTHEAST || direction == Direction.SOUTHEAST || direction == Direction.SOUTHWEST) && type == Piece.ROOK)) { continue; } else { // do stuff squares = SquareHelper.getAllSquaresInDirection(square, direction); for (Integer new_square : squares) { Piece piece = getPieceFromBoard(new_square); Side color = getSideFromBoard(new_square); if (piece == null || color == opp_color) { move = new Move(square, new_square); moves.add(move); if (piece != null && color == opp_color) // not possible to go further break; } else break; } } } } if (type == Piece.PAWN) { // If Pawn has not moved yet (steps possible) if ((SquareHelper.getRow(square) == 2 && active_color == Side.WHITE) || (SquareHelper.getRow(square) == 7 && active_color == Side.BLACK)) { if (getSideFromBoard(square + Direction.pawnDirection(active_color).offset) == null) { move = new Move(square, square + Direction.pawnDirection(active_color).offset); moves.add(move); if (getSideFromBoard(square + 2 * Direction.pawnDirection(active_color).offset) == null) { move = new Move(square, square + 2 * Direction.pawnDirection(active_color).offset); moves.add(move); } } Set<Direction> pawn_capturing_directions = Direction .pawnCapturingDirections(active_color); for (Direction direction : pawn_capturing_directions) { if (getSideFromBoard(square + direction.offset) == getOpponentsColor()) { move = new Move(square, square + direction.offset); moves.add(move); } } } // if Promotion will happen else if ((SquareHelper.getRow(square) == 7 && active_color == Side.WHITE) || (SquareHelper.getRow(square) == 2 && active_color == Side.BLACK)) { if (getSideFromBoard(square + Direction.pawnDirection(active_color).offset) == null) { move = new Move(square, square + Direction.pawnDirection(active_color).offset, Piece.QUEEN); moves.add(move); move = new Move(square, square + Direction.pawnDirection(active_color).offset, Piece.KNIGHT); moves.add(move); /* * A Queen is always better then a rook or a bishop move = * new Move(square, square + * Direction.pawnDirection(active_color).offset, * Piece.ROOK); moves.add(move); move = new Move(square, * square + Direction.pawnDirection(active_color).offset, * Piece.BISHOP); moves.add(move); */ } Set<Direction> pawn_capturing_directions = Direction .pawnCapturingDirections(active_color); for (Direction direction : pawn_capturing_directions) { if (getSideFromBoard(square + direction.offset) == getOpponentsColor()) { move = new Move(square, square + direction.offset, Piece.QUEEN); moves.add(move); move = new Move(square, square + direction.offset, Piece.KNIGHT); moves.add(move); } } } // Usual turn and en passente is possible, no promotion else { if (getSideFromBoard(square + Direction.pawnDirection(active_color).offset) == null) { move = new Move(square, square + Direction.pawnDirection(active_color).offset); moves.add(move); } Set<Direction> pawn_capturing_directions = Direction .pawnCapturingDirections(active_color); for (Direction direction : pawn_capturing_directions) { if ((getSideFromBoard(square + direction.offset) == getOpponentsColor()) || square + direction.offset == getEnPassant()) { move = new Move(square, square + direction.offset); moves.add(move); } } } } if (type == Piece.KING) { for (Direction direction : Direction.values()) { Integer new_square = square + direction.offset; if (SquareHelper.isValidSquare(new_square)) { move = new Move(square, new_square); Side side = getSideFromBoard(new_square); // if the new square is empty or occupied by the opponent if (side != active_color) moves.add(move); } } // Castle Moves // If the King is not check now, try castle moves if (!isCheckPosition()) { int off = 0; if (active_color == Side.BLACK) off = 2; for (int i = 0; i < 2; i++) { int castle_flag = 0; Integer new_square = castling[i + off]; // castling must still be possible to this side if (new_square != -1) { Direction dir; if (i == 0) dir = Direction.WEST; else dir = Direction.EAST; List<Integer> line = SquareHelper .getAllSquaresInDirection(square, dir); // Check each square if it is empty for (Integer squ : line) { if (getSideFromBoard(squ) != null) { castle_flag = 1; break; } if (squ == new_square) break; } if (castle_flag == 1) continue; // Check each square if the king on it would be check for (Integer squ : line) { move = new Move(square, squ); NaiveBoard board = doMove(move); board.active_color = active_color; // TODO: ugly // solution ! ;) if (board.isCheckPosition()) break; if (squ == new_square) { // if everything is right, then add the move moves.add(move); break; } } } } } } if (type == Piece.KNIGHT) { squares = SquareHelper.getAllSquaresByKnightStep(square); for (Integer new_square : squares) { Side side = getSideFromBoard(new_square); if (side != active_color) { move = new Move(square, new_square); moves.add(move); } } } // remove invalid positions // TODO do this in a more efficient way Iterator<IMove> iter = moves.iterator(); while (iter.hasNext()) { NaiveBoard temp_board = this.doMove(iter.next()); temp_board.active_color = active_color; if (temp_board.isCheckPosition()) { iter.remove(); } } return moves; } @Override public Set<IMove> getPossibleMovesTo(int square) { Set<IMove> result = new HashSet<IMove>(); if (possible_moves == null) possible_moves = getPossibleMoves(); else { for (IMove move : possible_moves) { if (move.getToSquare() == square) result.add(move); } } return result; } @Override public boolean isCheckPosition() { if (is_check == null) { is_check = true; Set<Integer> temp_king_pos = getOccupiedSquaresByColorAndType( active_color, Piece.KING); int king_pos = temp_king_pos.iterator().next(); // go in each direction for (Direction direction : Direction.values()) { List<Integer> line = SquareHelper.getAllSquaresInDirection( king_pos, direction); int iter = 0; for (int square : line) { iter++; Piece piece = getPieceFromBoard(square); Side side = getSideFromBoard(square); if (piece != null) { if (side == active_color) { break; } else { if (piece == Piece.PAWN && iter == 1) { if (((direction == Direction.NORTHEAST || direction == Direction.NORTHWEST) && active_color == Side.WHITE) || ((direction == Direction.SOUTHEAST || direction == Direction.SOUTHWEST) && active_color == Side.BLACK)) { return true; } } else if (piece == Piece.ROOK) { if (direction == Direction.EAST || direction == Direction.WEST || direction == Direction.NORTH || direction == Direction.SOUTH) { return true; } } else if (piece == Piece.BISHOP) { if (direction == Direction.NORTHEAST || direction == Direction.NORTHWEST || direction == Direction.SOUTHEAST || direction == Direction.SOUTHWEST) { return true; } } else if (piece == Piece.QUEEN) { return true; } else if (piece == Piece.KING && iter == 1) { return true; } break; } } } } // check for knight attacks List<Integer> knight_squares = SquareHelper .getAllSquaresByKnightStep(king_pos); for (int square : knight_squares) { Piece piece = getPieceFromBoard(square); Side side = getSideFromBoard(square); if (piece != null) { if (side != active_color && piece == Piece.KNIGHT) { return true; } } } is_check = false; } return is_check.booleanValue(); } @Override public boolean isMatePosition() { if (is_mate == null) { is_mate = true; Set<IMove> moves = getPossibleMoves(); if (moves.isEmpty() && isCheckPosition()) return true; is_mate = false; } return is_mate.booleanValue(); } @Override public boolean isStaleMatePosition() { if (is_stale_mate == null) { is_stale_mate = true; Set<IMove> moves = getPossibleMoves(); if (moves.isEmpty()) return true; is_stale_mate = false; } return is_stale_mate.booleanValue(); } @Override public boolean isPossibleMove(IMove move) { // TODO Auto-generated method stub return false; } public String toString() { return toFEN(); } @Override public String toFEN() { StringBuilder fen = new StringBuilder(); // piece placement for (int row = 0; row < 8; row++) { int counter = 0; for (int column = 0; column < 8; column++) { if (side_board[row * 8 + column] == null) { counter++; } else { if (counter != 0) { fen.append(counter); counter = 0; } fen.append(PieceHelper.toString( side_board[row * 8 + column], piece_board[row * 8 + column])); } if (column == 7 && counter != 0) { fen.append(counter); } } if (row != 7) { fen.append("/"); } } fen.append(" "); // active color if (active_color == Side.WHITE) { fen.append("w"); } else { fen.append("b"); } fen.append(" "); // castling availability boolean castle_flag = false; if (castling[1] != -1) { fen.append("K"); castle_flag = true; } if (castling[0] != -1) { fen.append("Q"); castle_flag = true; } if (castling[3] != -1) { fen.append("k"); castle_flag = true; } if (castling[2] != -1) { fen.append("q"); castle_flag = true; } if (!castle_flag) { fen.append("-"); } fen.append(" "); // en passant target square if (en_passant_target == -1) { fen.append("-"); } else { fen.append(SquareHelper.toString(en_passant_target)); } fen.append(" "); // halfmove clock fen.append(half_move_clock); fen.append(" "); // fullmove clock fen.append(full_move_clock); return fen.toString(); } @Override public Side getActiveColor() { return active_color; } @Override public int getHalfMoveClock() { return half_move_clock; } @Override public int getFullMoveClock() { return full_move_clock; } }
/** * This file is part of the Harmony package. */ package com.tactfactory.mda.template; import java.io.File; import java.util.ArrayList; import com.google.common.base.CaseFormat; import com.tactfactory.mda.Harmony; import com.tactfactory.mda.meta.ApplicationMetadata; import com.tactfactory.mda.plateforme.BaseAdapter; import com.tactfactory.mda.utils.ConsoleUtils; import com.tactfactory.mda.utils.FileUtils; /** * Generator class for the project. * */ public class ProjectGenerator extends BaseGenerator { /** * Constructor. * @param adapter The adapter to use for the generation. * @throws Exception */ public ProjectGenerator(final BaseAdapter adapter) throws Exception { super(adapter); this.datamodel = this.appMetas.toMap(this.adapter); } /** * Make Platform specific Project Structure. * @return success to make the platform project folder */ public final boolean makeProject() { boolean result = false; if (this.adapter.getPlatform().equals("android")) { result = this.makeProjectAndroid(); } else if (this.adapter.getPlatform().equals("ios")) { result = this.makeProjectIOS(); } else if (this.adapter.getPlatform().equals("rim")) { result = this.makeProjectRIM(); } else if (this.adapter.getPlatform().equals("winphone")) { result = this.makeProjectWinPhone(); } return result; } /** * Remove Platform specific Project Structure. * @return success to make the platform project folder */ public final boolean removeProject() { boolean result = false; final File dirproj = new File( String.format("%s/%s/", Harmony.PATH_PROJECT, this.adapter.getPlatform())); final int removeResult = FileUtils.deleteRecursive(dirproj); if (removeResult == 0) { result = true; ConsoleUtils.displayDebug( "Project " + this.adapter.getPlatform() + " removed!"); } else { ConsoleUtils.displayError( new Exception("Remove Project " + this.adapter.getPlatform() + " return " + removeResult + " errors...\n")); } return result; } /** * Generate HomeActivity File and merge it with datamodel. */ public final void generateHomeActivity() { ConsoleUtils.display(">> Generate HomeView & Strings..."); final String fullFilePath = this.adapter.getHomeActivityPathFile(); final String fullTemplatePath = this.adapter.getTemplateHomeActivityPathFile().substring(1); super.makeSource(fullTemplatePath, fullFilePath, true); } /** * Create Android project folders */ private void createFolders() { // create project name space folders FileUtils.makeFolder(this.adapter.getSourcePath() + this.appMetas.projectNameSpace.replaceAll("\\.", "/")); // create empty package entity FileUtils.makeFolder(this.adapter.getSourcePath() + this.appMetas.projectNameSpace.replaceAll("\\.", "/") + "/entity/"); // create util folder FileUtils.makeFolder(this.adapter.getSourcePath() + this.appMetas.projectNameSpace.replaceAll("\\.", "/") + "/harmony/util/"); // create libs folder FileUtils.makeFolder(this.adapter.getLibsPath()); } /** * Make Android sources project File */ private void makeSources() { // create HomeActivity.java super.makeSource(this.adapter.getHomeActivityPathFile(), this.adapter.getTemplateHomeActivityPathFile(), false); // create configs.xml super.makeSource( this.adapter.getTemplateRessourceValuesPath() + "configs.xml", this.adapter.getRessourceValuesPath() + "configs.xml", false); // create strings.xml super.makeSource( this.adapter.getTemplateStringsPathFile(), this.adapter.getStringsPathFile(), false); // create configs.xml super.makeSource( this.adapter.getTemplateRessourceValuesPath() + "styles.xml", this.adapter.getRessourceValuesPath() + "styles.xml", false); // create main.xml super.makeSource( this.adapter.getTemplateRessourceLayoutPath() + "main.xml", this.adapter.getRessourceLayoutPath() + "main.xml", false); // create HarmonyFragmentActivity super.makeSource( this.adapter.getTemplateSourcePath() + "harmony/view/HarmonyFragmentActivity.java", this.adapter.getSourcePath() + this.appMetas.projectNameSpace + "/harmony/view/" + "HarmonyFragmentActivity.java", false); // create HarmonyFragment super.makeSource( this.adapter.getTemplateSourcePath() + "harmony/view/HarmonyFragment.java", this.adapter.getSourcePath() + this.appMetas.projectNameSpace + "/harmony/view/" + "HarmonyFragment.java", false); // create HarmonyListFragment super.makeSource( this.adapter.getTemplateSourcePath() + "harmony/view/HarmonyListFragment.java", this.adapter.getSourcePath() + this.appMetas.projectNameSpace + "/harmony/view/" + "HarmonyListFragment.java", false); // create ProjectMenuBase super.makeSource( this.adapter.getTemplateSourcePath() + "menu/TemplateMenuBase.java", this.adapter.getMenuPath() + CaseFormat.LOWER_CAMEL.to( CaseFormat.UPPER_CAMEL, this.appMetas.name) + "MenuBase.java", false); // create ProjectMenu super.makeSource( this.adapter.getTemplateSourcePath() + "menu/TemplateMenu.java", this.adapter.getMenuPath() + CaseFormat.LOWER_CAMEL.to( CaseFormat.UPPER_CAMEL, this.appMetas.name) + "Menu.java", false); // create MenuWrapper super.makeSource( this.adapter.getTemplateSourcePath() + "menu/MenuWrapperBase.java", this.adapter.getMenuPath() + "MenuWrapperBase.java", false); } /** * Add Android libs project File */ private void addLibs() { // copy libraries this.updateLibrary("joda-time-2.1.jar"); this.updateLibrary("guava-12.0.jar"); this.updateLibrary("jsr305.jar"); /// copy sherlock library this.installAndroidSherlockLib(); /// copy Harmony library FileUtils.copyfile( new File(String.format("%s/%s", Harmony.PATH_HARMONY, "harmony.jar")), new File(String.format("%s/%s", this.adapter.getLibsPath(), "harmony.jar"))); } /** * @param pathSherlock */ private void installAndroidSherlockLib() { //TODO test if git is install String pathSherlock = String.format("%s%s", this.adapter.getLibsPath(), "sherlock"); if (!FileUtils.exists(pathSherlock)) { final ArrayList<String> command = new ArrayList<String>(); // command/Tools command.add("git"); // command action command.add("clone"); // command depot command.add("https://github.com/JakeWharton/ActionBarSherlock.git"); // command destination folder command.add(pathSherlock); ConsoleUtils.launchCommand(command); command.clear(); // command git checkout command.add("git"); command.add(String.format("%s%s/%s", "--git-dir=", pathSherlock, ".git")); command.add(String.format("%s%s", "--work-tree=", pathSherlock)); command.add("checkout"); command.add("4.2.0"); ConsoleUtils.launchCommand(command); command.clear(); // delete samples FileUtils.deleteRecursive( new File(String.format("%s/%s", pathSherlock, "samples"))); // make build sherlock command.add(String.format("%s/%s", ApplicationMetadata.androidSdkPath, "tools/android")); command.add("update"); command.add("project"); command.add("--path"); command.add(pathSherlock + "/library"); ConsoleUtils.launchCommand(command); } } /** * Make Android Project Structure * @return success to make the platform project folder */ protected final boolean makeProjectAndroid(){ boolean result = false; this.createFolders(); this.makeSources(); this.addLibs(); // copy utils this.updateUtil("DateUtils.java"); // Update newly created files with datamodel final File dirTpl = new File(this.adapter.getTemplateProjectPath()); if (dirTpl.exists() && dirTpl.listFiles().length != 0) { result = true; for (int i = 0; i < dirTpl.listFiles().length; i++) { if (dirTpl.listFiles()[i].isFile()) { super.makeSource( this.adapter.getTemplateProjectPath() + dirTpl.listFiles()[i].getName(), String.format("%s/%s/", Harmony.PATH_PROJECT, this.adapter.getPlatform()) + dirTpl.listFiles()[i].getName(), false); } } } return result; } /** * Make IOS Project Structure. * @return success to make the platform project folder */ protected final boolean makeProjectIOS() { boolean result = false; //Generate base folders & files final File dirProj = FileUtils.makeFolderRecursive( String.format("%s/%s/%s/", Harmony.PATH_TEMPLATE , this.adapter.getPlatform(), this.adapter.getProject()), String.format("%s/%s/", Harmony.PATH_PROJECT, this.adapter.getPlatform()), true); if (dirProj.exists() && dirProj.listFiles().length != 0) { result = true; } return result; } /** * Make RIM Project Structure. * @return success to make the platform project folder */ protected final boolean makeProjectRIM() { final boolean result = false; return result; } /** * Make Windows Phone Project Structure. * @return success to make the platform project folder */ protected final boolean makeProjectWinPhone() { final boolean result = false; return result; } }