diff
stringlengths
262
553k
is_single_chunk
bool
2 classes
is_single_function
bool
1 class
buggy_function
stringlengths
20
391k
fixed_function
stringlengths
0
392k
diff --git a/src/java/org/apache/jcs/utils/threadpool/ThreadPoolManager.java b/src/java/org/apache/jcs/utils/threadpool/ThreadPoolManager.java index 93ef8da7..1b593ccf 100644 --- a/src/java/org/apache/jcs/utils/threadpool/ThreadPoolManager.java +++ b/src/java/org/apache/jcs/utils/threadpool/ThreadPoolManager.java @@ -1,465 +1,465 @@ package org.apache.jcs.utils.threadpool; /* * Copyright 2001-2004 The Apache Software Foundation. Licensed under the Apache * License, Version 2.0 (the "License") you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law * or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Properties; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.jcs.utils.props.PropertyLoader; import org.apache.jcs.utils.threadpool.behavior.IPoolConfiguration; import EDU.oswego.cs.dl.util.concurrent.BoundedBuffer; import EDU.oswego.cs.dl.util.concurrent.Channel; import EDU.oswego.cs.dl.util.concurrent.LinkedQueue; import EDU.oswego.cs.dl.util.concurrent.PooledExecutor; import EDU.oswego.cs.dl.util.concurrent.ThreadFactory; /** * This manages threadpools for an application using Doug Lea's Util Concurrent * package. * http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.html * <p> * It is a singleton since threads need to be managed vm wide. * <p> * This manager forces you to use a bounded queue. By default it uses the * current thread for execuion when the buffer is full and no free threads can * be created. * <p> * You can specify the props file to use or pass in a properties object prior to * configuration. By default it looks for configuration information in * thread_pool.properties. * <p> * If set, the Properties object will take precedence. * <p> * If a value is not set for a particular pool, the hard coded defaults will be * used. * * <pre> * int boundarySize_DEFAULT = 2000; * * int maximumPoolSize_DEFAULT = 150; * * int minimumPoolSize_DEFAULT = 4; * * int keepAliveTime_DEFAULT = 1000 * 60 * 5; * * boolean abortWhenBlocked = false; * * String whenBlockedPolicy_DEFAULT = IPoolConfiguration.POLICY_RUN; * * int startUpSize_DEFAULT = 4; * </pre> * * You can configure default settings by specifying a default pool in the * properties, ie "cache.ccf" * <p> * @author Aaron Smuts */ public class ThreadPoolManager { private static final Log log = LogFactory.getLog( ThreadPoolManager.class ); // DEFAULT SETTINGS, these are not final since they can be set // via the Propeties file or object private static boolean useBoundary_DEFAULT = true; private static int boundarySize_DEFAULT = 2000; private static int maximumPoolSize_DEFAULT = 150; private static int minimumPoolSize_DEFAULT = 4; private static int keepAliveTime_DEFAULT = 1000 * 60 * 5; private static String whenBlockedPolicy_DEFAULT = IPoolConfiguration.POLICY_RUN; private static int startUpSize_DEFAULT = 4; private static PoolConfiguration defaultConfig; // This is the default value. Setting this after // inialization will have no effect private static String propsFileName = "cache.ccf"; // the root property name private static String PROP_NAME_ROOT = "thread_pool"; private static String DEFAULT_PROP_NAME_ROOT = "thread_pool.default"; // You can specify the properties to be used to configure // the thread pool. Setting this post initialization will have // no effect. private static Properties props = null; private static HashMap pools = new HashMap(); // singleton instance private static ThreadPoolManager INSTANCE = null; /** * No instances please. This is a singleton. */ private ThreadPoolManager() { configure(); } /** * Creates a pool based on the configuration info. * <p> * @param config * @return A ThreadPoll wrapper */ private ThreadPool createPool( PoolConfiguration config ) { PooledExecutor pool = null; Channel queue = null; if ( config.isUseBoundary() ) { if ( log.isDebugEnabled() ) { log.debug( "Creating a Bounded Buffer to use for the pool" ); } queue = new BoundedBuffer( config.getBoundarySize() ); pool = new PooledExecutor( queue, config.getMaximumPoolSize() ); pool.setThreadFactory( new MyThreadFactory() ); } else { if ( log.isDebugEnabled() ) { log.debug( "Creating a non bounded Linked Queue to use for the pool" ); } queue = new LinkedQueue(); pool = new PooledExecutor( queue, config.getMaximumPoolSize() ); } pool.setMinimumPoolSize( config.getMinimumPoolSize() ); pool.setKeepAliveTime( config.getKeepAliveTime() ); // when blocked policy if ( config.getWhenBlockedPolicy().equals( IPoolConfiguration.POLICY_ABORT ) ) { pool.abortWhenBlocked(); } else if ( config.getWhenBlockedPolicy().equals( IPoolConfiguration.POLICY_RUN ) ) { pool.runWhenBlocked(); } else if ( config.getWhenBlockedPolicy().equals( IPoolConfiguration.POLICY_WAIT ) ) { pool.waitWhenBlocked(); } else if ( config.getWhenBlockedPolicy().equals( IPoolConfiguration.POLICY_ABORT ) ) { pool.abortWhenBlocked(); } else if ( config.getWhenBlockedPolicy().equals( IPoolConfiguration.POLICY_DISCARDOLDEST ) ) { pool.discardOldestWhenBlocked(); } pool.createThreads( config.getStartUpSize() ); return new ThreadPool( pool, queue ); } /** * Returns a configured instance of the ThreadPoolManger To specify a * configuation file or Properties object to use call the appropriate setter * prior to calling getInstance. * <p> * @return The single instance of the ThreadPoolManager */ public static synchronized ThreadPoolManager getInstance() { if ( INSTANCE == null ) { INSTANCE = new ThreadPoolManager(); } return INSTANCE; } /** * Returns a pool by name. If a pool by this name does not exist in the * configuration file or properties, one will be created using the default * values. * <p> * Pools are lazily created. * <p> * @param name * @return The thread pool configured for the name. */ public ThreadPool getPool( String name ) { ThreadPool pool = null; synchronized ( pools ) { pool = (ThreadPool) pools.get( name ); if ( pool == null ) { if ( log.isDebugEnabled() ) { log.debug( "Creating pool for name [" + name + "]" ); } PoolConfiguration config = this.loadConfig( PROP_NAME_ROOT + "." + name ); pool = createPool( config ); if ( pool != null ) { pools.put( name, pool ); } if ( log.isDebugEnabled() ) { log.debug( "PoolName = " + getPoolNames() ); } } } return pool; } /** * Returns the names of all configured pools. * <p> * @return ArrayList of string names */ public ArrayList getPoolNames() { ArrayList poolNames = new ArrayList(); synchronized ( pools ) { Set names = pools.keySet(); Iterator it = names.iterator(); while ( it.hasNext() ) { poolNames.add( it.next() ); } } return poolNames; } /** * Setting this post initialization will have no effect. * <p> * @param propsFileName * The propsFileName to set. */ public static void setPropsFileName( String propsFileName ) { ThreadPoolManager.propsFileName = propsFileName; } /** * Returns the name of the properties file that we used to initialize the * pools. If the value was set post-initialization, then it may not be the * file used. * <p> * @return Returns the propsFileName. */ public static String getPropsFileName() { return propsFileName; } /** * This will be used if it is not null on initialzation. Setting this post * initialization will have no effect. * <p> * @param props * The props to set. */ public static void setProps( Properties props ) { ThreadPoolManager.props = props; } /** * @return Returns the props. */ public static Properties getProps() { return props; } /** * Intialize the ThreadPoolManager and create all the pools defined in the * configuration. */ protected void configure() { if ( log.isDebugEnabled() ) { log.debug( "Initializing ThreadPoolManager" ); } if ( props == null ) { try { props = PropertyLoader.loadProperties( propsFileName ); if ( log.isDebugEnabled() ) { log.debug( "File contained " + props.size() + " properties" ); } } catch ( Exception e ) { log.error( "Problem loading properties. propsFileName [" + propsFileName + "]", e ); } } if ( props == null ) { log.warn( "No configuration settings found. Using hardcoded default values for all pools." ); props = new Properties(); } // set intial default and then override if new // settings are available defaultConfig = new PoolConfiguration( useBoundary_DEFAULT, boundarySize_DEFAULT, maximumPoolSize_DEFAULT, minimumPoolSize_DEFAULT, keepAliveTime_DEFAULT, whenBlockedPolicy_DEFAULT, startUpSize_DEFAULT ); defaultConfig = loadConfig( DEFAULT_PROP_NAME_ROOT ); } /** * Configures the default PoolConfiguration settings. * <p> * @param root * @return PoolConfiguration */ protected PoolConfiguration loadConfig( String root ) { PoolConfiguration config = (PoolConfiguration) defaultConfig.clone(); if ( props.containsKey( root + ".useBoundary" ) ) { try { - config.setUseBoundary( Boolean.getBoolean( (String) props.get( root + ".useBoundary" ) ) ); + config.setUseBoundary( Boolean.valueOf( (String) props.get( root + ".useBoundary" ) ) ); } catch ( NumberFormatException nfe ) { log.error( "useBoundary not a boolean.", nfe ); } } // load default if they exist if ( props.containsKey( root + ".boundarySize" ) ) { try { config.setBoundarySize( Integer.parseInt( (String) props.get( root + ".boundarySize" ) ) ); } catch ( NumberFormatException nfe ) { log.error( "boundarySize not a number.", nfe ); } } // maximum pool size if ( props.containsKey( root + ".maximumPoolSize" ) ) { try { config.setMaximumPoolSize( Integer.parseInt( (String) props.get( root + ".maximumPoolSize" ) ) ); } catch ( NumberFormatException nfe ) { log.error( "maximumPoolSize not a number.", nfe ); } } // minimum pool size if ( props.containsKey( root + ".minimumPoolSize" ) ) { try { config.setMinimumPoolSize( Integer.parseInt( (String) props.get( root + ".minimumPoolSize" ) ) ); } catch ( NumberFormatException nfe ) { log.error( "minimumPoolSize not a number.", nfe ); } } // keep alive if ( props.containsKey( root + ".keepAliveTime" ) ) { try { config.setKeepAliveTime( Integer.parseInt( (String) props.get( root + ".keepAliveTime" ) ) ); } catch ( NumberFormatException nfe ) { log.error( "keepAliveTime not a number.", nfe ); } } // when blocked if ( props.containsKey( root + ".whenBlockedPolicy" ) ) { config.setWhenBlockedPolicy( (String) props.get( root + ".whenBlockedPolicy" ) ); } // startupsize if ( props.containsKey( root + ".startUpSize" ) ) { try { config.setStartUpSize( Integer.parseInt( (String) props.get( root + ".startUpSize" ) ) ); } catch ( NumberFormatException nfe ) { log.error( "startUpSize not a number.", nfe ); } } if ( log.isInfoEnabled() ) { log.info( root + " PoolConfiguration = " + config ); } return config; } /** * Allows us to set the daemon status on the threads. * <p> * @author aaronsm */ class MyThreadFactory implements ThreadFactory { /* * (non-Javadoc) * * @see EDU.oswego.cs.dl.util.concurrent.ThreadFactory#newThread(java.lang.Runnable) */ public Thread newThread( Runnable runner ) { Thread t = new Thread( runner ); t.setDaemon( true ); return t; } } }
true
true
protected PoolConfiguration loadConfig( String root ) { PoolConfiguration config = (PoolConfiguration) defaultConfig.clone(); if ( props.containsKey( root + ".useBoundary" ) ) { try { config.setUseBoundary( Boolean.getBoolean( (String) props.get( root + ".useBoundary" ) ) ); } catch ( NumberFormatException nfe ) { log.error( "useBoundary not a boolean.", nfe ); } } // load default if they exist if ( props.containsKey( root + ".boundarySize" ) ) { try { config.setBoundarySize( Integer.parseInt( (String) props.get( root + ".boundarySize" ) ) ); } catch ( NumberFormatException nfe ) { log.error( "boundarySize not a number.", nfe ); } } // maximum pool size if ( props.containsKey( root + ".maximumPoolSize" ) ) { try { config.setMaximumPoolSize( Integer.parseInt( (String) props.get( root + ".maximumPoolSize" ) ) ); } catch ( NumberFormatException nfe ) { log.error( "maximumPoolSize not a number.", nfe ); } } // minimum pool size if ( props.containsKey( root + ".minimumPoolSize" ) ) { try { config.setMinimumPoolSize( Integer.parseInt( (String) props.get( root + ".minimumPoolSize" ) ) ); } catch ( NumberFormatException nfe ) { log.error( "minimumPoolSize not a number.", nfe ); } } // keep alive if ( props.containsKey( root + ".keepAliveTime" ) ) { try { config.setKeepAliveTime( Integer.parseInt( (String) props.get( root + ".keepAliveTime" ) ) ); } catch ( NumberFormatException nfe ) { log.error( "keepAliveTime not a number.", nfe ); } } // when blocked if ( props.containsKey( root + ".whenBlockedPolicy" ) ) { config.setWhenBlockedPolicy( (String) props.get( root + ".whenBlockedPolicy" ) ); } // startupsize if ( props.containsKey( root + ".startUpSize" ) ) { try { config.setStartUpSize( Integer.parseInt( (String) props.get( root + ".startUpSize" ) ) ); } catch ( NumberFormatException nfe ) { log.error( "startUpSize not a number.", nfe ); } } if ( log.isInfoEnabled() ) { log.info( root + " PoolConfiguration = " + config ); } return config; }
protected PoolConfiguration loadConfig( String root ) { PoolConfiguration config = (PoolConfiguration) defaultConfig.clone(); if ( props.containsKey( root + ".useBoundary" ) ) { try { config.setUseBoundary( Boolean.valueOf( (String) props.get( root + ".useBoundary" ) ) ); } catch ( NumberFormatException nfe ) { log.error( "useBoundary not a boolean.", nfe ); } } // load default if they exist if ( props.containsKey( root + ".boundarySize" ) ) { try { config.setBoundarySize( Integer.parseInt( (String) props.get( root + ".boundarySize" ) ) ); } catch ( NumberFormatException nfe ) { log.error( "boundarySize not a number.", nfe ); } } // maximum pool size if ( props.containsKey( root + ".maximumPoolSize" ) ) { try { config.setMaximumPoolSize( Integer.parseInt( (String) props.get( root + ".maximumPoolSize" ) ) ); } catch ( NumberFormatException nfe ) { log.error( "maximumPoolSize not a number.", nfe ); } } // minimum pool size if ( props.containsKey( root + ".minimumPoolSize" ) ) { try { config.setMinimumPoolSize( Integer.parseInt( (String) props.get( root + ".minimumPoolSize" ) ) ); } catch ( NumberFormatException nfe ) { log.error( "minimumPoolSize not a number.", nfe ); } } // keep alive if ( props.containsKey( root + ".keepAliveTime" ) ) { try { config.setKeepAliveTime( Integer.parseInt( (String) props.get( root + ".keepAliveTime" ) ) ); } catch ( NumberFormatException nfe ) { log.error( "keepAliveTime not a number.", nfe ); } } // when blocked if ( props.containsKey( root + ".whenBlockedPolicy" ) ) { config.setWhenBlockedPolicy( (String) props.get( root + ".whenBlockedPolicy" ) ); } // startupsize if ( props.containsKey( root + ".startUpSize" ) ) { try { config.setStartUpSize( Integer.parseInt( (String) props.get( root + ".startUpSize" ) ) ); } catch ( NumberFormatException nfe ) { log.error( "startUpSize not a number.", nfe ); } } if ( log.isInfoEnabled() ) { log.info( root + " PoolConfiguration = " + config ); } return config; }
diff --git a/moskito-webcontrol/java/net/java/dev/moskito/webcontrol/feed/HttpGetter.java b/moskito-webcontrol/java/net/java/dev/moskito/webcontrol/feed/HttpGetter.java index de7cb2a4..3943c1f4 100644 --- a/moskito-webcontrol/java/net/java/dev/moskito/webcontrol/feed/HttpGetter.java +++ b/moskito-webcontrol/java/net/java/dev/moskito/webcontrol/feed/HttpGetter.java @@ -1,49 +1,49 @@ package net.java.dev.moskito.webcontrol.feed; import net.java.dev.moskito.webcontrol.configuration.SourceConfiguration; import org.apache.log4j.Logger; import org.w3c.dom.Document; import org.xml.sax.SAXException; import sun.misc.BASE64Encoder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; public class HttpGetter implements FeedGetter { private static Logger log = Logger.getLogger(HttpGetter.class); @Override public Document retreive(SourceConfiguration source) { System.out.println(source); try { URL url = new URL(source.getUrl()); URLConnection connection = url.openConnection(); if(source.needAuth()) { StringBuilder credentials = new StringBuilder(source.getUsername() + ":" + source.getPassword()); String encoding = new BASE64Encoder().encode(credentials.toString().getBytes()); connection.setRequestProperty("Authorization", "Basic " + encoding); } - if (connection.getContentType().startsWith("text/xml")) { + if (connection.getContentType() != null && connection.getContentType().startsWith("text/xml")) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setIgnoringElementContentWhitespace(true); return dbf.newDocumentBuilder().parse((InputStream) connection.getContent()); } } catch (MalformedURLException e) { log.error("Malformed URL in source configuration : " + source.getUrl()); } catch (IOException e) { log.error("Error retreiving content for source : " + source.getUrl()); } catch (SAXException e) { log.error("Error parsing XML for source configuration : " + source.getUrl(), e); } catch (ParserConfigurationException e) { log.error("Error parsing XML for source configuration : " + source.getUrl(), e); } return null; } }
true
true
public Document retreive(SourceConfiguration source) { System.out.println(source); try { URL url = new URL(source.getUrl()); URLConnection connection = url.openConnection(); if(source.needAuth()) { StringBuilder credentials = new StringBuilder(source.getUsername() + ":" + source.getPassword()); String encoding = new BASE64Encoder().encode(credentials.toString().getBytes()); connection.setRequestProperty("Authorization", "Basic " + encoding); } if (connection.getContentType().startsWith("text/xml")) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setIgnoringElementContentWhitespace(true); return dbf.newDocumentBuilder().parse((InputStream) connection.getContent()); } } catch (MalformedURLException e) { log.error("Malformed URL in source configuration : " + source.getUrl()); } catch (IOException e) { log.error("Error retreiving content for source : " + source.getUrl()); } catch (SAXException e) { log.error("Error parsing XML for source configuration : " + source.getUrl(), e); } catch (ParserConfigurationException e) { log.error("Error parsing XML for source configuration : " + source.getUrl(), e); } return null; }
public Document retreive(SourceConfiguration source) { System.out.println(source); try { URL url = new URL(source.getUrl()); URLConnection connection = url.openConnection(); if(source.needAuth()) { StringBuilder credentials = new StringBuilder(source.getUsername() + ":" + source.getPassword()); String encoding = new BASE64Encoder().encode(credentials.toString().getBytes()); connection.setRequestProperty("Authorization", "Basic " + encoding); } if (connection.getContentType() != null && connection.getContentType().startsWith("text/xml")) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setIgnoringElementContentWhitespace(true); return dbf.newDocumentBuilder().parse((InputStream) connection.getContent()); } } catch (MalformedURLException e) { log.error("Malformed URL in source configuration : " + source.getUrl()); } catch (IOException e) { log.error("Error retreiving content for source : " + source.getUrl()); } catch (SAXException e) { log.error("Error parsing XML for source configuration : " + source.getUrl(), e); } catch (ParserConfigurationException e) { log.error("Error parsing XML for source configuration : " + source.getUrl(), e); } return null; }
diff --git a/src/org/opensolaris/opengrok/util/Executor.java b/src/org/opensolaris/opengrok/util/Executor.java index 68d1ce5a..bcc3ee34 100644 --- a/src/org/opensolaris/opengrok/util/Executor.java +++ b/src/org/opensolaris/opengrok/util/Executor.java @@ -1,286 +1,309 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * See LICENSE.txt included in this distribution for the specific * language governing permissions and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved. */ package org.opensolaris.opengrok.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.Arrays; import java.util.List; import java.util.logging.Level; import org.opensolaris.opengrok.OpenGrokLogger; /** * Wrapper to Java Process API * * @author Emilio Monti - [email protected] */ public class Executor { private List<String> cmdList; private File workingDirectory; private byte[] stdout; private byte[] stderr; /** * Create a new instance of the Executor. * @param cmd An array containing the command to execute */ public Executor(String[] cmd) { this(Arrays.asList(cmd)); } /** * Create a new instance of the Executor. * @param cmdList A list containing the command to execute */ public Executor(List<String> cmdList) { this(cmdList, null); } /** * Create a new instance of the Executor * @param cmdList A list containing the command to execute * @param workingDirectory The directory the process should have as the * working directory */ public Executor(List<String> cmdList, File workingDirectory) { this.cmdList = cmdList; this.workingDirectory = workingDirectory; } /** * Execute the command and collect the output. All exceptions will be * logged. * * @return The exit code of the process */ public int exec() { return exec(true); } /** * Execute the command and collect the output * * @param reportExceptions Should exceptions be added to the log or not * @return The exit code of the process */ public int exec(boolean reportExceptions) { SpoolHandler spoolOut = new SpoolHandler(); int ret = exec(reportExceptions, spoolOut); stdout = spoolOut.getBytes(); return ret; } /** * Execute the command and collect the output * * @param reportExceptions Should exceptions be added to the log or not * @param handler The handler to handle data from standard output * @return The exit code of the process */ public int exec(final boolean reportExceptions, StreamHandler handler) { int ret = -1; + String error = null; ProcessBuilder processBuilder = new ProcessBuilder(cmdList); if (workingDirectory != null) { processBuilder.directory(workingDirectory); if (processBuilder.environment().containsKey("PWD")) { processBuilder.environment().put("PWD", workingDirectory.getAbsolutePath()); } } OpenGrokLogger.getLogger().log(Level.FINE, "Executing command {0} in directory {1}", new Object[] { processBuilder.command(), processBuilder.directory(), }); Process process = null; try { process = processBuilder.start(); final InputStream errorStream = process.getErrorStream(); final SpoolHandler err = new SpoolHandler(); Thread thread = new Thread(new Runnable() { @Override public void run() { try { err.processStream(errorStream); } catch (IOException ex) { if (reportExceptions) { OpenGrokLogger.getLogger().log(Level.SEVERE, "Error during process pipe listening", ex); } } } }); thread.start(); handler.processStream(process.getInputStream()); ret = process.waitFor(); process = null; thread.join(); stderr = err.getBytes(); } catch (IOException e) { if (reportExceptions) { OpenGrokLogger.getLogger().log(Level.SEVERE, "Failed to read from process: " + cmdList.get(0), e); + } else { + error = e.getLocalizedMessage(); } } catch (InterruptedException e) { if (reportExceptions) { OpenGrokLogger.getLogger().log(Level.SEVERE, "Waiting for process interrupted: " + cmdList.get(0), e); + } else { + error = e.getLocalizedMessage(); } } finally { try { if (process != null) { ret = process.exitValue(); } } catch (IllegalThreadStateException e) { process.destroy(); } } if (ret != 0) { - OpenGrokLogger.getLogger().log( - reportExceptions ? Level.SEVERE : Level.FINE, - "Non-zero exit status {0} from command {1} in directory {2}", - new Object[] { - ret, processBuilder.command(), processBuilder.directory() - }); + if (error != null) { + OpenGrokLogger.getLogger().log(Level.WARNING, error); + } else { + int MAX_MSG_SZ = 512; /* limit to avoid floodding the logs */ + StringBuilder msg = new StringBuilder("Non-zero exit status ") + .append(ret).append(" from command ") + .append(processBuilder.command().toString()) + .append(" in directory "); + File cwd = processBuilder.directory(); + if (cwd != null) { + msg.append(cwd.toString()); + } else { + msg.append(System.getProperty("user.dir")); + } + if (stderr != null && stderr.length > 0) { + msg.append(": "); + if (stderr.length > MAX_MSG_SZ) { + msg.append(new String(stderr, 0, MAX_MSG_SZ)).append("..."); + } else { + msg.append(new String(stderr)); + } + } + OpenGrokLogger.getLogger().log(Level.WARNING, msg.toString()); + } } return ret; } /** * Get the output from the process as a string. * * @return The output from the process */ public String getOutputString() { String ret = null; if (stdout != null) { ret = new String(stdout); } return ret; } /** * Get a reader to read the output from the process * * @return A reader reading the process output */ public Reader getOutputReader() { return new InputStreamReader(getOutputStream()); } /** * Get an input stream read the output from the process * * @return A reader reading the process output */ public InputStream getOutputStream() { return new ByteArrayInputStream(stdout); } /** * Get the output from the process written to the error stream as a string. * * @return The error output from the process */ public String getErrorString() { String ret = null; if (stderr != null) { ret = new String(stderr); } return ret; } /** * Get a reader to read the output the process wrote to the error stream. * * @return A reader reading the process error stream */ public Reader getErrorReader() { return new InputStreamReader(getErrorStream()); } /** * Get an inputstreamto read the output the process wrote to the error stream. * * @return An inputstream for reading the process error stream */ public InputStream getErrorStream() { return new ByteArrayInputStream(stderr); } /** * You should use the StreamHandler interface if you would like to process * the output from a process while it is running */ public static interface StreamHandler { /** * Process the data in the stream. The processStream function is * called _once_ during the lifetime of the process, and you should * process all of the input you want before returning from the function. * * @param in The InputStream containing the data * @throws java.io.IOException */ public void processStream(InputStream in) throws IOException; } private static class SpoolHandler implements StreamHandler { private final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); public byte[] getBytes() { return bytes.toByteArray(); } @Override public void processStream(InputStream in) throws IOException { byte[] buffer = new byte[8092]; int len; while ((len = in.read(buffer)) != -1) { if (len > 0) { bytes.write(buffer, 0, len); } } } } }
false
true
public int exec(final boolean reportExceptions, StreamHandler handler) { int ret = -1; ProcessBuilder processBuilder = new ProcessBuilder(cmdList); if (workingDirectory != null) { processBuilder.directory(workingDirectory); if (processBuilder.environment().containsKey("PWD")) { processBuilder.environment().put("PWD", workingDirectory.getAbsolutePath()); } } OpenGrokLogger.getLogger().log(Level.FINE, "Executing command {0} in directory {1}", new Object[] { processBuilder.command(), processBuilder.directory(), }); Process process = null; try { process = processBuilder.start(); final InputStream errorStream = process.getErrorStream(); final SpoolHandler err = new SpoolHandler(); Thread thread = new Thread(new Runnable() { @Override public void run() { try { err.processStream(errorStream); } catch (IOException ex) { if (reportExceptions) { OpenGrokLogger.getLogger().log(Level.SEVERE, "Error during process pipe listening", ex); } } } }); thread.start(); handler.processStream(process.getInputStream()); ret = process.waitFor(); process = null; thread.join(); stderr = err.getBytes(); } catch (IOException e) { if (reportExceptions) { OpenGrokLogger.getLogger().log(Level.SEVERE, "Failed to read from process: " + cmdList.get(0), e); } } catch (InterruptedException e) { if (reportExceptions) { OpenGrokLogger.getLogger().log(Level.SEVERE, "Waiting for process interrupted: " + cmdList.get(0), e); } } finally { try { if (process != null) { ret = process.exitValue(); } } catch (IllegalThreadStateException e) { process.destroy(); } } if (ret != 0) { OpenGrokLogger.getLogger().log( reportExceptions ? Level.SEVERE : Level.FINE, "Non-zero exit status {0} from command {1} in directory {2}", new Object[] { ret, processBuilder.command(), processBuilder.directory() }); } return ret; }
public int exec(final boolean reportExceptions, StreamHandler handler) { int ret = -1; String error = null; ProcessBuilder processBuilder = new ProcessBuilder(cmdList); if (workingDirectory != null) { processBuilder.directory(workingDirectory); if (processBuilder.environment().containsKey("PWD")) { processBuilder.environment().put("PWD", workingDirectory.getAbsolutePath()); } } OpenGrokLogger.getLogger().log(Level.FINE, "Executing command {0} in directory {1}", new Object[] { processBuilder.command(), processBuilder.directory(), }); Process process = null; try { process = processBuilder.start(); final InputStream errorStream = process.getErrorStream(); final SpoolHandler err = new SpoolHandler(); Thread thread = new Thread(new Runnable() { @Override public void run() { try { err.processStream(errorStream); } catch (IOException ex) { if (reportExceptions) { OpenGrokLogger.getLogger().log(Level.SEVERE, "Error during process pipe listening", ex); } } } }); thread.start(); handler.processStream(process.getInputStream()); ret = process.waitFor(); process = null; thread.join(); stderr = err.getBytes(); } catch (IOException e) { if (reportExceptions) { OpenGrokLogger.getLogger().log(Level.SEVERE, "Failed to read from process: " + cmdList.get(0), e); } else { error = e.getLocalizedMessage(); } } catch (InterruptedException e) { if (reportExceptions) { OpenGrokLogger.getLogger().log(Level.SEVERE, "Waiting for process interrupted: " + cmdList.get(0), e); } else { error = e.getLocalizedMessage(); } } finally { try { if (process != null) { ret = process.exitValue(); } } catch (IllegalThreadStateException e) { process.destroy(); } } if (ret != 0) { if (error != null) { OpenGrokLogger.getLogger().log(Level.WARNING, error); } else { int MAX_MSG_SZ = 512; /* limit to avoid floodding the logs */ StringBuilder msg = new StringBuilder("Non-zero exit status ") .append(ret).append(" from command ") .append(processBuilder.command().toString()) .append(" in directory "); File cwd = processBuilder.directory(); if (cwd != null) { msg.append(cwd.toString()); } else { msg.append(System.getProperty("user.dir")); } if (stderr != null && stderr.length > 0) { msg.append(": "); if (stderr.length > MAX_MSG_SZ) { msg.append(new String(stderr, 0, MAX_MSG_SZ)).append("..."); } else { msg.append(new String(stderr)); } } OpenGrokLogger.getLogger().log(Level.WARNING, msg.toString()); } } return ret; }
diff --git a/src/org/apache/xerces/impl/xs/traversers/XSDHandler.java b/src/org/apache/xerces/impl/xs/traversers/XSDHandler.java index d5c59bfa9..f04316018 100644 --- a/src/org/apache/xerces/impl/xs/traversers/XSDHandler.java +++ b/src/org/apache/xerces/impl/xs/traversers/XSDHandler.java @@ -1,1875 +1,1876 @@ /* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999-2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.apache.org. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.xerces.impl.xs.traversers; import org.apache.xerces.impl.xs.XSGrammarBucket; import org.apache.xerces.impl.xs.XSParticleDecl; import org.apache.xerces.impl.xs.XSElementDecl; import org.apache.xerces.impl.xs.SchemaNamespaceSupport; import org.apache.xerces.impl.xs.SchemaGrammar; import org.apache.xerces.impl.xs.XSComplexTypeDecl; import org.apache.xerces.impl.xs.SchemaSymbols; import org.apache.xerces.impl.xs.XSMessageFormatter; import org.apache.xerces.impl.xs.XMLSchemaValidator; import org.apache.xerces.impl.xs.XSDDescription; import org.apache.xerces.impl.xs.XMLSchemaException; import org.apache.xerces.parsers.StandardParserConfiguration; import org.apache.xerces.impl.Constants; import org.apache.xerces.impl.XMLErrorReporter; import org.apache.xerces.impl.XMLEntityManager; import org.apache.xerces.xni.QName; import org.apache.xerces.xni.XMLResourceIdentifier; import org.apache.xerces.xni.XMLAttributes; import org.apache.xerces.xni.parser.XMLConfigurationException; import org.apache.xerces.xni.parser.XMLEntityResolver; import org.apache.xerces.xni.parser.XMLInputSource; import org.apache.xerces.xni.grammars.Grammar; import org.apache.xerces.xni.grammars.XMLGrammarPool; import org.apache.xerces.util.XMLResourceIdentifierImpl; import org.apache.xerces.util.SymbolTable; import org.apache.xerces.util.SymbolHash; import org.apache.xerces.util.DOMUtil; import org.apache.xerces.xni.XMLLocator; import org.apache.xerces.impl.xs.dom.DOMParser; import org.apache.xerces.impl.xs.dom.ElementNSImpl; import org.apache.xerces.impl.xs.util.SimpleLocator; import org.w3c.dom.Document; import org.w3c.dom.Attr; import org.w3c.dom.Element; import org.xml.sax.InputSource; import java.util.Hashtable; import java.util.Stack; import java.util.Vector; import java.util.StringTokenizer; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.IOException; import java.io.Reader; /** * The purpose of this class is to co-ordinate the construction of a * grammar object corresponding to a schema. To do this, it must be * prepared to parse several schema documents (for instance if the * schema document originally referred to contains <include> or * <redefined> information items). If any of the schemas imports a * schema, other grammars may be constructed as a side-effect. * * @author Neil Graham, IBM * @author Pavani Mukthipudi, Sun Microsystems * @version $Id$ */ public class XSDHandler { /** Property identifier: error handler. */ protected static final String ERROR_HANDLER = Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_HANDLER_PROPERTY; /** Property identifier: JAXP schema source. */ protected static final String JAXP_SCHEMA_SOURCE = Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_SOURCE; // data // different sorts of declarations; should make lookup and // traverser calling more efficient/less bulky. final static int ATTRIBUTE_TYPE = 1; final static int ATTRIBUTEGROUP_TYPE = 2; final static int ELEMENT_TYPE = 3; final static int GROUP_TYPE = 4; final static int IDENTITYCONSTRAINT_TYPE = 5; final static int NOTATION_TYPE = 6; final static int TYPEDECL_TYPE = 7; // this string gets appended to redefined names; it's purpose is to be // as unlikely as possible to cause collisions. public final static String REDEF_IDENTIFIER = "_fn3dktizrknc9pi"; // please note the difference between SchemaHandler.EMPTY_STRING and // SchemaSymbols.EMPTY_STRING: // the one in SchemaHandler is only for namespace binding purpose, it's // used as a legal prefix, and it's added to the current symbol table; // while the one in SchemaSymbols is for general purpose: just empty. public String EMPTY_STRING; // //protected data that can be accessable by any traverser // stores <notation> decl protected Hashtable fNotationRegistry = new Hashtable(); // These tables correspond to the symbol spaces defined in the // spec. // They are keyed with a QName (that is, String("URI,localpart) and // their values are nodes corresponding to the given name's decl. // By asking the node for its ownerDocument and looking in // XSDocumentInfoRegistry we can easily get the corresponding // XSDocumentInfo object. private Hashtable fUnparsedAttributeRegistry = new Hashtable(); private Hashtable fUnparsedAttributeGroupRegistry = new Hashtable(); private Hashtable fUnparsedElementRegistry = new Hashtable(); private Hashtable fUnparsedGroupRegistry = new Hashtable(); private Hashtable fUnparsedIdentityConstraintRegistry = new Hashtable(); private Hashtable fUnparsedNotationRegistry = new Hashtable(); private Hashtable fUnparsedTypeRegistry = new Hashtable(); // this is keyed with a documentNode (or the schemaRoot nodes // contained in the XSDocumentInfo objects) and its value is the // XSDocumentInfo object corresponding to that document. // Basically, the function of this registry is to be a link // between the nodes we fetch from calls to the fUnparsed* // arrays and the XSDocumentInfos they live in. private Hashtable fXSDocumentInfoRegistry = new Hashtable(); // this hashtable is keyed on by XSDocumentInfo objects. Its values // are Vectors containing the XSDocumentInfo objects <include>d, // <import>ed or <redefine>d by the key XSDocumentInfo. private Hashtable fDependencyMap = new Hashtable(); // This vector stores strings which are combinations of the // publicId and systemId of the inputSource corresponding to a // schema document. This combination is used so that the user's // EntityResolver can provide a consistent way of identifying a // schema document that is included in multiple other schemas. private Hashtable fTraversed = new Hashtable(); // this hashtable contains a mapping from Document to its systemId // this is useful to resolve a uri relative to the referring document private Hashtable fDoc2SystemId = new Hashtable(); // the primary XSDocumentInfo we were called to parse private XSDocumentInfo fRoot = null; // This hashtable's job is to act as a link between the document // node at the root of the parsed schema's tree and its // XSDocumentInfo object. private Hashtable fDoc2XSDocumentMap = new Hashtable(); // map between <redefine> elements and the XSDocumentInfo // objects that correspond to the documents being redefined. private Hashtable fRedefine2XSDMap = new Hashtable(); // these objects store a mapping between the names of redefining // groups/attributeGroups and the groups/AttributeGroups which // they redefine by restriction (implicitly). It is up to the // Group and AttributeGroup traversers to check these restrictions for // validity. private Hashtable fRedefinedRestrictedAttributeGroupRegistry = new Hashtable(); private Hashtable fRedefinedRestrictedGroupRegistry = new Hashtable(); // a variable storing whether the last schema document // processed (by getSchema) was a duplicate. private boolean fLastSchemaWasDuplicate; // the XMLErrorReporter private XMLErrorReporter fErrorReporter; // the XSAttributeChecker private XSAttributeChecker fAttributeChecker; // this class is to make use of the schema location property values. // we store the namespace/location pairs in a hashtable (use "" as the // namespace of absent namespace). when resolving an entity, we first try // to find in the hashtable whether there is a value for that namespace, // if so, pass that location value to the user-defined entity resolver. protected class LocationResolver { // the user-defined entity resolver public XMLEntityResolver fExternalResolver = null; // namespace/location pairs public Hashtable fLocationPairs = new Hashtable(); public void reset(XMLEntityResolver entityResolver, String sLocation, String nsLocation) { fLocationPairs.clear(); fExternalResolver = entityResolver; if (sLocation != null) { StringTokenizer t = new StringTokenizer(sLocation, " \n\t\r"); String namespace, location; while (t.hasMoreTokens()) { namespace = t.nextToken (); if (!t.hasMoreTokens()) { break; } location = t.nextToken(); fLocationPairs.put(namespace, location); } } if (nsLocation != null) { fLocationPairs.put(EMPTY_STRING, nsLocation); } } public XMLInputSource resolveEntity(XSDDescription desc) throws IOException { if (fExternalResolver == null) return null; String loc = null; // we consider the schema location properties for import if (desc.getContextType() == XSDDescription.CONTEXT_IMPORT || desc.fromInstance()) { // use empty string as the key for absent namespace String namespace = desc.getTargetNamespace(); String ns = namespace == null ? EMPTY_STRING : namespace; // get the location hint for that namespace loc = (String)fLocationPairs.get(ns); } // if it's not import, or if the target namespace is not set // in the schema location properties, use location hint if (loc == null) { String[] hints = desc.getLocationHints(); if (hints != null && hints.length > 0) loc = hints[0]; } String expandedLoc = XMLEntityManager.expandSystemId(loc, desc.getBaseSystemId()); desc.setLiteralSystemId(loc); desc.setExpandedSystemId(expandedLoc); return fExternalResolver.resolveEntity(desc); } } // the schema location resolver private LocationResolver fLocationResolver = new LocationResolver(); // the symbol table private SymbolTable fSymbolTable; // the GrammarResolver private XSGrammarBucket fGrammarBucket; // the Grammar description private XSDDescription fSchemaGrammarDescription; // the Grammar Pool private XMLGrammarPool fGrammarPool; //************ Traversers ********** XSDAttributeGroupTraverser fAttributeGroupTraverser; XSDAttributeTraverser fAttributeTraverser; XSDComplexTypeTraverser fComplexTypeTraverser; XSDElementTraverser fElementTraverser; XSDGroupTraverser fGroupTraverser; XSDKeyrefTraverser fKeyrefTraverser; XSDNotationTraverser fNotationTraverser; XSDSimpleTypeTraverser fSimpleTypeTraverser; XSDUniqueOrKeyTraverser fUniqueOrKeyTraverser; XSDWildcardTraverser fWildCardTraverser; DOMParser fSchemaParser; // these data members are needed for the deferred traversal // of local elements. // the initial size of the array to store deferred local elements private static final int INIT_STACK_SIZE = 30; // the incremental size of the array to store deferred local elements private static final int INC_STACK_SIZE = 10; // current position of the array (# of deferred local elements) private int fLocalElemStackPos = 0; private XSParticleDecl[] fParticle = new XSParticleDecl[INIT_STACK_SIZE]; private Element[] fLocalElementDecl = new Element[INIT_STACK_SIZE]; private int[] fAllContext = new int[INIT_STACK_SIZE]; private String [][] fLocalElemNamespaceContext = new String [INIT_STACK_SIZE][1]; // these data members are needed for the deferred traversal // of keyrefs. // the initial size of the array to store deferred keyrefs private static final int INIT_KEYREF_STACK = 2; // the incremental size of the array to store deferred keyrefs private static final int INC_KEYREF_STACK_AMOUNT = 2; // current position of the array (# of deferred keyrefs) private int fKeyrefStackPos = 0; private Element [] fKeyrefs = new Element[INIT_KEYREF_STACK]; private XSElementDecl [] fKeyrefElems = new XSElementDecl [INIT_KEYREF_STACK]; private String [][] fKeyrefNamespaceContext = new String[INIT_KEYREF_STACK][1]; // Constructors // it should be possible to use the same XSDHandler to parse // multiple schema documents; this will allow one to be // constructed. public XSDHandler (XSGrammarBucket gBucket) { fGrammarBucket = gBucket; // Note: don't use SchemaConfiguration internally // we will get stack overflaw because // XMLSchemaValidator will be instantiating XSDHandler... fSchemaParser = new DOMParser(); fSchemaGrammarDescription = new XSDDescription(); createTraversers(); } // end constructor // This method initiates the parse of a schema. It will likely be // called from the Validator and it will make the // resulting grammar available; it returns a reference to this object just // in case. An ErrorHandler, EntityResolver, XSGrammarBucket and SymbolTable must // already have been set; the last thing this method does is reset // this object (i.e., clean the registries, etc.). public SchemaGrammar parseSchema(XSDDescription desc) { XMLInputSource schemaSource=null; try { schemaSource = fLocationResolver.resolveEntity(desc); } catch (IOException ex) { reportSchemaError(DOC_ERROR_CODES[desc.getContextType()], new Object[]{desc.getLocationHints()[0]}, null); } return parseSchema(schemaSource, desc); } // end parseSchema public SchemaGrammar parseSchema(XMLInputSource is, XSDDescription desc) { String schemaNamespace = desc.getTargetNamespace(); // handle empty string URI as null if (schemaNamespace != null) { schemaNamespace = fSymbolTable.addSymbol(schemaNamespace); } short referType = desc.getContextType(); // before parsing a schema, need to reset all traversers and // clear all registries prepare(); // first phase: construct trees. Document schemaRoot = getSchema(schemaNamespace, is, referType == XSDDescription.CONTEXT_PREPARSE, referType, null); if (schemaRoot == null) { // something went wrong right off the hop return null; } fRoot = constructTrees(schemaRoot, is.getSystemId(), desc); if (fRoot == null) { return fGrammarBucket.getGrammar(schemaNamespace); } // second phase: fill global registries. buildGlobalNameRegistries(); // third phase: call traversers traverseSchemas(); // fourth phase: handle local element decls traverseLocalElements(); // fifth phase: handle Keyrefs resolveKeyRefs(); // sixth phase: validate attribute of non-schema namespaces // REVISIT: skip this for now. we really don't want to do it. //fAttributeChecker.checkNonSchemaAttributes(fGrammarBucket); // and return. return fGrammarBucket.getGrammar(schemaNamespace); } // end parseSchema // may wish to have setter methods for ErrorHandler, // EntityResolver... private static final String[][] NS_ERROR_CODES = { {"src-include.2.1", "src-include.2.1"}, {"src-redefine.3.1", "src-redefine.3.1"}, {"src-import.3.1", "src-import.3.2"}, null, {"TargetNamespace.1", "TargetNamespace.2"}, {"TargetNamespace.1", "TargetNamespace.2"}, {"TargetNamespace.1", "TargetNamespace.2"}, {"TargetNamespace.1", "TargetNamespace.2"} }; private static final String[] ELE_ERROR_CODES = { "src-include.1", "src-redefine.2", "src-import.2", "schema_reference.4", "schema_reference.4", "schema_reference.4", "schema_reference.4", "schema_reference.4" }; // This method does several things: // It constructs an instance of an XSDocumentInfo object using the // schemaRoot node. Then, for each <include>, // <redefine>, and <import> children, it attempts to resolve the // requested schema document, initiates a DOM parse, and calls // itself recursively on that document's root. It also records in // the DependencyMap object what XSDocumentInfo objects its XSDocumentInfo // depends on. // It also makes sure the targetNamespace of the schema it was // called to parse is correct. protected XSDocumentInfo constructTrees(Document schemaRoot, String locationHint, XSDDescription desc) { if (schemaRoot == null) return null; String callerTNS = desc.getTargetNamespace(); short referType = desc.getContextType(); XSDocumentInfo currSchemaInfo = null; try { currSchemaInfo = new XSDocumentInfo(schemaRoot, fAttributeChecker, fSymbolTable); } catch (XMLSchemaException se) { reportSchemaError(ELE_ERROR_CODES[referType], new Object[]{locationHint}, DOMUtil.getRoot(schemaRoot)); return null; } // targetNamespace="" is not valid, issue a warning, and ignore it if (currSchemaInfo.fTargetNamespace != null && currSchemaInfo.fTargetNamespace.length() == 0) { reportSchemaWarning("EmptyTargetNamespace", new Object[]{locationHint}, DOMUtil.getRoot(schemaRoot)); currSchemaInfo.fTargetNamespace = null; } if (callerTNS != null) { // the second index to the NS_ERROR_CODES array // if the caller/expected NS is not absent, we use the first column int secondIdx = 0; // for include and redefine if (referType == XSDDescription.CONTEXT_INCLUDE || referType == XSDDescription.CONTEXT_REDEFINE) { // if the referred document has no targetNamespace, // it's a chameleon schema if (currSchemaInfo.fTargetNamespace == null) { currSchemaInfo.fTargetNamespace = callerTNS; currSchemaInfo.fIsChameleonSchema = true; } // if the referred document has a target namespace differing // from the caller, it's an error else if (callerTNS != currSchemaInfo.fTargetNamespace) { reportSchemaError(NS_ERROR_CODES[referType][secondIdx], new Object [] {callerTNS, currSchemaInfo.fTargetNamespace}, DOMUtil.getRoot(schemaRoot)); } } // for preparse, callerTNS is null, so it's not possible // for instance and import, the two NS's must be the same else if (callerTNS != currSchemaInfo.fTargetNamespace) { reportSchemaError(NS_ERROR_CODES[referType][secondIdx], new Object [] {callerTNS, currSchemaInfo.fTargetNamespace}, DOMUtil.getRoot(schemaRoot)); } } // now there is no caller/expected NS, it's an error for the referred // document to have a target namespace, unless we are preparsing a schema else if (currSchemaInfo.fTargetNamespace != null) { // set the target namespace of the description if (referType == XSDDescription.CONTEXT_PREPARSE) { desc.setTargetNamespace(currSchemaInfo.fTargetNamespace); + callerTNS = currSchemaInfo.fTargetNamespace; } else { // the second index to the NS_ERROR_CODES array // if the caller/expected NS is absent, we use the second column int secondIdx = 1; reportSchemaError(NS_ERROR_CODES[referType][secondIdx], new Object [] {callerTNS, currSchemaInfo.fTargetNamespace}, DOMUtil.getRoot(schemaRoot)); } } // the other cases (callerTNS == currSchemaInfo.fTargetNamespce == null) // are valid // a schema document can always access it's own target namespace currSchemaInfo.addAllowedNS(currSchemaInfo.fTargetNamespace); SchemaGrammar sg = null; // In the case of preparse, if the grammar is not available in the bucket we ask the pool // If the context is instance, the validator would have already consulted the pool if ((sg = fGrammarBucket.getGrammar(currSchemaInfo.fTargetNamespace)) == null && referType == XSDDescription.CONTEXT_PREPARSE) { if (fGrammarPool != null) { sg = (SchemaGrammar)fGrammarPool.retrieveGrammar(desc); if (sg != null) { fGrammarBucket.putGrammar(sg); } } } if (sg == null) { sg = new SchemaGrammar(fSymbolTable, currSchemaInfo.fTargetNamespace, desc.makeClone()); fGrammarBucket.putGrammar(sg); } // we got a grammar of the same namespace in the bucket, should ignore this one else if (referType == XSDDescription.CONTEXT_PREPARSE) { return null; } fDoc2XSDocumentMap.put(schemaRoot, currSchemaInfo); Vector dependencies = new Vector(); Element rootNode = DOMUtil.getRoot(schemaRoot); Document newSchemaRoot = null; for (Element child = DOMUtil.getFirstChildElement(rootNode); child != null; child = DOMUtil.getNextSiblingElement(child)) { String schemaNamespace=null; String schemaHint=null; String localName = DOMUtil.getLocalName(child); short refType = -1; if (localName.equals(SchemaSymbols.ELT_ANNOTATION)) continue; else if (localName.equals(SchemaSymbols.ELT_IMPORT)) { refType = XSDDescription.CONTEXT_IMPORT; // have to handle some validation here too! // call XSAttributeChecker to fill in attrs Object[] includeAttrs = fAttributeChecker.checkAttributes(child, true, currSchemaInfo); schemaHint = (String)includeAttrs[XSAttributeChecker.ATTIDX_SCHEMALOCATION]; schemaNamespace = (String)includeAttrs[XSAttributeChecker.ATTIDX_NAMESPACE]; if (schemaNamespace != null) schemaNamespace = fSymbolTable.addSymbol(schemaNamespace); if (schemaNamespace == currSchemaInfo.fTargetNamespace) { reportSchemaError("src-import.1.1", new Object [] {schemaNamespace}, child); } fAttributeChecker.returnAttrArray(includeAttrs, currSchemaInfo); // a schema document can access it's imported namespaces currSchemaInfo.addAllowedNS(schemaNamespace); fSchemaGrammarDescription.reset(); fSchemaGrammarDescription.setContextType(XSDDescription.CONTEXT_IMPORT); fSchemaGrammarDescription.setBaseSystemId((String)fDoc2SystemId.get(schemaRoot)); fSchemaGrammarDescription.setLocationHints(new String[]{schemaHint}); fSchemaGrammarDescription.setTargetNamespace(schemaNamespace); newSchemaRoot = getSchema(fSchemaGrammarDescription, false, child); } else if ((localName.equals(SchemaSymbols.ELT_INCLUDE)) || (localName.equals(SchemaSymbols.ELT_REDEFINE))) { // validation for redefine/include will be the same here; just // make sure TNS is right (don't care about redef contents // yet). Object[] includeAttrs = fAttributeChecker.checkAttributes(child, true, currSchemaInfo); schemaHint = (String)includeAttrs[XSAttributeChecker.ATTIDX_SCHEMALOCATION]; fAttributeChecker.returnAttrArray(includeAttrs, currSchemaInfo); // schemaLocation is required on <include> and <redefine> if (schemaHint == null) reportSchemaError("s4s-att-must-appear", new Object [] { "<include> or <redefine>", "schemaLocation"}, child); // pass the systemId of the current document as the base systemId boolean mustResolve = false; refType = XSDDescription.CONTEXT_INCLUDE; if(localName.equals(SchemaSymbols.ELT_REDEFINE)) { mustResolve = nonAnnotationContent(child); refType = XSDDescription.CONTEXT_REDEFINE; } fSchemaGrammarDescription.reset(); fSchemaGrammarDescription.setContextType(refType); fSchemaGrammarDescription.setBaseSystemId((String)fDoc2SystemId.get(schemaRoot)); fSchemaGrammarDescription.setLocationHints(new String[]{schemaHint}); fSchemaGrammarDescription.setTargetNamespace(callerTNS); newSchemaRoot = getSchema(fSchemaGrammarDescription, mustResolve, child); schemaNamespace = currSchemaInfo.fTargetNamespace; } else { // no more possibility of schema references in well-formed // schema... break; } // If the schema is duplicate, we needn't call constructTrees() again. // To handle mutual <include>s XSDocumentInfo newSchemaInfo = null; if (fLastSchemaWasDuplicate) { newSchemaInfo = (XSDocumentInfo)fDoc2XSDocumentMap.get(newSchemaRoot); } else { newSchemaInfo = constructTrees(newSchemaRoot, schemaHint, fSchemaGrammarDescription); } if (localName.equals(SchemaSymbols.ELT_REDEFINE) && newSchemaInfo != null) { // must record which schema we're redefining so that we can // rename the right things later! fRedefine2XSDMap.put(child, newSchemaInfo); } if (newSchemaRoot != null) { if (newSchemaInfo != null) dependencies.addElement(newSchemaInfo); newSchemaRoot = null; } } fDependencyMap.put(currSchemaInfo, dependencies); return currSchemaInfo; } // end constructTrees // This method builds registries for all globally-referenceable // names. A registry will be built for each symbol space defined // by the spec. It is also this method's job to rename redefined // components, and to record which components redefine others (so // that implicit redefinitions of groups and attributeGroups can be handled). protected void buildGlobalNameRegistries() { /* Starting with fRoot, we examine each child of the schema * element. Skipping all imports and includes, we record the names * of all other global components (and children of <redefine>). We * also put <redefine> names in a registry that we look through in * case something needs renaming. Once we're done with a schema we * set its Document node to hidden so that we don't try to traverse * it again; then we look to its Dependency map entry. We keep a * stack of schemas that we haven't yet finished processing; this * is a depth-first traversal. */ Stack schemasToProcess = new Stack(); schemasToProcess.push(fRoot); while (!schemasToProcess.empty()) { XSDocumentInfo currSchemaDoc = (XSDocumentInfo)schemasToProcess.pop(); Document currDoc = currSchemaDoc.fSchemaDoc; if (DOMUtil.isHidden(currDoc)) { // must have processed this already! continue; } Element currRoot = DOMUtil.getRoot(currDoc); // process this schema's global decls boolean dependenciesCanOccur = true; for (Element globalComp = DOMUtil.getFirstChildElement(currRoot); globalComp != null; globalComp = DOMUtil.getNextSiblingElement(globalComp)) { // this loop makes sure the <schema> element ordering is // also valid. if (DOMUtil.getLocalName(globalComp).equals(SchemaSymbols.ELT_ANNOTATION)) { //skip it; traverse it later continue; } else if (DOMUtil.getLocalName(globalComp).equals(SchemaSymbols.ELT_INCLUDE) || DOMUtil.getLocalName(globalComp).equals(SchemaSymbols.ELT_IMPORT)) { if (!dependenciesCanOccur) { reportSchemaError("sch-props-correct.1", new Object [] {DOMUtil.getLocalName(globalComp)}, globalComp); } // we've dealt with this; mark as traversed DOMUtil.setHidden(globalComp); } else if (DOMUtil.getLocalName(globalComp).equals(SchemaSymbols.ELT_REDEFINE)) { if (!dependenciesCanOccur) { reportSchemaError("sch-props-correct.1", new Object [] {DOMUtil.getLocalName(globalComp)}, globalComp); } for (Element redefineComp = DOMUtil.getFirstChildElement(globalComp); redefineComp != null; redefineComp = DOMUtil.getNextSiblingElement(redefineComp)) { String lName = DOMUtil.getAttrValue(redefineComp, SchemaSymbols.ATT_NAME); if (lName.length() == 0) // an error we'll catch later continue; String qName = currSchemaDoc.fTargetNamespace == null ? ","+lName: currSchemaDoc.fTargetNamespace +","+lName; String componentType = DOMUtil.getLocalName(redefineComp); if (componentType.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) { checkForDuplicateNames(qName, fUnparsedAttributeGroupRegistry, redefineComp, currSchemaDoc); // the check will have changed our name; String targetLName = DOMUtil.getAttrValue(redefineComp, SchemaSymbols.ATT_NAME)+REDEF_IDENTIFIER; // and all we need to do is error-check+rename our kkids: renameRedefiningComponents(currSchemaDoc, redefineComp, SchemaSymbols.ELT_ATTRIBUTEGROUP, lName, targetLName); } else if ((componentType.equals(SchemaSymbols.ELT_COMPLEXTYPE)) || (componentType.equals(SchemaSymbols.ELT_SIMPLETYPE))) { checkForDuplicateNames(qName, fUnparsedTypeRegistry, redefineComp, currSchemaDoc); // the check will have changed our name; String targetLName = DOMUtil.getAttrValue(redefineComp, SchemaSymbols.ATT_NAME) + REDEF_IDENTIFIER; // and all we need to do is error-check+rename our kkids: if (componentType.equals(SchemaSymbols.ELT_COMPLEXTYPE)) { renameRedefiningComponents(currSchemaDoc, redefineComp, SchemaSymbols.ELT_COMPLEXTYPE, lName, targetLName); } else { // must be simpleType renameRedefiningComponents(currSchemaDoc, redefineComp, SchemaSymbols.ELT_SIMPLETYPE, lName, targetLName); } } else if (componentType.equals(SchemaSymbols.ELT_GROUP)) { checkForDuplicateNames(qName, fUnparsedGroupRegistry, redefineComp, currSchemaDoc); // the check will have changed our name; String targetLName = DOMUtil.getAttrValue(redefineComp, SchemaSymbols.ATT_NAME)+REDEF_IDENTIFIER; // and all we need to do is error-check+rename our kids: renameRedefiningComponents(currSchemaDoc, redefineComp, SchemaSymbols.ELT_GROUP, lName, targetLName); } } // end march through <redefine> children // and now set as traversed //DOMUtil.setHidden(globalComp); } else { dependenciesCanOccur = false; String lName = DOMUtil.getAttrValue(globalComp, SchemaSymbols.ATT_NAME); if (lName.length() == 0) // an error we'll catch later continue; String qName = currSchemaDoc.fTargetNamespace == null? ","+lName: currSchemaDoc.fTargetNamespace +","+lName; String componentType = DOMUtil.getLocalName(globalComp); if (componentType.equals(SchemaSymbols.ELT_ATTRIBUTE)) { checkForDuplicateNames(qName, fUnparsedAttributeRegistry, globalComp, currSchemaDoc); } else if (componentType.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) { checkForDuplicateNames(qName, fUnparsedAttributeGroupRegistry, globalComp, currSchemaDoc); } else if ((componentType.equals(SchemaSymbols.ELT_COMPLEXTYPE)) || (componentType.equals(SchemaSymbols.ELT_SIMPLETYPE))) { checkForDuplicateNames(qName, fUnparsedTypeRegistry, globalComp, currSchemaDoc); } else if (componentType.equals(SchemaSymbols.ELT_ELEMENT)) { checkForDuplicateNames(qName, fUnparsedElementRegistry, globalComp, currSchemaDoc); } else if (componentType.equals(SchemaSymbols.ELT_GROUP)) { checkForDuplicateNames(qName, fUnparsedGroupRegistry, globalComp, currSchemaDoc); } else if (componentType.equals(SchemaSymbols.ELT_NOTATION)) { checkForDuplicateNames(qName, fUnparsedNotationRegistry, globalComp, currSchemaDoc); } } } // end for // now we're done with this one! DOMUtil.setHidden(currDoc); // now add the schemas this guy depends on Vector currSchemaDepends = (Vector)fDependencyMap.get(currSchemaDoc); for (int i = 0; i < currSchemaDepends.size(); i++) { schemasToProcess.push(currSchemaDepends.elementAt(i)); } } // while } // end buildGlobalNameRegistries // Beginning at the first schema processing was requested for // (fRoot), this method // examines each child (global schema information item) of each // schema document (and of each <redefine> element) // corresponding to an XSDocumentInfo object. If the // readOnly field on that node has not been set, it calls an // appropriate traverser to traverse it. Once all global decls in // an XSDocumentInfo object have been traversed, it marks that object // as traversed (or hidden) in order to avoid infinite loops. It completes // when it has visited all XSDocumentInfo objects in the // DependencyMap and marked them as traversed. protected void traverseSchemas() { // the process here is very similar to that in // buildGlobalRegistries, except we can't set our schemas as // hidden for a second time; so make them all visible again // first! setSchemasVisible(fRoot); Stack schemasToProcess = new Stack(); schemasToProcess.push(fRoot); while (!schemasToProcess.empty()) { XSDocumentInfo currSchemaDoc = (XSDocumentInfo)schemasToProcess.pop(); Document currDoc = currSchemaDoc.fSchemaDoc; SchemaGrammar currSG = fGrammarBucket.getGrammar(currSchemaDoc.fTargetNamespace); if (DOMUtil.isHidden(currDoc)) { // must have processed this already! continue; } Element currRoot = DOMUtil.getRoot(currDoc); // traverse this schema's global decls for (Element globalComp = DOMUtil.getFirstVisibleChildElement(currRoot); globalComp != null; globalComp = DOMUtil.getNextVisibleSiblingElement(globalComp)) { // We'll always want to set this as hidden! DOMUtil.setHidden(globalComp); String componentType = DOMUtil.getLocalName(globalComp); // includes and imports will not show up here! if (DOMUtil.getLocalName(globalComp).equals(SchemaSymbols.ELT_REDEFINE)) { for (Element redefinedComp = DOMUtil.getFirstVisibleChildElement(globalComp); redefinedComp != null; redefinedComp = DOMUtil.getNextVisibleSiblingElement(redefinedComp)) { String redefinedComponentType = DOMUtil.getLocalName(redefinedComp); DOMUtil.setHidden(redefinedComp); if (redefinedComponentType.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) { fAttributeGroupTraverser.traverseGlobal(redefinedComp, currSchemaDoc, currSG); } else if (redefinedComponentType.equals(SchemaSymbols.ELT_COMPLEXTYPE)) { fComplexTypeTraverser.traverseGlobal(redefinedComp, currSchemaDoc, currSG); } else if (redefinedComponentType.equals(SchemaSymbols.ELT_GROUP)) { fGroupTraverser.traverseGlobal(redefinedComp, currSchemaDoc, currSG); } else if (redefinedComponentType.equals(SchemaSymbols.ELT_SIMPLETYPE)) { fSimpleTypeTraverser.traverseGlobal(redefinedComp, currSchemaDoc, currSG); } else if (redefinedComponentType.equals(SchemaSymbols.ELT_ANNOTATION)) { // REVISIT: according to 3.13.2 the PSVI needs the parent's attributes; // thus this should be done in buildGlobalNameRegistries not here... fElementTraverser.traverseAnnotationDecl(redefinedComp, null, true, currSchemaDoc); } else { reportSchemaError("src-redefine", new Object [] {componentType}, redefinedComp); } } // end march through <redefine> children } else if (componentType.equals(SchemaSymbols.ELT_ATTRIBUTE)) { fAttributeTraverser.traverseGlobal(globalComp, currSchemaDoc, currSG); } else if (componentType.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) { fAttributeGroupTraverser.traverseGlobal(globalComp, currSchemaDoc, currSG); } else if (componentType.equals(SchemaSymbols.ELT_COMPLEXTYPE)) { fComplexTypeTraverser.traverseGlobal(globalComp, currSchemaDoc, currSG); } else if (componentType.equals(SchemaSymbols.ELT_ELEMENT)) { fElementTraverser.traverseGlobal(globalComp, currSchemaDoc, currSG); } else if (componentType.equals(SchemaSymbols.ELT_GROUP)) { fGroupTraverser.traverseGlobal(globalComp, currSchemaDoc, currSG); } else if (componentType.equals(SchemaSymbols.ELT_NOTATION)) { fNotationTraverser.traverse(globalComp, currSchemaDoc, currSG); } else if (componentType.equals(SchemaSymbols.ELT_SIMPLETYPE)) { fSimpleTypeTraverser.traverseGlobal(globalComp, currSchemaDoc, currSG); } else if (componentType.equals(SchemaSymbols.ELT_ANNOTATION)) { // REVISIT: according to 3.13.2 the PSVI needs the parent's attributes; // thus this should be done in buildGlobalNameRegistries not here... fElementTraverser.traverseAnnotationDecl(globalComp, null, true, currSchemaDoc); } else { reportSchemaError("sch-props-correct.1", new Object [] {DOMUtil.getLocalName(globalComp)}, globalComp); } } // end for // now we're done with this one! DOMUtil.setHidden(currDoc); // now add the schemas this guy depends on Vector currSchemaDepends = (Vector)fDependencyMap.get(currSchemaDoc); for (int i = 0; i < currSchemaDepends.size(); i++) { schemasToProcess.push(currSchemaDepends.elementAt(i)); } } // while } // end traverseSchemas private static final String[] COMP_TYPE = { null, // index 0 "attribute declaration", "attribute group", "elment declaration", "group", "identity constraint", "notation", "type definition", }; // since it is forbidden for traversers to talk to each other // directly (except wen a traverser encounters a local declaration), // this provides a generic means for a traverser to call // for the traversal of some declaration. An XSDocumentInfo is // required because the XSDocumentInfo that the traverser is traversing // may bear no relation to the one the handler is operating on. // This method will: // 1. See if a global definition matching declToTraverse exists; // 2. if so, determine if there is a path from currSchema to the // schema document where declToTraverse lives (i.e., do a lookup // in DependencyMap); // 3. depending on declType (which will be relevant to step 1 as // well), call the appropriate traverser with the appropriate // XSDocumentInfo object. // This method returns whatever the traverser it called returned; // this will be an Object of some kind // that lives in the Grammar. protected Object getGlobalDecl(XSDocumentInfo currSchema, int declType, QName declToTraverse, Element elmNode) { // from the schema spec, all built-in types are present in all schemas, // so if the requested component is a type, and could be found in the // default schema grammar, we should return that type. // otherwise (since we would support user-defined schema grammar) we'll // use the normal way to get the decl if (declToTraverse.uri != null && declToTraverse.uri == SchemaSymbols.URI_SCHEMAFORSCHEMA) { if (declType == TYPEDECL_TYPE) { Object retObj = SchemaGrammar.SG_SchemaNS.getGlobalTypeDecl(declToTraverse.localpart); if (retObj != null) return retObj; } } // now check whether this document can access the requsted namespace if (!currSchema.isAllowedNS(declToTraverse.uri)) { // cannot get to this schema from the one containing the requesting decl reportSchemaError("src-resolve.4", new Object[]{fDoc2SystemId.get(currSchema.fSchemaDoc), declToTraverse.uri}, elmNode); return null; } // check whether there is grammar for the requested namespace SchemaGrammar sGrammar = fGrammarBucket.getGrammar(declToTraverse.uri); if (sGrammar == null) { reportSchemaError("src-resolve", new Object[]{declToTraverse.rawname, COMP_TYPE[declType]}, elmNode); return null; } // if there is such grammar, check whether the requested component is in the grammar Object retObj = null; switch (declType) { case ATTRIBUTE_TYPE : retObj = sGrammar.getGlobalAttributeDecl(declToTraverse.localpart); break; case ATTRIBUTEGROUP_TYPE : retObj = sGrammar.getGlobalAttributeGroupDecl(declToTraverse.localpart); break; case ELEMENT_TYPE : retObj = sGrammar.getGlobalElementDecl(declToTraverse.localpart); break; case GROUP_TYPE : retObj = sGrammar.getGlobalGroupDecl(declToTraverse.localpart); break; case IDENTITYCONSTRAINT_TYPE : retObj = sGrammar.getIDConstraintDecl(declToTraverse.localpart); break; case NOTATION_TYPE : retObj = sGrammar.getNotationDecl(declToTraverse.localpart); break; case TYPEDECL_TYPE : retObj = sGrammar.getGlobalTypeDecl(declToTraverse.localpart); break; } // if the component is parsed, return it if (retObj != null) return retObj; XSDocumentInfo schemaWithDecl = null; Element decl = null; // the component is not parsed, try to find a DOM element for it String declKey = declToTraverse.uri == null? ","+declToTraverse.localpart: declToTraverse.uri+","+declToTraverse.localpart; switch (declType) { case ATTRIBUTE_TYPE : decl = (Element)fUnparsedAttributeRegistry.get(declKey); break; case ATTRIBUTEGROUP_TYPE : decl = (Element)fUnparsedAttributeGroupRegistry.get(declKey); break; case ELEMENT_TYPE : decl = (Element)fUnparsedElementRegistry.get(declKey); break; case GROUP_TYPE : decl = (Element)fUnparsedGroupRegistry.get(declKey); break; case IDENTITYCONSTRAINT_TYPE : decl = (Element)fUnparsedIdentityConstraintRegistry.get(declKey); break; case NOTATION_TYPE : decl = (Element)fUnparsedNotationRegistry.get(declKey); break; case TYPEDECL_TYPE : decl = (Element)fUnparsedTypeRegistry.get(declKey); break; default: reportSchemaError("Internal-Error", new Object [] {"XSDHandler asked to locate component of type " + declType + "; it does not recognize this type!"}, elmNode); } // no DOM element found, so the component can't be located if (decl == null) { reportSchemaError("src-resolve", new Object[]{declToTraverse.rawname, COMP_TYPE[declType]}, elmNode); return null; } // get the schema doc containing the component to be parsed // it should always return non-null value, but since null-checking // comes for free, let's be safe and check again schemaWithDecl = findXSDocumentForDecl(currSchema, decl); if (schemaWithDecl == null) { // cannot get to this schema from the one containing the requesting decl reportSchemaError("src-resolve.4", new Object[]{fDoc2SystemId.get(currSchema.fSchemaDoc), declToTraverse.uri}, elmNode); return null; } // a component is hidden, meaning either it's traversed, or being traversed. // but we didn't find it in the grammar, so it's the latter case, and // a circular reference. error! if (DOMUtil.isHidden(decl)) { // decl must not be null if we're here... reportSchemaError("st-props-correct.2", new Object [] {declToTraverse.prefix+":"+declToTraverse.localpart}, elmNode); return null; } // hide the element node before traversing it DOMUtil.setHidden(decl); // back up the current SchemaNamespaceSupport, because we need to provide // a fresh one to the traverseGlobal methods. schemaWithDecl.backupNSSupport(); // traverse the referenced global component switch (declType) { case ATTRIBUTE_TYPE : retObj = fAttributeTraverser.traverseGlobal(decl, schemaWithDecl, sGrammar); break; case ATTRIBUTEGROUP_TYPE : retObj = fAttributeGroupTraverser.traverseGlobal(decl, schemaWithDecl, sGrammar); break; case ELEMENT_TYPE : retObj = fElementTraverser.traverseGlobal(decl, schemaWithDecl, sGrammar); break; case GROUP_TYPE : retObj = fGroupTraverser.traverseGlobal(decl, schemaWithDecl, sGrammar); break; case IDENTITYCONSTRAINT_TYPE : // identity constraints should have been parsed already... // we should never get here retObj = null; break; case NOTATION_TYPE : retObj = fNotationTraverser.traverse(decl, schemaWithDecl, sGrammar); break; case TYPEDECL_TYPE : if (DOMUtil.getLocalName(decl).equals(SchemaSymbols.ELT_COMPLEXTYPE)) retObj = fComplexTypeTraverser.traverseGlobal(decl, schemaWithDecl, sGrammar); else retObj = fSimpleTypeTraverser.traverseGlobal(decl, schemaWithDecl, sGrammar); } // restore the previous SchemaNamespaceSupport, so that the caller can get // proper namespace binding. schemaWithDecl.restoreNSSupport(); return retObj; } // getGlobalDecl(XSDocumentInfo, int, QName): Object // This method determines whether there is a group // (attributeGroup) which the given one has redefined by // restriction. If so, it returns it; else it returns null. // @param type: whether what's been redefined is an // attributeGroup or a group; // @param name: the QName of the component doing the redefining. // @param currSchema: schema doc in which the redefining component lives. // @return: Object representing decl redefined if present, null // otherwise. Object getGrpOrAttrGrpRedefinedByRestriction(int type, QName name, XSDocumentInfo currSchema, Element elmNode) { String realName = name.uri != null?name.uri+","+name.localpart: ","+name.localpart; String nameToFind = null; switch (type) { case ATTRIBUTEGROUP_TYPE: nameToFind = (String)fRedefinedRestrictedAttributeGroupRegistry.get(realName); break; case GROUP_TYPE: nameToFind = (String)fRedefinedRestrictedGroupRegistry.get(realName); break; default: return null; } if (nameToFind == null) return null; int commaPos = nameToFind.indexOf(","); QName qNameToFind = new QName(EMPTY_STRING, nameToFind.substring(commaPos+1), nameToFind.substring(commaPos), (commaPos == 0)? null : nameToFind.substring(0, commaPos)); Object retObj = getGlobalDecl(currSchema, type, qNameToFind, elmNode); if(retObj == null) { switch (type) { case ATTRIBUTEGROUP_TYPE: reportSchemaError("src-redefine.7.2.1", new Object []{name.localpart}, elmNode); break; case GROUP_TYPE: reportSchemaError("src-redefine.6.2.1", new Object []{name.localpart}, elmNode); break; } return null; } return retObj; } // getGrpOrAttrGrpRedefinedByRestriction(int, QName, XSDocumentInfo): Object // Since ID constraints can occur in local elements, unless we // wish to completely traverse all our DOM trees looking for ID // constraints while we're building our global name registries, // which seems terribly inefficient, we need to resolve keyrefs // after all parsing is complete. This we can simply do by running through // fIdentityConstraintRegistry and calling traverseKeyRef on all // of the KeyRef nodes. This unfortunately removes this knowledge // from the elementTraverser class (which must ignore keyrefs), // but there seems to be no efficient way around this... protected void resolveKeyRefs() { for (int i=0; i<fKeyrefStackPos; i++) { Document keyrefDoc = DOMUtil.getDocument(fKeyrefs[i]); XSDocumentInfo keyrefSchemaDoc = (XSDocumentInfo)fDoc2XSDocumentMap.get(keyrefDoc); keyrefSchemaDoc.fNamespaceSupport.makeGlobal(); keyrefSchemaDoc.fNamespaceSupport.setEffectiveContext( fKeyrefNamespaceContext[i] ); SchemaGrammar keyrefGrammar = fGrammarBucket.getGrammar(keyrefSchemaDoc.fTargetNamespace); // need to set <keyref> to hidden before traversing it, // because it has global scope DOMUtil.setHidden(fKeyrefs[i]); fKeyrefTraverser.traverse(fKeyrefs[i], fKeyrefElems[i], keyrefSchemaDoc, keyrefGrammar); } } // end resolveKeyRefs // an accessor method. Just makes sure callers // who want the Identity constraint registry vaguely know what they're about. protected Hashtable getIDRegistry() { return fUnparsedIdentityConstraintRegistry; } // This method squirrels away <keyref> declarations--along with the element // decls and namespace bindings they might find handy. protected void storeKeyRef (Element keyrefToStore, XSDocumentInfo schemaDoc, XSElementDecl currElemDecl) { String keyrefName = DOMUtil.getAttrValue(keyrefToStore, SchemaSymbols.ATT_NAME); if (keyrefName.length() != 0) { String keyrefQName = schemaDoc.fTargetNamespace == null? "," + keyrefName: schemaDoc.fTargetNamespace+","+keyrefName; checkForDuplicateNames(keyrefQName, fUnparsedIdentityConstraintRegistry, keyrefToStore, schemaDoc); } // now set up all the registries we'll need... // check array sizes if (fKeyrefStackPos == fKeyrefs.length) { Element [] elemArray = new Element [fKeyrefStackPos + INC_KEYREF_STACK_AMOUNT]; System.arraycopy(fKeyrefs, 0, elemArray, 0, fKeyrefStackPos); fKeyrefs = elemArray; XSElementDecl [] declArray = new XSElementDecl [fKeyrefStackPos + INC_KEYREF_STACK_AMOUNT]; System.arraycopy(fKeyrefElems, 0, declArray, 0, fKeyrefStackPos); fKeyrefElems = declArray; String[][] stringArray = new String [fKeyrefStackPos + INC_KEYREF_STACK_AMOUNT][]; System.arraycopy(fKeyrefNamespaceContext, 0, stringArray, 0, fKeyrefStackPos); fKeyrefNamespaceContext = stringArray; } fKeyrefs[fKeyrefStackPos] = keyrefToStore; fKeyrefElems[fKeyrefStackPos] = currElemDecl; fKeyrefNamespaceContext[fKeyrefStackPos++] = schemaDoc.fNamespaceSupport.getEffectiveLocalContext(); } // storeKeyref (Element, XSDocumentInfo, XSElementDecl): void private static final String[] DOC_ERROR_CODES = { "src-include.0", "src-redefine.0", "src-import.0", "schema_reference.4", "schema_reference.4", "schema_reference.4", "schema_reference.4", "schema_reference.4" }; // This method is responsible for schema resolution. If it finds // a schema document that the XMLEntityResolver resolves to with // the given namespace and hint, it returns it. It returns true // if this is the first time it's seen this document, false // otherwise. schemaDoc is null if and only if no schema document // was resolved to. private Document getSchema(XSDDescription desc, boolean mustResolve, Element referElement) { XMLInputSource schemaSource=null; try { schemaSource = fLocationResolver.resolveEntity(desc); } catch (IOException ex) { if (mustResolve) { reportSchemaError(DOC_ERROR_CODES[desc.getContextType()], new Object[]{desc.getLocationHints()[0]}, referElement); } else { reportSchemaWarning(DOC_ERROR_CODES[desc.getContextType()], new Object[]{desc.getLocationHints()[0]}, referElement); } } return getSchema(desc.getTargetNamespace(), schemaSource, mustResolve, desc.getContextType(), referElement); } // getSchema(String, String, String, boolean, short): Document private Document getSchema(String schemaNamespace, XMLInputSource schemaSource, boolean mustResolve, short referType, Element referElement) { boolean hasInput = true; // contents of this method will depend on the system we adopt for entity resolution--i.e., XMLEntityHandler, EntityHandler, etc. Document schemaDoc = null; try { // when the system id and byte stream and character stream // of the input source are all null, it's // impossible to find the schema document. so we skip in // this case. otherwise we'll receive some NPE or // file not found errors. but schemaHint=="" is perfectly // legal for import. if (schemaSource != null && (schemaSource.getSystemId() != null || schemaSource.getByteStream() != null || schemaSource.getCharacterStream() != null)) { // When the system id of the input source is used, first try to // expand it, and check whether the same document has been // parsed before. If so, return the document corresponding to // that system id. String schemaId = null; XSDKey key = null; if (schemaSource.getByteStream() == null && schemaSource.getCharacterStream() == null) { schemaId = XMLEntityManager.expandSystemId(schemaSource.getSystemId(), schemaSource.getBaseSystemId()); key = new XSDKey(schemaId, referType, schemaNamespace); if (fTraversed.get(key) != null) { fLastSchemaWasDuplicate = true; return(Document)(fTraversed.get(key)); } } fSchemaParser.reset(); fSchemaParser.parse(schemaSource); schemaDoc = fSchemaParser.getDocument(); // now we need to store the mapping information from system id // to the document. also from the document to the system id. if (schemaId != null) { fTraversed.put(key, schemaDoc ); fDoc2SystemId.put(schemaDoc, schemaId ); } fLastSchemaWasDuplicate = false; return schemaDoc; } else { hasInput = false; } } catch (IOException ex) { } // either an error occured (exception), or empty input source was // returned, we need to report an error or a warning if (mustResolve) { reportSchemaError(DOC_ERROR_CODES[referType], new Object[]{schemaSource.getSystemId()}, referElement); } else if (hasInput) { reportSchemaWarning(DOC_ERROR_CODES[referType], new Object[]{schemaSource.getSystemId()}, referElement); } fLastSchemaWasDuplicate = false; return null; } // getSchema(String, XMLInputSource, boolean, boolean): Document // initialize all the traversers. // this should only need to be called once during the construction // of this object; it creates the traversers that will be used to // construct schemaGrammars. private void createTraversers() { fAttributeChecker = new XSAttributeChecker(this); fAttributeGroupTraverser = new XSDAttributeGroupTraverser(this, fAttributeChecker); fAttributeTraverser = new XSDAttributeTraverser(this, fAttributeChecker); fComplexTypeTraverser = new XSDComplexTypeTraverser(this, fAttributeChecker); fElementTraverser = new XSDElementTraverser(this, fAttributeChecker); fGroupTraverser = new XSDGroupTraverser(this, fAttributeChecker); fKeyrefTraverser = new XSDKeyrefTraverser(this, fAttributeChecker); fNotationTraverser = new XSDNotationTraverser(this, fAttributeChecker); fSimpleTypeTraverser = new XSDSimpleTypeTraverser(this, fAttributeChecker); fUniqueOrKeyTraverser = new XSDUniqueOrKeyTraverser(this, fAttributeChecker); fWildCardTraverser = new XSDWildcardTraverser(this, fAttributeChecker); } // createTraversers() // before parsing a schema, need to reset all traversers and // clear all registries void prepare() { fUnparsedAttributeRegistry.clear(); fUnparsedAttributeGroupRegistry.clear(); fUnparsedElementRegistry.clear(); fUnparsedGroupRegistry.clear(); fUnparsedIdentityConstraintRegistry.clear(); fUnparsedNotationRegistry.clear(); fUnparsedTypeRegistry.clear(); fXSDocumentInfoRegistry.clear(); fDependencyMap.clear(); fTraversed.clear(); fDoc2SystemId.clear(); fDoc2XSDocumentMap.clear(); fRedefine2XSDMap.clear(); fRoot = null; fLastSchemaWasDuplicate = false; // clear local element stack for (int i = 0; i < fLocalElemStackPos; i++) { fParticle[i] = null; fLocalElementDecl[i] = null; fLocalElemNamespaceContext[i] = null; } fLocalElemStackPos = 0; // and do same for keyrefs. for (int i = 0; i < fKeyrefStackPos; i++) { fKeyrefs[i] = null; fKeyrefElems[i] = null; fKeyrefNamespaceContext[i] = null; } fKeyrefStackPos = 0; // reset traversers fAttributeChecker.reset(fSymbolTable); fAttributeGroupTraverser.reset(fSymbolTable); fAttributeTraverser.reset(fSymbolTable); fComplexTypeTraverser.reset(fSymbolTable); fElementTraverser.reset(fSymbolTable); fGroupTraverser.reset(fSymbolTable); fKeyrefTraverser.reset(fSymbolTable); fNotationTraverser.reset(fSymbolTable); fSimpleTypeTraverser.reset(fSymbolTable); fUniqueOrKeyTraverser.reset(fSymbolTable); fWildCardTraverser.reset(fSymbolTable); fRedefinedRestrictedAttributeGroupRegistry.clear(); fRedefinedRestrictedGroupRegistry.clear(); } // this method reset properties that might change between parses. // and process the jaxp schemaSource property public void reset(XMLErrorReporter errorReporter, XMLEntityResolver entityResolver, SymbolTable symbolTable, String externalSchemaLocation, String externalNoNSSchemaLocation, XMLGrammarPool grammarPool) { fErrorReporter = errorReporter; fSymbolTable = symbolTable; fGrammarPool = grammarPool; EMPTY_STRING = fSymbolTable.addSymbol(SchemaSymbols.EMPTY_STRING); fLocationResolver.reset(entityResolver, externalSchemaLocation, externalNoNSSchemaLocation); try { fSchemaParser.setProperty(ERROR_HANDLER, fErrorReporter.getErrorHandler()); } catch (Exception e) { } //now this part is done in XMLSchemaValidator //processJAXPSchemaSource(jaxpSchemaSource, entityResolver); } // reset(ErrorReporter, EntityResolver, SymbolTable) /** * Traverse all the deferred local elements. This method should be called * by traverseSchemas after we've done with all the global declarations. */ void traverseLocalElements() { fElementTraverser.fDeferTraversingLocalElements = false; for (int i = 0; i < fLocalElemStackPos; i++) { Element currElem = fLocalElementDecl[i]; XSDocumentInfo currSchema = (XSDocumentInfo)fDoc2XSDocumentMap.get(DOMUtil.getDocument(currElem)); SchemaGrammar currGrammar = fGrammarBucket.getGrammar(currSchema.fTargetNamespace); fElementTraverser.traverseLocal (fParticle[i], currElem, currSchema, currGrammar, fAllContext[i]); } } // the purpose of this method is to keep up-to-date structures // we'll need for the feferred traversal of local elements. void fillInLocalElemInfo(Element elmDecl, XSDocumentInfo schemaDoc, int allContextFlags, XSParticleDecl particle) { // if the stack is full, increase the size if (fParticle.length == fLocalElemStackPos) { // increase size XSParticleDecl[] newStackP = new XSParticleDecl[fLocalElemStackPos+INC_STACK_SIZE]; System.arraycopy(fParticle, 0, newStackP, 0, fLocalElemStackPos); fParticle = newStackP; Element[] newStackE = new Element[fLocalElemStackPos+INC_STACK_SIZE]; System.arraycopy(fLocalElementDecl, 0, newStackE, 0, fLocalElemStackPos); fLocalElementDecl = newStackE; int[] newStackI = new int[fLocalElemStackPos+INC_STACK_SIZE]; System.arraycopy(fAllContext, 0, newStackI, 0, fLocalElemStackPos); fAllContext = newStackI; String [][] newStackN = new String [fLocalElemStackPos+INC_STACK_SIZE][]; System.arraycopy(fLocalElemNamespaceContext, 0, newStackN, 0, fLocalElemStackPos); fLocalElemNamespaceContext = newStackN; } fParticle[fLocalElemStackPos] = particle; fLocalElementDecl[fLocalElemStackPos] = elmDecl; fAllContext[fLocalElemStackPos] = allContextFlags; fLocalElemNamespaceContext[fLocalElemStackPos++] = schemaDoc.fNamespaceSupport.getEffectiveLocalContext(); } // end fillInLocalElemInfo(...) /** This method makes sure that * if this component is being redefined that it lives in the * right schema. It then renames the component correctly. If it * detects a collision--a duplicate definition--then it complains. * Note that redefines must be handled carefully: if there * is a collision, it may be because we're redefining something we know about * or because we've found the thing we're redefining. */ void checkForDuplicateNames(String qName, Hashtable registry, Element currComp, XSDocumentInfo currSchema) { Object objElem = null; // REVISIT: when we add derivation checking, we'll have to make // sure that ID constraint collisions don't necessarily result in error messages. if ((objElem = registry.get(qName)) == null) { // just add it in! registry.put(qName, currComp); } else { Element collidingElem = (Element)objElem; if (collidingElem == currComp) return; Element elemParent = null; XSDocumentInfo redefinedSchema = null; // case where we've collided with a redefining element // (the parent of the colliding element is a redefine) boolean collidedWithRedefine = true; if ((DOMUtil.getLocalName((elemParent = DOMUtil.getParent(collidingElem))).equals(SchemaSymbols.ELT_REDEFINE))) { redefinedSchema = (XSDocumentInfo)(fRedefine2XSDMap.get(elemParent)); // case where we're a redefining element. } else if ((DOMUtil.getLocalName(DOMUtil.getParent(currComp)).equals(SchemaSymbols.ELT_REDEFINE))) { redefinedSchema = (XSDocumentInfo)(fDoc2XSDocumentMap.get(DOMUtil.getDocument(collidingElem))); collidedWithRedefine = false; } if (redefinedSchema != null) { //redefinition involved somehow String newName = qName.substring(qName.lastIndexOf(',')+1)+REDEF_IDENTIFIER; if (redefinedSchema == currSchema) { // object comp. okay here // now have to do some renaming... currComp.setAttribute(SchemaSymbols.ATT_NAME, newName); if (currSchema.fTargetNamespace == null) registry.put(","+newName, currComp); else registry.put(currSchema.fTargetNamespace+","+newName, currComp); // and take care of nested redefines by calling recursively: if (currSchema.fTargetNamespace == null) checkForDuplicateNames(","+newName, registry, currComp, currSchema); else checkForDuplicateNames(currSchema.fTargetNamespace+","+newName, registry, currComp, currSchema); } else { // we may be redefining the wrong schema if (collidedWithRedefine) { if (currSchema.fTargetNamespace == null) checkForDuplicateNames(","+newName, registry, currComp, currSchema); else checkForDuplicateNames(currSchema.fTargetNamespace+","+newName, registry, currComp, currSchema); } else { // error that redefined element in wrong schema reportSchemaError("src-redefine.1", new Object [] {qName}, currComp); } } } else { // we've just got a flat-out collision reportSchemaError("sch-props-correct.2", new Object []{qName}, currComp); } } } // checkForDuplicateNames(String, Hashtable, Element, XSDocumentInfo):void // the purpose of this method is to take the component of the // specified type and rename references to itself so that they // refer to the object being redefined. It takes special care of // <group>s and <attributeGroup>s to ensure that information // relating to implicit restrictions is preserved for those // traversers. private void renameRedefiningComponents(XSDocumentInfo currSchema, Element child, String componentType, String oldName, String newName) { SchemaNamespaceSupport currNSMap = currSchema.fNamespaceSupport; if (componentType.equals(SchemaSymbols.ELT_SIMPLETYPE)) { Element grandKid = DOMUtil.getFirstChildElement(child); if (grandKid == null) { reportSchemaError("src-redefine.5", null, child); } else { String grandKidName = grandKid.getLocalName(); if (grandKidName.equals(SchemaSymbols.ELT_ANNOTATION)) { grandKid = DOMUtil.getNextSiblingElement(grandKid); grandKidName = grandKid.getLocalName(); } if (grandKid == null) { reportSchemaError("src-redefine.5", null, child); } else if (!grandKidName.equals(SchemaSymbols.ELT_RESTRICTION)) { reportSchemaError("src-redefine.5", null, child); } else { Object[] attrs = fAttributeChecker.checkAttributes(grandKid, false, currSchema); QName derivedBase = (QName)attrs[XSAttributeChecker.ATTIDX_BASE]; if (derivedBase == null || derivedBase.uri != currSchema.fTargetNamespace || !derivedBase.localpart.equals(oldName)) { reportSchemaError("src-redefine.5", null, child); } else { // now we have to do the renaming... if (derivedBase.prefix != null && derivedBase.prefix.length() > 0) grandKid.setAttribute( SchemaSymbols.ATT_BASE, derivedBase.prefix + ":" + newName ); else grandKid.setAttribute( SchemaSymbols.ATT_BASE, newName ); // return true; } fAttributeChecker.returnAttrArray(attrs, currSchema); } } } else if (componentType.equals(SchemaSymbols.ELT_COMPLEXTYPE)) { Element grandKid = DOMUtil.getFirstChildElement(child); if (grandKid == null) { reportSchemaError("src-redefine.5", null, child); } else { if (grandKid.getLocalName().equals(SchemaSymbols.ELT_ANNOTATION)) { grandKid = DOMUtil.getNextSiblingElement(grandKid); } if (grandKid == null) { reportSchemaError("src-redefine.5", null, child); } else { // have to go one more level down; let another pass worry whether complexType is valid. Element greatGrandKid = DOMUtil.getFirstChildElement(grandKid); if (greatGrandKid == null) { reportSchemaError("src-redefine.5", null, grandKid); } else { String greatGrandKidName = greatGrandKid.getLocalName(); if (greatGrandKidName.equals(SchemaSymbols.ELT_ANNOTATION)) { greatGrandKid = DOMUtil.getNextSiblingElement(greatGrandKid); greatGrandKidName = greatGrandKid.getLocalName(); } if (greatGrandKid == null) { reportSchemaError("src-redefine.5", null, grandKid); } else if (!greatGrandKidName.equals(SchemaSymbols.ELT_RESTRICTION) && !greatGrandKidName.equals(SchemaSymbols.ELT_EXTENSION)) { reportSchemaError("src-redefine.5", null, greatGrandKid); } else { Object[] attrs = fAttributeChecker.checkAttributes(greatGrandKid, false, currSchema); QName derivedBase = (QName)attrs[XSAttributeChecker.ATTIDX_BASE]; if (derivedBase == null || derivedBase.uri != currSchema.fTargetNamespace || !derivedBase.localpart.equals(oldName)) { reportSchemaError("src-redefine.5", null, greatGrandKid); } else { // now we have to do the renaming... if (derivedBase.prefix != null && derivedBase.prefix.length() > 0) greatGrandKid.setAttribute( SchemaSymbols.ATT_BASE, derivedBase.prefix + ":" + newName ); else greatGrandKid.setAttribute( SchemaSymbols.ATT_BASE, newName ); // return true; } } } } } } else if (componentType.equals(SchemaSymbols.ELT_ATTRIBUTEGROUP)) { String processedBaseName = (currSchema.fTargetNamespace == null)? ","+oldName:currSchema.fTargetNamespace+","+oldName; int attGroupRefsCount = changeRedefineGroup(processedBaseName, componentType, newName, child, currSchema); if (attGroupRefsCount > 1) { reportSchemaError("src-redefine.7.1", new Object []{new Integer(attGroupRefsCount)}, child); } else if (attGroupRefsCount == 1) { // return true; } else if (currSchema.fTargetNamespace == null) fRedefinedRestrictedAttributeGroupRegistry.put(processedBaseName, ","+newName); else fRedefinedRestrictedAttributeGroupRegistry.put(processedBaseName, currSchema.fTargetNamespace+","+newName); } else if (componentType.equals(SchemaSymbols.ELT_GROUP)) { String processedBaseName = (currSchema.fTargetNamespace == null)? ","+oldName:currSchema.fTargetNamespace+","+oldName; int groupRefsCount = changeRedefineGroup(processedBaseName, componentType, newName, child, currSchema); if (groupRefsCount > 1) { reportSchemaError("src-redefine.6.1.1", new Object []{new Integer(groupRefsCount)}, child); } else if (groupRefsCount == 1) { // return true; } else { if (currSchema.fTargetNamespace == null) fRedefinedRestrictedGroupRegistry.put(processedBaseName, ","+newName); else fRedefinedRestrictedGroupRegistry.put(processedBaseName, currSchema.fTargetNamespace+","+newName); } } else { reportSchemaError("Internal-Error", new Object [] {"could not handle this particular <redefine>; please submit your schemas and instance document in a bug report!"}, child); } // if we get here then we must have reported an error and failed somewhere... // return false; } // renameRedefiningComponents(XSDocumentInfo, Element, String, String, String):void // this method takes a name of the form a:b, determines the URI mapped // to by a in the current SchemaNamespaceSupport object, and returns this // information in the form (nsURI,b) suitable for lookups in the global // decl Hashtables. // REVISIT: should have it return QName, instead of String. this would // save lots of string concatenation time. we can use // QName#equals() to compare two QNames, and use QName directly // as a key to the SymbolHash. // And when the DV's are ready to return compiled values from // validate() method, we should just call QNameDV.validate() // in this method. private String findQName(String name, XSDocumentInfo schemaDoc) { SchemaNamespaceSupport currNSMap = schemaDoc.fNamespaceSupport; int colonPtr = name.indexOf(':'); String prefix = EMPTY_STRING; if (colonPtr > 0) prefix = name.substring(0, colonPtr); String uri = currNSMap.getURI(fSymbolTable.addSymbol(prefix)); String localpart = (colonPtr == 0)?name:name.substring(colonPtr+1); if (prefix == this.EMPTY_STRING && uri == null && schemaDoc.fIsChameleonSchema) uri = schemaDoc.fTargetNamespace; if (uri == null) return ","+localpart; return uri+","+localpart; } // findQName(String, XSDocumentInfo): String // This function looks among the children of curr for an element of type elementSought. // If it finds one, it evaluates whether its ref attribute contains a reference // to originalQName. If it does, it returns 1 + the value returned by // calls to itself on all other children. In all other cases it returns 0 plus // the sum of the values returned by calls to itself on curr's children. // It also resets the value of ref so that it will refer to the renamed type from the schema // being redefined. private int changeRedefineGroup(String originalQName, String elementSought, String newName, Element curr, XSDocumentInfo schemaDoc) { SchemaNamespaceSupport currNSMap = schemaDoc.fNamespaceSupport; int result = 0; for (Element child = DOMUtil.getFirstChildElement(curr); child != null; child = DOMUtil.getNextSiblingElement(child)) { String name = child.getLocalName(); if (!name.equals(elementSought)) result += changeRedefineGroup(originalQName, elementSought, newName, child, schemaDoc); else { String ref = child.getAttribute( SchemaSymbols.ATT_REF ); if (ref.length() != 0) { String processedRef = findQName(ref, schemaDoc); if (originalQName.equals(processedRef)) { String prefix = EMPTY_STRING; String localpart = ref; int colonptr = ref.indexOf(":"); if (colonptr > 0) { prefix = ref.substring(0,colonptr); child.setAttribute(SchemaSymbols.ATT_REF, prefix + ":" + newName); } else child.setAttribute(SchemaSymbols.ATT_REF, newName); result++; if (elementSought.equals(SchemaSymbols.ELT_GROUP)) { String minOccurs = child.getAttribute( SchemaSymbols.ATT_MINOCCURS ); String maxOccurs = child.getAttribute( SchemaSymbols.ATT_MAXOCCURS ); if (!((maxOccurs.length() == 0 || maxOccurs.equals("1")) && (minOccurs.length() == 0 || minOccurs.equals("1")))) { reportSchemaError("src-redefine.6.1.2", new Object [] {ref}, child); } } } } // if ref was null some other stage of processing will flag the error } } return result; } // changeRedefineGroup // this method returns the XSDocumentInfo object that contains the // component corresponding to decl. If components from this // document cannot be referred to from those of currSchema, this // method returns null; it's up to the caller to throw an error. // @param: currSchema: the XSDocumentInfo object containing the // decl ref'ing us. // @param: decl: the declaration being ref'd. private XSDocumentInfo findXSDocumentForDecl(XSDocumentInfo currSchema, Element decl) { Document declDoc = DOMUtil.getDocument(decl); Object temp = fDoc2XSDocumentMap.get(declDoc); if (temp == null) { // something went badly wrong; we don't know this doc? return null; } XSDocumentInfo declDocInfo = (XSDocumentInfo)temp; return declDocInfo; /********* Logic here is unnecessary after schema WG's recent decision to allow schema components from one document to refer to components of any other, so long as there's some include/import/redefine path amongst them. If they rver reverse this decision the code's right here though... - neilg // now look in fDependencyMap to see if this is reachable if(((Vector)fDependencyMap.get(currSchema)).contains(declDocInfo)) { return declDocInfo; } // obviously the requesting doc didn't include, redefine or // import the one containing decl... return null; **********/ } // findXSDocumentForDecl(XSDocumentInfo, Element): XSDocumentInfo // returns whether more than <annotation>s occur in children of elem private boolean nonAnnotationContent(Element elem) { for(Element child = DOMUtil.getFirstChildElement(elem); child != null; child = DOMUtil.getNextSiblingElement(child)) { if(!(DOMUtil.getLocalName(child).equals(SchemaSymbols.ELT_ANNOTATION))) return true; } return false; } // nonAnnotationContent(Element): boolean private void setSchemasVisible(XSDocumentInfo startSchema) { if (DOMUtil.isHidden(startSchema.fSchemaDoc)) { // make it visible DOMUtil.setVisible(startSchema.fSchemaDoc); Vector dependingSchemas = (Vector)fDependencyMap.get(startSchema); for (int i = 0; i < dependingSchemas.size(); i++) { setSchemasVisible((XSDocumentInfo)dependingSchemas.elementAt(i)); } } // if it's visible already than so must be its children } // setSchemasVisible(XSDocumentInfo): void private SimpleLocator xl = new SimpleLocator(); /** * Extract location information from an Element node, and create a * new SimpleLocator object from such information. Returning null means * no information can be retrieved from the element. */ public SimpleLocator element2Locator(Element e) { if (!(e instanceof ElementNSImpl)) return null; SimpleLocator l = new SimpleLocator(); return element2Locator(e, l) ? l : null; } /** * Extract location information from an Element node, store such * information in the passed-in SimpleLocator object, then return * true. Returning false means can't extract or store such information. */ public boolean element2Locator(Element e, SimpleLocator l) { if (!(e instanceof ElementNSImpl) || l == null) return false; ElementNSImpl ele = (ElementNSImpl)e; // get system id from document object Document doc = ele.getOwnerDocument(); String sid = (String)fDoc2SystemId.get(doc); // line/column numbers are stored in the element node int line = ele.getLineNumber(); int column = ele.getColumnNumber(); l.setValues(sid, sid, line, column); return true; } void reportSchemaError(String key, Object[] args, Element ele) { if (element2Locator(ele, xl)) { fErrorReporter.reportError(xl, XSMessageFormatter.SCHEMA_DOMAIN, key, args, XMLErrorReporter.SEVERITY_ERROR); } else { fErrorReporter.reportError(XSMessageFormatter.SCHEMA_DOMAIN, key, args, XMLErrorReporter.SEVERITY_ERROR); } } void reportSchemaWarning(String key, Object[] args, Element ele) { if (element2Locator(ele, xl)) { fErrorReporter.reportError(xl, XSMessageFormatter.SCHEMA_DOMAIN, key, args, XMLErrorReporter.SEVERITY_WARNING); } else { fErrorReporter.reportError(XSMessageFormatter.SCHEMA_DOMAIN, key, args, XMLErrorReporter.SEVERITY_WARNING); } } // used to identify a reference to a schema document // if the same document is referenced twice with the same key, then // we only need to parse it once. private static class XSDKey { String systemId; short referType; String referNS; XSDKey(String systemId, short referType, String referNS) { this.systemId = systemId; this.referType = referType; this.referNS = referNS; } public int hashCode() { return systemId.hashCode(); } public boolean equals(Object obj) { if (!(obj instanceof XSDKey)) { return false; } XSDKey key = (XSDKey)obj; // if they have different system id, then read the document if (!systemId.equals(key.systemId)) { return false; } // for include and redefine if (referType == XSDDescription.CONTEXT_INCLUDE || referType == XSDDescription.CONTEXT_REDEFINE || key.referType == XSDDescription.CONTEXT_INCLUDE || key.referType == XSDDescription.CONTEXT_REDEFINE) { // the refer type must be the same, and the referer NS must be // the same if (referType != key.referType || referNS != key.referNS) { return false; } } // for import/instance/preparse, as long as the system id // are the same, we don't need to parse the document again return true; } } } // XSDHandler
true
true
protected XSDocumentInfo constructTrees(Document schemaRoot, String locationHint, XSDDescription desc) { if (schemaRoot == null) return null; String callerTNS = desc.getTargetNamespace(); short referType = desc.getContextType(); XSDocumentInfo currSchemaInfo = null; try { currSchemaInfo = new XSDocumentInfo(schemaRoot, fAttributeChecker, fSymbolTable); } catch (XMLSchemaException se) { reportSchemaError(ELE_ERROR_CODES[referType], new Object[]{locationHint}, DOMUtil.getRoot(schemaRoot)); return null; } // targetNamespace="" is not valid, issue a warning, and ignore it if (currSchemaInfo.fTargetNamespace != null && currSchemaInfo.fTargetNamespace.length() == 0) { reportSchemaWarning("EmptyTargetNamespace", new Object[]{locationHint}, DOMUtil.getRoot(schemaRoot)); currSchemaInfo.fTargetNamespace = null; } if (callerTNS != null) { // the second index to the NS_ERROR_CODES array // if the caller/expected NS is not absent, we use the first column int secondIdx = 0; // for include and redefine if (referType == XSDDescription.CONTEXT_INCLUDE || referType == XSDDescription.CONTEXT_REDEFINE) { // if the referred document has no targetNamespace, // it's a chameleon schema if (currSchemaInfo.fTargetNamespace == null) { currSchemaInfo.fTargetNamespace = callerTNS; currSchemaInfo.fIsChameleonSchema = true; } // if the referred document has a target namespace differing // from the caller, it's an error else if (callerTNS != currSchemaInfo.fTargetNamespace) { reportSchemaError(NS_ERROR_CODES[referType][secondIdx], new Object [] {callerTNS, currSchemaInfo.fTargetNamespace}, DOMUtil.getRoot(schemaRoot)); } } // for preparse, callerTNS is null, so it's not possible // for instance and import, the two NS's must be the same else if (callerTNS != currSchemaInfo.fTargetNamespace) { reportSchemaError(NS_ERROR_CODES[referType][secondIdx], new Object [] {callerTNS, currSchemaInfo.fTargetNamespace}, DOMUtil.getRoot(schemaRoot)); } } // now there is no caller/expected NS, it's an error for the referred // document to have a target namespace, unless we are preparsing a schema else if (currSchemaInfo.fTargetNamespace != null) { // set the target namespace of the description if (referType == XSDDescription.CONTEXT_PREPARSE) { desc.setTargetNamespace(currSchemaInfo.fTargetNamespace); } else { // the second index to the NS_ERROR_CODES array // if the caller/expected NS is absent, we use the second column int secondIdx = 1; reportSchemaError(NS_ERROR_CODES[referType][secondIdx], new Object [] {callerTNS, currSchemaInfo.fTargetNamespace}, DOMUtil.getRoot(schemaRoot)); } } // the other cases (callerTNS == currSchemaInfo.fTargetNamespce == null) // are valid // a schema document can always access it's own target namespace currSchemaInfo.addAllowedNS(currSchemaInfo.fTargetNamespace); SchemaGrammar sg = null; // In the case of preparse, if the grammar is not available in the bucket we ask the pool // If the context is instance, the validator would have already consulted the pool if ((sg = fGrammarBucket.getGrammar(currSchemaInfo.fTargetNamespace)) == null && referType == XSDDescription.CONTEXT_PREPARSE) { if (fGrammarPool != null) { sg = (SchemaGrammar)fGrammarPool.retrieveGrammar(desc); if (sg != null) { fGrammarBucket.putGrammar(sg); } } } if (sg == null) { sg = new SchemaGrammar(fSymbolTable, currSchemaInfo.fTargetNamespace, desc.makeClone()); fGrammarBucket.putGrammar(sg); } // we got a grammar of the same namespace in the bucket, should ignore this one else if (referType == XSDDescription.CONTEXT_PREPARSE) { return null; } fDoc2XSDocumentMap.put(schemaRoot, currSchemaInfo); Vector dependencies = new Vector(); Element rootNode = DOMUtil.getRoot(schemaRoot); Document newSchemaRoot = null; for (Element child = DOMUtil.getFirstChildElement(rootNode); child != null; child = DOMUtil.getNextSiblingElement(child)) { String schemaNamespace=null; String schemaHint=null; String localName = DOMUtil.getLocalName(child); short refType = -1; if (localName.equals(SchemaSymbols.ELT_ANNOTATION)) continue; else if (localName.equals(SchemaSymbols.ELT_IMPORT)) { refType = XSDDescription.CONTEXT_IMPORT; // have to handle some validation here too! // call XSAttributeChecker to fill in attrs Object[] includeAttrs = fAttributeChecker.checkAttributes(child, true, currSchemaInfo); schemaHint = (String)includeAttrs[XSAttributeChecker.ATTIDX_SCHEMALOCATION]; schemaNamespace = (String)includeAttrs[XSAttributeChecker.ATTIDX_NAMESPACE]; if (schemaNamespace != null) schemaNamespace = fSymbolTable.addSymbol(schemaNamespace); if (schemaNamespace == currSchemaInfo.fTargetNamespace) { reportSchemaError("src-import.1.1", new Object [] {schemaNamespace}, child); } fAttributeChecker.returnAttrArray(includeAttrs, currSchemaInfo); // a schema document can access it's imported namespaces currSchemaInfo.addAllowedNS(schemaNamespace); fSchemaGrammarDescription.reset(); fSchemaGrammarDescription.setContextType(XSDDescription.CONTEXT_IMPORT); fSchemaGrammarDescription.setBaseSystemId((String)fDoc2SystemId.get(schemaRoot)); fSchemaGrammarDescription.setLocationHints(new String[]{schemaHint}); fSchemaGrammarDescription.setTargetNamespace(schemaNamespace); newSchemaRoot = getSchema(fSchemaGrammarDescription, false, child); } else if ((localName.equals(SchemaSymbols.ELT_INCLUDE)) || (localName.equals(SchemaSymbols.ELT_REDEFINE))) { // validation for redefine/include will be the same here; just // make sure TNS is right (don't care about redef contents // yet). Object[] includeAttrs = fAttributeChecker.checkAttributes(child, true, currSchemaInfo); schemaHint = (String)includeAttrs[XSAttributeChecker.ATTIDX_SCHEMALOCATION]; fAttributeChecker.returnAttrArray(includeAttrs, currSchemaInfo); // schemaLocation is required on <include> and <redefine> if (schemaHint == null) reportSchemaError("s4s-att-must-appear", new Object [] { "<include> or <redefine>", "schemaLocation"}, child); // pass the systemId of the current document as the base systemId boolean mustResolve = false; refType = XSDDescription.CONTEXT_INCLUDE; if(localName.equals(SchemaSymbols.ELT_REDEFINE)) { mustResolve = nonAnnotationContent(child); refType = XSDDescription.CONTEXT_REDEFINE; } fSchemaGrammarDescription.reset(); fSchemaGrammarDescription.setContextType(refType); fSchemaGrammarDescription.setBaseSystemId((String)fDoc2SystemId.get(schemaRoot)); fSchemaGrammarDescription.setLocationHints(new String[]{schemaHint}); fSchemaGrammarDescription.setTargetNamespace(callerTNS); newSchemaRoot = getSchema(fSchemaGrammarDescription, mustResolve, child); schemaNamespace = currSchemaInfo.fTargetNamespace; } else { // no more possibility of schema references in well-formed // schema... break; } // If the schema is duplicate, we needn't call constructTrees() again. // To handle mutual <include>s XSDocumentInfo newSchemaInfo = null; if (fLastSchemaWasDuplicate) { newSchemaInfo = (XSDocumentInfo)fDoc2XSDocumentMap.get(newSchemaRoot); } else { newSchemaInfo = constructTrees(newSchemaRoot, schemaHint, fSchemaGrammarDescription); } if (localName.equals(SchemaSymbols.ELT_REDEFINE) && newSchemaInfo != null) { // must record which schema we're redefining so that we can // rename the right things later! fRedefine2XSDMap.put(child, newSchemaInfo); } if (newSchemaRoot != null) { if (newSchemaInfo != null) dependencies.addElement(newSchemaInfo); newSchemaRoot = null; } } fDependencyMap.put(currSchemaInfo, dependencies); return currSchemaInfo; } // end constructTrees
protected XSDocumentInfo constructTrees(Document schemaRoot, String locationHint, XSDDescription desc) { if (schemaRoot == null) return null; String callerTNS = desc.getTargetNamespace(); short referType = desc.getContextType(); XSDocumentInfo currSchemaInfo = null; try { currSchemaInfo = new XSDocumentInfo(schemaRoot, fAttributeChecker, fSymbolTable); } catch (XMLSchemaException se) { reportSchemaError(ELE_ERROR_CODES[referType], new Object[]{locationHint}, DOMUtil.getRoot(schemaRoot)); return null; } // targetNamespace="" is not valid, issue a warning, and ignore it if (currSchemaInfo.fTargetNamespace != null && currSchemaInfo.fTargetNamespace.length() == 0) { reportSchemaWarning("EmptyTargetNamespace", new Object[]{locationHint}, DOMUtil.getRoot(schemaRoot)); currSchemaInfo.fTargetNamespace = null; } if (callerTNS != null) { // the second index to the NS_ERROR_CODES array // if the caller/expected NS is not absent, we use the first column int secondIdx = 0; // for include and redefine if (referType == XSDDescription.CONTEXT_INCLUDE || referType == XSDDescription.CONTEXT_REDEFINE) { // if the referred document has no targetNamespace, // it's a chameleon schema if (currSchemaInfo.fTargetNamespace == null) { currSchemaInfo.fTargetNamespace = callerTNS; currSchemaInfo.fIsChameleonSchema = true; } // if the referred document has a target namespace differing // from the caller, it's an error else if (callerTNS != currSchemaInfo.fTargetNamespace) { reportSchemaError(NS_ERROR_CODES[referType][secondIdx], new Object [] {callerTNS, currSchemaInfo.fTargetNamespace}, DOMUtil.getRoot(schemaRoot)); } } // for preparse, callerTNS is null, so it's not possible // for instance and import, the two NS's must be the same else if (callerTNS != currSchemaInfo.fTargetNamespace) { reportSchemaError(NS_ERROR_CODES[referType][secondIdx], new Object [] {callerTNS, currSchemaInfo.fTargetNamespace}, DOMUtil.getRoot(schemaRoot)); } } // now there is no caller/expected NS, it's an error for the referred // document to have a target namespace, unless we are preparsing a schema else if (currSchemaInfo.fTargetNamespace != null) { // set the target namespace of the description if (referType == XSDDescription.CONTEXT_PREPARSE) { desc.setTargetNamespace(currSchemaInfo.fTargetNamespace); callerTNS = currSchemaInfo.fTargetNamespace; } else { // the second index to the NS_ERROR_CODES array // if the caller/expected NS is absent, we use the second column int secondIdx = 1; reportSchemaError(NS_ERROR_CODES[referType][secondIdx], new Object [] {callerTNS, currSchemaInfo.fTargetNamespace}, DOMUtil.getRoot(schemaRoot)); } } // the other cases (callerTNS == currSchemaInfo.fTargetNamespce == null) // are valid // a schema document can always access it's own target namespace currSchemaInfo.addAllowedNS(currSchemaInfo.fTargetNamespace); SchemaGrammar sg = null; // In the case of preparse, if the grammar is not available in the bucket we ask the pool // If the context is instance, the validator would have already consulted the pool if ((sg = fGrammarBucket.getGrammar(currSchemaInfo.fTargetNamespace)) == null && referType == XSDDescription.CONTEXT_PREPARSE) { if (fGrammarPool != null) { sg = (SchemaGrammar)fGrammarPool.retrieveGrammar(desc); if (sg != null) { fGrammarBucket.putGrammar(sg); } } } if (sg == null) { sg = new SchemaGrammar(fSymbolTable, currSchemaInfo.fTargetNamespace, desc.makeClone()); fGrammarBucket.putGrammar(sg); } // we got a grammar of the same namespace in the bucket, should ignore this one else if (referType == XSDDescription.CONTEXT_PREPARSE) { return null; } fDoc2XSDocumentMap.put(schemaRoot, currSchemaInfo); Vector dependencies = new Vector(); Element rootNode = DOMUtil.getRoot(schemaRoot); Document newSchemaRoot = null; for (Element child = DOMUtil.getFirstChildElement(rootNode); child != null; child = DOMUtil.getNextSiblingElement(child)) { String schemaNamespace=null; String schemaHint=null; String localName = DOMUtil.getLocalName(child); short refType = -1; if (localName.equals(SchemaSymbols.ELT_ANNOTATION)) continue; else if (localName.equals(SchemaSymbols.ELT_IMPORT)) { refType = XSDDescription.CONTEXT_IMPORT; // have to handle some validation here too! // call XSAttributeChecker to fill in attrs Object[] includeAttrs = fAttributeChecker.checkAttributes(child, true, currSchemaInfo); schemaHint = (String)includeAttrs[XSAttributeChecker.ATTIDX_SCHEMALOCATION]; schemaNamespace = (String)includeAttrs[XSAttributeChecker.ATTIDX_NAMESPACE]; if (schemaNamespace != null) schemaNamespace = fSymbolTable.addSymbol(schemaNamespace); if (schemaNamespace == currSchemaInfo.fTargetNamespace) { reportSchemaError("src-import.1.1", new Object [] {schemaNamespace}, child); } fAttributeChecker.returnAttrArray(includeAttrs, currSchemaInfo); // a schema document can access it's imported namespaces currSchemaInfo.addAllowedNS(schemaNamespace); fSchemaGrammarDescription.reset(); fSchemaGrammarDescription.setContextType(XSDDescription.CONTEXT_IMPORT); fSchemaGrammarDescription.setBaseSystemId((String)fDoc2SystemId.get(schemaRoot)); fSchemaGrammarDescription.setLocationHints(new String[]{schemaHint}); fSchemaGrammarDescription.setTargetNamespace(schemaNamespace); newSchemaRoot = getSchema(fSchemaGrammarDescription, false, child); } else if ((localName.equals(SchemaSymbols.ELT_INCLUDE)) || (localName.equals(SchemaSymbols.ELT_REDEFINE))) { // validation for redefine/include will be the same here; just // make sure TNS is right (don't care about redef contents // yet). Object[] includeAttrs = fAttributeChecker.checkAttributes(child, true, currSchemaInfo); schemaHint = (String)includeAttrs[XSAttributeChecker.ATTIDX_SCHEMALOCATION]; fAttributeChecker.returnAttrArray(includeAttrs, currSchemaInfo); // schemaLocation is required on <include> and <redefine> if (schemaHint == null) reportSchemaError("s4s-att-must-appear", new Object [] { "<include> or <redefine>", "schemaLocation"}, child); // pass the systemId of the current document as the base systemId boolean mustResolve = false; refType = XSDDescription.CONTEXT_INCLUDE; if(localName.equals(SchemaSymbols.ELT_REDEFINE)) { mustResolve = nonAnnotationContent(child); refType = XSDDescription.CONTEXT_REDEFINE; } fSchemaGrammarDescription.reset(); fSchemaGrammarDescription.setContextType(refType); fSchemaGrammarDescription.setBaseSystemId((String)fDoc2SystemId.get(schemaRoot)); fSchemaGrammarDescription.setLocationHints(new String[]{schemaHint}); fSchemaGrammarDescription.setTargetNamespace(callerTNS); newSchemaRoot = getSchema(fSchemaGrammarDescription, mustResolve, child); schemaNamespace = currSchemaInfo.fTargetNamespace; } else { // no more possibility of schema references in well-formed // schema... break; } // If the schema is duplicate, we needn't call constructTrees() again. // To handle mutual <include>s XSDocumentInfo newSchemaInfo = null; if (fLastSchemaWasDuplicate) { newSchemaInfo = (XSDocumentInfo)fDoc2XSDocumentMap.get(newSchemaRoot); } else { newSchemaInfo = constructTrees(newSchemaRoot, schemaHint, fSchemaGrammarDescription); } if (localName.equals(SchemaSymbols.ELT_REDEFINE) && newSchemaInfo != null) { // must record which schema we're redefining so that we can // rename the right things later! fRedefine2XSDMap.put(child, newSchemaInfo); } if (newSchemaRoot != null) { if (newSchemaInfo != null) dependencies.addElement(newSchemaInfo); newSchemaRoot = null; } } fDependencyMap.put(currSchemaInfo, dependencies); return currSchemaInfo; } // end constructTrees
diff --git a/src/test/org/jdesktop/test/TableModelReport.java b/src/test/org/jdesktop/test/TableModelReport.java index e6ae72e0..0f4d6c09 100644 --- a/src/test/org/jdesktop/test/TableModelReport.java +++ b/src/test/org/jdesktop/test/TableModelReport.java @@ -1,170 +1,170 @@ /* * $Id$ * * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.test; import java.util.LinkedList; import java.util.List; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; /** * TODO add type doc * * @author Jeanette Winzenburg */ public class TableModelReport implements TableModelListener { List<TableModelEvent> allEvents = new LinkedList<TableModelEvent>(); List<TableModelEvent> updateEvents = new LinkedList<TableModelEvent>(); List<TableModelEvent> insertEvents = new LinkedList<TableModelEvent>(); List<TableModelEvent> deleteEvents = new LinkedList<TableModelEvent>(); //------------------- TableModelListener public void tableChanged(TableModelEvent e) { allEvents.add(0, e); if (isUpdate(e)) { updateEvents.add(0, e); } else if (isStructureChanged(e)) { // this is effectively a test for null event // do nothing for now } else if (isDataChanged(e)) { // do nothing for now } else if (TableModelEvent.DELETE == e.getType()) { - deleteEvents.add(e); + deleteEvents.add(0, e); } else if (TableModelEvent.INSERT == e.getType()) { - insertEvents.add(e); + insertEvents.add(0, e); } } //-------------------- all events access public void clear() { updateEvents.clear(); deleteEvents.clear(); insertEvents.clear(); allEvents.clear(); } public boolean hasEvents() { return !allEvents.isEmpty(); } /** * @return */ public int getEventCount() { return allEvents.size(); } public TableModelEvent getLastEvent() { return allEvents.isEmpty() ? null : allEvents.get(0); } //---------------- update events public boolean hasUpdateEvents() { return !updateEvents.isEmpty(); } /** * @return */ public int getUpdateEventCount() { return updateEvents.size(); } public TableModelEvent getLastUpdateEvent() { return updateEvents.isEmpty() ? null : updateEvents.get(0); } // ---------------- insert events public boolean hasInsertEvents() { return !insertEvents.isEmpty(); } /** * @return */ public int getInsertEventCount() { return insertEvents.size(); } public TableModelEvent getLastInsertEvent() { return insertEvents.isEmpty() ? null : insertEvents.get(0); } // ---------------- delete events public boolean hasDeleteEvents() { return !deleteEvents.isEmpty(); } /** * @return */ public int getDeleteEventCount() { return deleteEvents.size(); } public TableModelEvent getLastDeleteEvent() { return deleteEvents.isEmpty() ? null : deleteEvents.get(0); } //---------------- utility /** * Convenience method to detect dataChanged table event type. * * @param e the event to examine. * @return true if the event is of type dataChanged, false else. */ protected boolean isDataChanged(TableModelEvent e) { if (e == null) return false; return e.getType() == TableModelEvent.UPDATE && e.getFirstRow() == 0 && e.getLastRow() == Integer.MAX_VALUE; } /** * Convenience method to detect update table event type. * * @param e the event to examine. * @return true if the event is of type update and not dataChanged, false else. */ protected boolean isUpdate(TableModelEvent e) { if (isStructureChanged(e)) return false; return e.getType() == TableModelEvent.UPDATE && e.getLastRow() < Integer.MAX_VALUE; } /** * Convenience method to detect a structureChanged table event type. * @param e the event to examine. * @return true if the event is of type structureChanged or null, false else. */ protected boolean isStructureChanged(TableModelEvent e) { return e == null || e.getFirstRow() == TableModelEvent.HEADER_ROW; } }
false
true
public void tableChanged(TableModelEvent e) { allEvents.add(0, e); if (isUpdate(e)) { updateEvents.add(0, e); } else if (isStructureChanged(e)) { // this is effectively a test for null event // do nothing for now } else if (isDataChanged(e)) { // do nothing for now } else if (TableModelEvent.DELETE == e.getType()) { deleteEvents.add(e); } else if (TableModelEvent.INSERT == e.getType()) { insertEvents.add(e); } }
public void tableChanged(TableModelEvent e) { allEvents.add(0, e); if (isUpdate(e)) { updateEvents.add(0, e); } else if (isStructureChanged(e)) { // this is effectively a test for null event // do nothing for now } else if (isDataChanged(e)) { // do nothing for now } else if (TableModelEvent.DELETE == e.getType()) { deleteEvents.add(0, e); } else if (TableModelEvent.INSERT == e.getType()) { insertEvents.add(0, e); } }
diff --git a/src/semanticMarkup/LearnMain.java b/src/semanticMarkup/LearnMain.java index 170df238..d87e8c03 100644 --- a/src/semanticMarkup/LearnMain.java +++ b/src/semanticMarkup/LearnMain.java @@ -1,208 +1,208 @@ package semanticMarkup; import java.io.File; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import semanticMarkup.config.RunConfig; import semanticMarkup.know.lib.InMemoryGlossary; import semanticMarkup.log.LogLevel; import semanticMarkup.markupElement.description.io.lib.MOXyBinderDescriptionReader; import semanticMarkup.markupElement.description.io.lib.MOXyBinderDescriptionWriter; import semanticMarkup.markupElement.description.ling.learn.lib.DatabaseInputNoLearner; import semanticMarkup.markupElement.description.ling.learn.lib.PerlTerminologyLearner; import semanticMarkup.markupElement.description.run.iplant.IPlantLearnRun; import semanticMarkup.markupElement.description.transform.MarkupDescriptionTreatmentTransformer; /** * Learn CLI Entry point into the processing of the charaparser framework * @author thomas rodenhausen */ public class LearnMain extends CLIMain { /** * @param args */ public static void main(String[] args) { CLIMain cliMain = new LearnMain(); cliMain.parse(args); cliMain.run(); } @Override public void parse(String[] args) { CommandLineParser parser = new BasicParser(); Options options = new Options(); //for iplant user shown configuration options options.addOption("i", "input", true, "input file or directory"); options.addOption("c", "config", true, "config to use"); options.addOption("z", "database-table-prefix", true, "database table prefix to use"); options.addOption("w", "style mapping", true, "Optional style mapping to use for Word file input"); options.addOption("y", "categorize terms", false, "If specified, indicates that one does not intend to categorize newly discovered terms to improve markup"); //for iplant user hidden inputs, but still required or 'nice to have' configuration possibilities' options.addOption("f", "source", true, "source of the descriptions, e.g. fna v7"); options.addOption("g", "user", true, "etc user submitting learned terms to oto lite"); options.addOption("j", "bioportal user id", true, "bioportal user id to use for bioportal submission"); options.addOption("k", "bioportal api key", true, "bioportal api key to use for bioportal submission"); options.addOption("b", "debug log", true, "location of debug log file"); options.addOption("e", "error log", true, "location of error log file"); options.addOption("r", "resources directory", true, "location of resources directory"); options.addOption("l", "src directory", true, "location of src directory"); options.addOption("a", "workspace directory", true, "location of workspace directory"); options.addOption("n", "database-host", true, "dbms host"); options.addOption("p", "database-port", true, "dbms port"); options.addOption("d", "database-name", true, "name of database to use"); options.addOption("u", "database-user", true, "database user to use"); options.addOption("s", "database-password", true, "database password to use"); Option threadingOption = new Option("t", "multi-threading", true, "use multi-threading to compute the result"); //threadingOption.setValueSeparator(','); options.addOption(threadingOption); options.addOption("h", "help", false, "shows the help"); config = new RunConfig(); try { CommandLine commandLine = parser.parse( options, args ); if(commandLine.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( "what is this?", options ); System.exit(0); } if(commandLine.hasOption("c")) { config = getConfig(commandLine.getOptionValue("c")); } else { log(LogLevel.ERROR, "You have to specify a configuration to use"); System.exit(0); //use standard config RunConfig } if (commandLine.hasOption("a")) { - config.setWorkspaceDirectory(commandLine.getOptionValue("t")); + config.setWorkspaceDirectory(commandLine.getOptionValue("a")); } String workspace = config.getWorkspaceDirectory(); if(commandLine.hasOption("b") && commandLine.hasOption("e")) { this.setupLogging(commandLine.getOptionValue("b"), commandLine.getOptionValue("e")); } else { setupLogging(workspace + File.separator +"debug.log", workspace + File.separator + "error.log"); } if(commandLine.hasOption("f")) { config.setSourceOfDescriptions(commandLine.getOptionValue("f")); } if(commandLine.hasOption("g")) { config.setEtcUser(commandLine.getOptionValue("g")); } if(commandLine.hasOption("j")) { config.setBioportalUserId(commandLine.getOptionValue("j")); } if(commandLine.hasOption("k")) { config.setBioportalAPIKey(commandLine.getOptionValue("k")); } if(!commandLine.hasOption("y")) { config.setTermCategorizationRequired(true); } config.setDescriptionReader(MOXyBinderDescriptionReader.class); if(!commandLine.hasOption("i")) { log(LogLevel.ERROR, "You have to specify an input file or directory"); System.exit(0); } else { config.setDescriptionReaderInputDirectory(commandLine.getOptionValue("i")); //config.setGenericFileVolumeReaderSource(commandLine.getOptionValue("i")); } if(commandLine.hasOption("w")) { //config.setWordVolumeReaderStyleMappingFile(commandLine.getOptionValue("w")); } if(commandLine.hasOption("t")) { config.setMarkupDescriptionTreatmentTransformerParallelProcessing(true); String parallelParameter = commandLine.getOptionValue("t"); String[] parallelParameters = parallelParameter.split(","); if(parallelParameters.length != 2) { log(LogLevel.ERROR, "You have to specify 2 values for parameter t"); System.exit(0); } else { try { int threadsPerDescriptionExtractor = Integer.parseInt(parallelParameters[0]); int threadsPerSentenceChunking = Integer.parseInt(parallelParameters[1]); config.setMarkupDescriptionTreatmentTransformerSentenceChunkerRunMaximum(threadsPerSentenceChunking); config.setMarkupDescriptionTreatmentTransformerDescriptionExtractorRunMaximum(threadsPerDescriptionExtractor); } catch(Exception e) { log(LogLevel.ERROR, "Problem to convert parameter to Integer", e); System.exit(0); } } } if(commandLine.hasOption("n")) { config.setDatabaseHost(commandLine.getOptionValue("n")); } else { log(LogLevel.ERROR, "You have to specify a MySQL server hostname"); System.exit(0); //use standard value from RunConfig } if(commandLine.hasOption("p")) { config.setDatabasePort(commandLine.getOptionValue("p")); } else { log(LogLevel.ERROR, "You have to specify a MySQL server port"); System.exit(0); //use standard value from RunConfig } if(commandLine.hasOption("d")) { config.setDatabaseName(commandLine.getOptionValue("d")); } else { log(LogLevel.ERROR, "You have to specify a database name"); System.exit(0); //use standard value from RunConfig } if(commandLine.hasOption("u")) { config.setDatabaseUser(commandLine.getOptionValue("u")); } else { log(LogLevel.ERROR, "You have to specify a database user"); System.exit(0); //use standard value from RunConfig } if(commandLine.hasOption("s")) { config.setDatabasePassword(commandLine.getOptionValue("s")); } else { log(LogLevel.ERROR, "You have to specify a database password"); System.exit(0); //use standard value from RunConfig } //TODO databaseTablePrefix has to be given as user as a ID he remembered from LearnMain //since we have no user information to be able to generate an ID that allows to know //at least whos data to pull if(commandLine.hasOption("z")) { config.setDatabaseTablePrefix(commandLine.getOptionValue("z")); config.setDatabaseGlossaryTable(commandLine.getOptionValue("z") + "_permanentGlossary"); } else { log(LogLevel.ERROR, "You have to specify a database table prefix"); System.exit(0); } if (commandLine.hasOption("r")) { config.setResourcesDirectory(commandLine.getOptionValue("r")); } if (commandLine.hasOption("l")) { config.setSrcDirectory(commandLine.getOptionValue("l")); } } catch (ParseException e) { log(LogLevel.ERROR, "Problem parsing parameters", e); } config.setMarkupDescriptionTreatmentTransformer(MarkupDescriptionTreatmentTransformer.class); config.setRun(IPlantLearnRun.class); config.setGlossary(InMemoryGlossary.class); config.setTerminologyLearner(PerlTerminologyLearner.class); config.setDescriptionWriter(MOXyBinderDescriptionWriter.class); config.setOtoLiteReviewFile("nextStep.html"); } }
true
true
public void parse(String[] args) { CommandLineParser parser = new BasicParser(); Options options = new Options(); //for iplant user shown configuration options options.addOption("i", "input", true, "input file or directory"); options.addOption("c", "config", true, "config to use"); options.addOption("z", "database-table-prefix", true, "database table prefix to use"); options.addOption("w", "style mapping", true, "Optional style mapping to use for Word file input"); options.addOption("y", "categorize terms", false, "If specified, indicates that one does not intend to categorize newly discovered terms to improve markup"); //for iplant user hidden inputs, but still required or 'nice to have' configuration possibilities' options.addOption("f", "source", true, "source of the descriptions, e.g. fna v7"); options.addOption("g", "user", true, "etc user submitting learned terms to oto lite"); options.addOption("j", "bioportal user id", true, "bioportal user id to use for bioportal submission"); options.addOption("k", "bioportal api key", true, "bioportal api key to use for bioportal submission"); options.addOption("b", "debug log", true, "location of debug log file"); options.addOption("e", "error log", true, "location of error log file"); options.addOption("r", "resources directory", true, "location of resources directory"); options.addOption("l", "src directory", true, "location of src directory"); options.addOption("a", "workspace directory", true, "location of workspace directory"); options.addOption("n", "database-host", true, "dbms host"); options.addOption("p", "database-port", true, "dbms port"); options.addOption("d", "database-name", true, "name of database to use"); options.addOption("u", "database-user", true, "database user to use"); options.addOption("s", "database-password", true, "database password to use"); Option threadingOption = new Option("t", "multi-threading", true, "use multi-threading to compute the result"); //threadingOption.setValueSeparator(','); options.addOption(threadingOption); options.addOption("h", "help", false, "shows the help"); config = new RunConfig(); try { CommandLine commandLine = parser.parse( options, args ); if(commandLine.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( "what is this?", options ); System.exit(0); } if(commandLine.hasOption("c")) { config = getConfig(commandLine.getOptionValue("c")); } else { log(LogLevel.ERROR, "You have to specify a configuration to use"); System.exit(0); //use standard config RunConfig } if (commandLine.hasOption("a")) { config.setWorkspaceDirectory(commandLine.getOptionValue("t")); } String workspace = config.getWorkspaceDirectory(); if(commandLine.hasOption("b") && commandLine.hasOption("e")) { this.setupLogging(commandLine.getOptionValue("b"), commandLine.getOptionValue("e")); } else { setupLogging(workspace + File.separator +"debug.log", workspace + File.separator + "error.log"); } if(commandLine.hasOption("f")) { config.setSourceOfDescriptions(commandLine.getOptionValue("f")); } if(commandLine.hasOption("g")) { config.setEtcUser(commandLine.getOptionValue("g")); } if(commandLine.hasOption("j")) { config.setBioportalUserId(commandLine.getOptionValue("j")); } if(commandLine.hasOption("k")) { config.setBioportalAPIKey(commandLine.getOptionValue("k")); } if(!commandLine.hasOption("y")) { config.setTermCategorizationRequired(true); } config.setDescriptionReader(MOXyBinderDescriptionReader.class); if(!commandLine.hasOption("i")) { log(LogLevel.ERROR, "You have to specify an input file or directory"); System.exit(0); } else { config.setDescriptionReaderInputDirectory(commandLine.getOptionValue("i")); //config.setGenericFileVolumeReaderSource(commandLine.getOptionValue("i")); } if(commandLine.hasOption("w")) { //config.setWordVolumeReaderStyleMappingFile(commandLine.getOptionValue("w")); } if(commandLine.hasOption("t")) { config.setMarkupDescriptionTreatmentTransformerParallelProcessing(true); String parallelParameter = commandLine.getOptionValue("t"); String[] parallelParameters = parallelParameter.split(","); if(parallelParameters.length != 2) { log(LogLevel.ERROR, "You have to specify 2 values for parameter t"); System.exit(0); } else { try { int threadsPerDescriptionExtractor = Integer.parseInt(parallelParameters[0]); int threadsPerSentenceChunking = Integer.parseInt(parallelParameters[1]); config.setMarkupDescriptionTreatmentTransformerSentenceChunkerRunMaximum(threadsPerSentenceChunking); config.setMarkupDescriptionTreatmentTransformerDescriptionExtractorRunMaximum(threadsPerDescriptionExtractor); } catch(Exception e) { log(LogLevel.ERROR, "Problem to convert parameter to Integer", e); System.exit(0); } } } if(commandLine.hasOption("n")) { config.setDatabaseHost(commandLine.getOptionValue("n")); } else { log(LogLevel.ERROR, "You have to specify a MySQL server hostname"); System.exit(0); //use standard value from RunConfig } if(commandLine.hasOption("p")) { config.setDatabasePort(commandLine.getOptionValue("p")); } else { log(LogLevel.ERROR, "You have to specify a MySQL server port"); System.exit(0); //use standard value from RunConfig } if(commandLine.hasOption("d")) { config.setDatabaseName(commandLine.getOptionValue("d")); } else { log(LogLevel.ERROR, "You have to specify a database name"); System.exit(0); //use standard value from RunConfig } if(commandLine.hasOption("u")) { config.setDatabaseUser(commandLine.getOptionValue("u")); } else { log(LogLevel.ERROR, "You have to specify a database user"); System.exit(0); //use standard value from RunConfig } if(commandLine.hasOption("s")) { config.setDatabasePassword(commandLine.getOptionValue("s")); } else { log(LogLevel.ERROR, "You have to specify a database password"); System.exit(0); //use standard value from RunConfig } //TODO databaseTablePrefix has to be given as user as a ID he remembered from LearnMain //since we have no user information to be able to generate an ID that allows to know //at least whos data to pull if(commandLine.hasOption("z")) { config.setDatabaseTablePrefix(commandLine.getOptionValue("z")); config.setDatabaseGlossaryTable(commandLine.getOptionValue("z") + "_permanentGlossary"); } else { log(LogLevel.ERROR, "You have to specify a database table prefix"); System.exit(0); } if (commandLine.hasOption("r")) { config.setResourcesDirectory(commandLine.getOptionValue("r")); } if (commandLine.hasOption("l")) { config.setSrcDirectory(commandLine.getOptionValue("l")); } } catch (ParseException e) { log(LogLevel.ERROR, "Problem parsing parameters", e); } config.setMarkupDescriptionTreatmentTransformer(MarkupDescriptionTreatmentTransformer.class); config.setRun(IPlantLearnRun.class); config.setGlossary(InMemoryGlossary.class); config.setTerminologyLearner(PerlTerminologyLearner.class); config.setDescriptionWriter(MOXyBinderDescriptionWriter.class); config.setOtoLiteReviewFile("nextStep.html"); }
public void parse(String[] args) { CommandLineParser parser = new BasicParser(); Options options = new Options(); //for iplant user shown configuration options options.addOption("i", "input", true, "input file or directory"); options.addOption("c", "config", true, "config to use"); options.addOption("z", "database-table-prefix", true, "database table prefix to use"); options.addOption("w", "style mapping", true, "Optional style mapping to use for Word file input"); options.addOption("y", "categorize terms", false, "If specified, indicates that one does not intend to categorize newly discovered terms to improve markup"); //for iplant user hidden inputs, but still required or 'nice to have' configuration possibilities' options.addOption("f", "source", true, "source of the descriptions, e.g. fna v7"); options.addOption("g", "user", true, "etc user submitting learned terms to oto lite"); options.addOption("j", "bioportal user id", true, "bioportal user id to use for bioportal submission"); options.addOption("k", "bioportal api key", true, "bioportal api key to use for bioportal submission"); options.addOption("b", "debug log", true, "location of debug log file"); options.addOption("e", "error log", true, "location of error log file"); options.addOption("r", "resources directory", true, "location of resources directory"); options.addOption("l", "src directory", true, "location of src directory"); options.addOption("a", "workspace directory", true, "location of workspace directory"); options.addOption("n", "database-host", true, "dbms host"); options.addOption("p", "database-port", true, "dbms port"); options.addOption("d", "database-name", true, "name of database to use"); options.addOption("u", "database-user", true, "database user to use"); options.addOption("s", "database-password", true, "database password to use"); Option threadingOption = new Option("t", "multi-threading", true, "use multi-threading to compute the result"); //threadingOption.setValueSeparator(','); options.addOption(threadingOption); options.addOption("h", "help", false, "shows the help"); config = new RunConfig(); try { CommandLine commandLine = parser.parse( options, args ); if(commandLine.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( "what is this?", options ); System.exit(0); } if(commandLine.hasOption("c")) { config = getConfig(commandLine.getOptionValue("c")); } else { log(LogLevel.ERROR, "You have to specify a configuration to use"); System.exit(0); //use standard config RunConfig } if (commandLine.hasOption("a")) { config.setWorkspaceDirectory(commandLine.getOptionValue("a")); } String workspace = config.getWorkspaceDirectory(); if(commandLine.hasOption("b") && commandLine.hasOption("e")) { this.setupLogging(commandLine.getOptionValue("b"), commandLine.getOptionValue("e")); } else { setupLogging(workspace + File.separator +"debug.log", workspace + File.separator + "error.log"); } if(commandLine.hasOption("f")) { config.setSourceOfDescriptions(commandLine.getOptionValue("f")); } if(commandLine.hasOption("g")) { config.setEtcUser(commandLine.getOptionValue("g")); } if(commandLine.hasOption("j")) { config.setBioportalUserId(commandLine.getOptionValue("j")); } if(commandLine.hasOption("k")) { config.setBioportalAPIKey(commandLine.getOptionValue("k")); } if(!commandLine.hasOption("y")) { config.setTermCategorizationRequired(true); } config.setDescriptionReader(MOXyBinderDescriptionReader.class); if(!commandLine.hasOption("i")) { log(LogLevel.ERROR, "You have to specify an input file or directory"); System.exit(0); } else { config.setDescriptionReaderInputDirectory(commandLine.getOptionValue("i")); //config.setGenericFileVolumeReaderSource(commandLine.getOptionValue("i")); } if(commandLine.hasOption("w")) { //config.setWordVolumeReaderStyleMappingFile(commandLine.getOptionValue("w")); } if(commandLine.hasOption("t")) { config.setMarkupDescriptionTreatmentTransformerParallelProcessing(true); String parallelParameter = commandLine.getOptionValue("t"); String[] parallelParameters = parallelParameter.split(","); if(parallelParameters.length != 2) { log(LogLevel.ERROR, "You have to specify 2 values for parameter t"); System.exit(0); } else { try { int threadsPerDescriptionExtractor = Integer.parseInt(parallelParameters[0]); int threadsPerSentenceChunking = Integer.parseInt(parallelParameters[1]); config.setMarkupDescriptionTreatmentTransformerSentenceChunkerRunMaximum(threadsPerSentenceChunking); config.setMarkupDescriptionTreatmentTransformerDescriptionExtractorRunMaximum(threadsPerDescriptionExtractor); } catch(Exception e) { log(LogLevel.ERROR, "Problem to convert parameter to Integer", e); System.exit(0); } } } if(commandLine.hasOption("n")) { config.setDatabaseHost(commandLine.getOptionValue("n")); } else { log(LogLevel.ERROR, "You have to specify a MySQL server hostname"); System.exit(0); //use standard value from RunConfig } if(commandLine.hasOption("p")) { config.setDatabasePort(commandLine.getOptionValue("p")); } else { log(LogLevel.ERROR, "You have to specify a MySQL server port"); System.exit(0); //use standard value from RunConfig } if(commandLine.hasOption("d")) { config.setDatabaseName(commandLine.getOptionValue("d")); } else { log(LogLevel.ERROR, "You have to specify a database name"); System.exit(0); //use standard value from RunConfig } if(commandLine.hasOption("u")) { config.setDatabaseUser(commandLine.getOptionValue("u")); } else { log(LogLevel.ERROR, "You have to specify a database user"); System.exit(0); //use standard value from RunConfig } if(commandLine.hasOption("s")) { config.setDatabasePassword(commandLine.getOptionValue("s")); } else { log(LogLevel.ERROR, "You have to specify a database password"); System.exit(0); //use standard value from RunConfig } //TODO databaseTablePrefix has to be given as user as a ID he remembered from LearnMain //since we have no user information to be able to generate an ID that allows to know //at least whos data to pull if(commandLine.hasOption("z")) { config.setDatabaseTablePrefix(commandLine.getOptionValue("z")); config.setDatabaseGlossaryTable(commandLine.getOptionValue("z") + "_permanentGlossary"); } else { log(LogLevel.ERROR, "You have to specify a database table prefix"); System.exit(0); } if (commandLine.hasOption("r")) { config.setResourcesDirectory(commandLine.getOptionValue("r")); } if (commandLine.hasOption("l")) { config.setSrcDirectory(commandLine.getOptionValue("l")); } } catch (ParseException e) { log(LogLevel.ERROR, "Problem parsing parameters", e); } config.setMarkupDescriptionTreatmentTransformer(MarkupDescriptionTreatmentTransformer.class); config.setRun(IPlantLearnRun.class); config.setGlossary(InMemoryGlossary.class); config.setTerminologyLearner(PerlTerminologyLearner.class); config.setDescriptionWriter(MOXyBinderDescriptionWriter.class); config.setOtoLiteReviewFile("nextStep.html"); }
diff --git a/src/taberystwyth/controller/TeamInsertionListener.java b/src/taberystwyth/controller/TeamInsertionListener.java index 0860f39..5225035 100644 --- a/src/taberystwyth/controller/TeamInsertionListener.java +++ b/src/taberystwyth/controller/TeamInsertionListener.java @@ -1,123 +1,137 @@ /* * This file is part of TAberystwyth, a debating competition organiser * Copyright (C) 2010, Roberto Sarrionandia and Cal Paterson * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package taberystwyth.controller; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import javax.swing.JOptionPane; import org.apache.log4j.Logger; import taberystwyth.db.TabServer; import taberystwyth.view.TeamInsertionFrame; /** * @author Roberto Sarrionandia [[email protected]] * @author Cal Paterson The listener for the TeamInsertionFrame * */ public class TeamInsertionListener implements ActionListener { private static final Logger LOG = Logger .getLogger(TeamInsertionListener.class); TeamInsertionFrame frame; /** * Constructor */ public TeamInsertionListener() { this.frame = TeamInsertionFrame.getInstance(); } @Override public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("Clear")) { frame.getTeamName().setText(""); frame.getSwing().setSelected(false); frame.getSpeaker1Name().setText(""); frame.getSpeaker1Institution().setText(""); frame.getSpeaker1ESL().setSelected(false); frame.getSpeaker1Novice().setSelected(false); frame.getSpeaker2Name().setText(""); frame.getSpeaker2Institution().setText(""); frame.getSpeaker2ESL().setSelected(false); frame.getSpeaker2Novice().setSelected(false); } if (e.getActionCommand().equals("Save")) { Connection sql; try { sql = TabServer.getConnectionPool().getConnection(); - String speaker1 = "insert into speakers (name, institution, esl, novice) values (?,?,?,?);"; + String speaker1 = "insert into speakers " + + "(\"name\", " + + "\"institution\", " + + "\"esl\", " + + "\"novice\") " + + "values (?,?,?,?);"; PreparedStatement p1 = sql.prepareStatement(speaker1); p1.setString(1, frame.getSpeaker1Name().getText()); p1.setString(2, frame.getSpeaker1Institution().getText()); p1.setBoolean(3, frame.getSpeaker1ESL().isSelected()); p1.setBoolean(4, frame.getSpeaker1Novice().isSelected()); LOG.debug("s1name = " + frame.getSpeaker1Name().getText()); p1.execute(); p1.close(); - String speaker2 = "insert into speakers (name, institution, esl, novice) values (?,?,?,?);"; + String speaker2 = "insert into speakers " + + "(\"name\", " + + "\"institution\", " + + "\"esl\", " + + "\"novice\") " + + "values (?,?,?,?);"; PreparedStatement p2 = sql.prepareStatement(speaker2); p2.setString(1, frame.getSpeaker2Name().getText()); p2.setString(2, frame.getSpeaker2Institution().getText()); p2.setBoolean(3, frame.getSpeaker2ESL().isSelected()); p2.setBoolean(4, frame.getSpeaker2Novice().isSelected()); LOG.debug("s1name = " + frame.getSpeaker2Name().getText()); p2.execute(); p2.close(); - String team = "insert into teams (speaker1, speaker2, name) values(?,?,?)"; + String team = "insert into teams " + + "(\"speaker1\", " + + "\"speaker2\", " + + "\"name\") " + + "values(?,?,?)"; PreparedStatement t = sql.prepareStatement(team); t.setString(1, frame.getSpeaker1Name().getText()); t.setString(2, frame.getSpeaker2Name().getText()); t.setString(3, frame.getTeamName().getText()); t.execute(); t.close(); sql.commit(); } catch (SQLException e1) { LOG.error("Unable to insert a team", e1); JOptionPane.showMessageDialog(frame, "Unable to insert that team into the database", "Database Error", JOptionPane.ERROR_MESSAGE); } frame.getSpeaker1Name().setText(""); frame.getSpeaker1Institution().setText(""); frame.getSpeaker1ESL().setSelected(false); frame.getSpeaker1Novice().setSelected(false); frame.getSpeaker2Name().setText(""); frame.getSpeaker2Institution().setText(""); frame.getSpeaker2ESL().setSelected(false); frame.getSpeaker2Novice().setSelected(false); frame.getTeamName().setText(""); } } }
false
true
public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("Clear")) { frame.getTeamName().setText(""); frame.getSwing().setSelected(false); frame.getSpeaker1Name().setText(""); frame.getSpeaker1Institution().setText(""); frame.getSpeaker1ESL().setSelected(false); frame.getSpeaker1Novice().setSelected(false); frame.getSpeaker2Name().setText(""); frame.getSpeaker2Institution().setText(""); frame.getSpeaker2ESL().setSelected(false); frame.getSpeaker2Novice().setSelected(false); } if (e.getActionCommand().equals("Save")) { Connection sql; try { sql = TabServer.getConnectionPool().getConnection(); String speaker1 = "insert into speakers (name, institution, esl, novice) values (?,?,?,?);"; PreparedStatement p1 = sql.prepareStatement(speaker1); p1.setString(1, frame.getSpeaker1Name().getText()); p1.setString(2, frame.getSpeaker1Institution().getText()); p1.setBoolean(3, frame.getSpeaker1ESL().isSelected()); p1.setBoolean(4, frame.getSpeaker1Novice().isSelected()); LOG.debug("s1name = " + frame.getSpeaker1Name().getText()); p1.execute(); p1.close(); String speaker2 = "insert into speakers (name, institution, esl, novice) values (?,?,?,?);"; PreparedStatement p2 = sql.prepareStatement(speaker2); p2.setString(1, frame.getSpeaker2Name().getText()); p2.setString(2, frame.getSpeaker2Institution().getText()); p2.setBoolean(3, frame.getSpeaker2ESL().isSelected()); p2.setBoolean(4, frame.getSpeaker2Novice().isSelected()); LOG.debug("s1name = " + frame.getSpeaker2Name().getText()); p2.execute(); p2.close(); String team = "insert into teams (speaker1, speaker2, name) values(?,?,?)"; PreparedStatement t = sql.prepareStatement(team); t.setString(1, frame.getSpeaker1Name().getText()); t.setString(2, frame.getSpeaker2Name().getText()); t.setString(3, frame.getTeamName().getText()); t.execute(); t.close(); sql.commit(); } catch (SQLException e1) { LOG.error("Unable to insert a team", e1); JOptionPane.showMessageDialog(frame, "Unable to insert that team into the database", "Database Error", JOptionPane.ERROR_MESSAGE); } frame.getSpeaker1Name().setText(""); frame.getSpeaker1Institution().setText(""); frame.getSpeaker1ESL().setSelected(false); frame.getSpeaker1Novice().setSelected(false); frame.getSpeaker2Name().setText(""); frame.getSpeaker2Institution().setText(""); frame.getSpeaker2ESL().setSelected(false); frame.getSpeaker2Novice().setSelected(false); frame.getTeamName().setText(""); } }
public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("Clear")) { frame.getTeamName().setText(""); frame.getSwing().setSelected(false); frame.getSpeaker1Name().setText(""); frame.getSpeaker1Institution().setText(""); frame.getSpeaker1ESL().setSelected(false); frame.getSpeaker1Novice().setSelected(false); frame.getSpeaker2Name().setText(""); frame.getSpeaker2Institution().setText(""); frame.getSpeaker2ESL().setSelected(false); frame.getSpeaker2Novice().setSelected(false); } if (e.getActionCommand().equals("Save")) { Connection sql; try { sql = TabServer.getConnectionPool().getConnection(); String speaker1 = "insert into speakers " + "(\"name\", " + "\"institution\", " + "\"esl\", " + "\"novice\") " + "values (?,?,?,?);"; PreparedStatement p1 = sql.prepareStatement(speaker1); p1.setString(1, frame.getSpeaker1Name().getText()); p1.setString(2, frame.getSpeaker1Institution().getText()); p1.setBoolean(3, frame.getSpeaker1ESL().isSelected()); p1.setBoolean(4, frame.getSpeaker1Novice().isSelected()); LOG.debug("s1name = " + frame.getSpeaker1Name().getText()); p1.execute(); p1.close(); String speaker2 = "insert into speakers " + "(\"name\", " + "\"institution\", " + "\"esl\", " + "\"novice\") " + "values (?,?,?,?);"; PreparedStatement p2 = sql.prepareStatement(speaker2); p2.setString(1, frame.getSpeaker2Name().getText()); p2.setString(2, frame.getSpeaker2Institution().getText()); p2.setBoolean(3, frame.getSpeaker2ESL().isSelected()); p2.setBoolean(4, frame.getSpeaker2Novice().isSelected()); LOG.debug("s1name = " + frame.getSpeaker2Name().getText()); p2.execute(); p2.close(); String team = "insert into teams " + "(\"speaker1\", " + "\"speaker2\", " + "\"name\") " + "values(?,?,?)"; PreparedStatement t = sql.prepareStatement(team); t.setString(1, frame.getSpeaker1Name().getText()); t.setString(2, frame.getSpeaker2Name().getText()); t.setString(3, frame.getTeamName().getText()); t.execute(); t.close(); sql.commit(); } catch (SQLException e1) { LOG.error("Unable to insert a team", e1); JOptionPane.showMessageDialog(frame, "Unable to insert that team into the database", "Database Error", JOptionPane.ERROR_MESSAGE); } frame.getSpeaker1Name().setText(""); frame.getSpeaker1Institution().setText(""); frame.getSpeaker1ESL().setSelected(false); frame.getSpeaker1Novice().setSelected(false); frame.getSpeaker2Name().setText(""); frame.getSpeaker2Institution().setText(""); frame.getSpeaker2ESL().setSelected(false); frame.getSpeaker2Novice().setSelected(false); frame.getTeamName().setText(""); } }
diff --git a/src/java/net/sf/jabref/Globals.java b/src/java/net/sf/jabref/Globals.java index 41e7adbdd..d3722be4e 100644 --- a/src/java/net/sf/jabref/Globals.java +++ b/src/java/net/sf/jabref/Globals.java @@ -1,965 +1,965 @@ /* (C) 2003 Nizar N. Batada, Morten O. Alver All programs in this directory and subdirectories are published under the GNU General Public License as described below. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Further information about the GNU GPL is available at: http://www.gnu.org/copyleft/gpl.ja.html */ package net.sf.jabref; import java.io.* ; import java.util.* ; import java.util.logging.* ; import java.util.logging.Filter ; import java.awt.* ; import javax.swing.* ; import net.sf.jabref.collab.* ; import net.sf.jabref.imports.* ; import net.sf.jabref.util.* ; import net.sf.jabref.journals.JournalAbbreviations; public class Globals { public static int SHORTCUT_MASK,// = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); FUTURE_YEAR = 2050, // Needs to give a year definitely in the future. Used for guessing the // year field when parsing textual data. :-) STANDARD_EXPORT_COUNT = 5, // The number of standard export formats. METADATA_LINE_LENGTH = 70; // The line length used to wrap metadata. private static String resourcePrefix = "resource/JabRef", menuResourcePrefix = "resource/Menu", integrityResourcePrefix = "resource/IntegrityMessage"; private static final String buildInfos = "/resource/build.properties" ; private static String logfile = "jabref.log"; public static ResourceBundle messages, menuTitles, intMessages ; public static FileUpdateMonitor fileUpdateMonitor = new FileUpdateMonitor(); public static ImportFormatReader importFormatReader = new ImportFormatReader(); public static String VERSION, BUILD, BUILD_DATE ; static { TBuildInfo bi = new TBuildInfo(buildInfos) ; VERSION = bi.getBUILD_VERSION() ; BUILD = bi.getBUILD_NUMBER() ; BUILD_DATE = bi.getBUILD_DATE() ; } //public static ResourceBundle preferences = ResourceBundle.getBundle("resource/defaultPrefs"); public static Locale locale; public static final String FILETYPE_PREFS_EXT = "_dir", SELECTOR_META_PREFIX = "selector_", LAYOUT_PREFIX = "/resource/layout/", MAC = "Mac OS X", DOI_LOOKUP_PREFIX = "http://dx.doi.org/", NONE = "_non__", FORMATTER_PACKAGE = "net.sf.jabref.export.layout.format."; public static float duplicateThreshold = 0.75f; private static Handler consoleHandler = new java.util.logging.ConsoleHandler(); public static String[] ENCODINGS = new String[] {"ISO8859_1", "UTF8", "UTF-16", "ASCII", "Cp1250", "Cp1251", "Cp1252", "Cp1253", "Cp1254", "Cp1257", "JIS", "SJIS", "EUC-JP", // Added Japanese encodings. "Big5", "Big5_HKSCS", "GBK", "ISO8859_2", "ISO8859_3", "ISO8859_4", "ISO8859_5", "ISO8859_6", "ISO8859_7", "ISO8859_8", "ISO8859_9", "ISO8859_13", "ISO8859_15"}; // String array that maps from month number to month string label: public static String[] MONTHS = new String[] {"jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"}; // Map that maps from month string labels to public static Map MONTH_STRINGS = new HashMap(); static { MONTH_STRINGS.put("jan", "January"); MONTH_STRINGS.put("feb", "February"); MONTH_STRINGS.put("mar", "March"); MONTH_STRINGS.put("apr", "April"); MONTH_STRINGS.put("may", "May"); MONTH_STRINGS.put("jun", "June"); MONTH_STRINGS.put("jul", "July"); MONTH_STRINGS.put("aug", "August"); MONTH_STRINGS.put("sep", "September"); MONTH_STRINGS.put("oct", "October"); MONTH_STRINGS.put("nov", "November"); MONTH_STRINGS.put("dec", "December"); } public static GlobalFocusListener focusListener = new GlobalFocusListener(); public static JabRefPreferences prefs = null; public static HelpDialog helpDiag = null; public static String osName = System.getProperty("os.name", "def"); public static boolean ON_MAC = (osName.equals(MAC)), ON_WIN = osName.startsWith("Windows"); public static String[] SKIP_WORDS = {"a", "an", "the", "for", "on"}; public static SidePaneManager sidePaneManager; public static final String NEWLINE = System.getProperty("line.separator"); public static final boolean UNIX_NEWLINE = NEWLINE.equals("\n"); // true if we have unix newlines. public static final String BIBTEX_STRING = "__string"; // "Fieldname" to indicate that a field should be treated as a bibtex string. Used when writing database to file. public static void logger(String s) { Logger.global.info(s); } public static void turnOffLogging() { // only log exceptions Logger.global.setLevel(java.util.logging.Level.SEVERE); } // should be only called once public static void turnOnConsoleLogging() { Logger.global.addHandler(consoleHandler); } public static void turnOnFileLogging() { Logger.global.setLevel(java.util.logging.Level.ALL); java.util.logging.Handler handler; handler = new ConsoleHandler(); /*try { handler = new FileHandler(logfile); // this will overwrite } catch (IOException e) { //can't open log file so use console e.printStackTrace(); } */ Logger.global.addHandler(handler); handler.setFilter(new Filter() { // select what gets logged public boolean isLoggable(LogRecord record) { return true; } }); } /** * String constants. */ public static final String KEY_FIELD = "bibtexkey", SEARCH = "__search", GROUPSEARCH = "__groupsearch", MARKED = "__markedentry", OWNER = "owner", // Using this when I have no database open when I read // non bibtex file formats (used byte ImportFormatReader.java DEFAULT_BIBTEXENTRY_ID = "__ID"; public static void setLanguage(String language, String country) { locale = new Locale(language, country); messages = ResourceBundle.getBundle(resourcePrefix, locale); menuTitles = ResourceBundle.getBundle(menuResourcePrefix, locale); intMessages = ResourceBundle.getBundle(integrityResourcePrefix, locale); Locale.setDefault(locale); javax.swing.JComponent.setDefaultLocale(locale); } public static JournalAbbreviations journalAbbrev; public static String lang(String key, String[] params) { String translation = null; try { if (Globals.messages != null) { translation = Globals.messages.getString(key.replaceAll(" ", "_")); } } catch (MissingResourceException ex) { translation = key; logger("Warning: could not get translation for \"" + key + "\""); } if ((translation != null) && (translation.length() != 0)) { translation = translation.replaceAll("_", " "); StringBuffer sb = new StringBuffer(); boolean b = false; char c; for (int i = 0; i < translation.length(); ++i) { c = translation.charAt(i); if (c == '%') { b = true; } else { if (!b) { sb.append(c); } else { b = false; try { int index = Integer.parseInt(String.valueOf(c)); if (params != null && index >= 0 && index <= params.length) sb.append(params[index]); } catch (NumberFormatException e) { // append literally (for quoting) or insert special symbol switch (c) { case 'c': // colon sb.append(':'); break; case 'e': // equal sb.append('='); break; default: // anything else, e.g. % sb.append(c); } } } } } return sb.toString(); } return key; } public static String lang(String key) { return lang(key, (String[])null); } public static String lang(String key, String s1) { return lang(key, new String[]{s1}); } public static String lang(String key, String s1, String s2) { return lang(key, new String[]{s1, s2}); } public static String lang(String key, String s1, String s2, String s3) { return lang(key, new String[]{s1, s2, s3}); } public static String menuTitle(String key) { String translation = null; try { if (Globals.messages != null) { translation = Globals.menuTitles.getString(key.replaceAll(" ", "_")); } } catch (MissingResourceException ex) { translation = key; // System.err.println("Warning: could not get menu item translation for \"" // + key + "\""); } if ((translation != null) && (translation.length() != 0)) { return translation.replaceAll("_", " "); } else { return key; } } public static String getIntegrityMessage(String key) { String translation = null; try { if (Globals.intMessages != null) { translation = Globals.intMessages.getString(key); } } catch (MissingResourceException ex) { translation = key; // System.err.println("Warning: could not get menu item translation for \"" // + key + "\""); } if ((translation != null) && (translation.length() != 0)) { return translation ; } else { return key; } } //============================================================ // Using the hashmap of entry types found in BibtexEntryType //============================================================ public static BibtexEntryType getEntryType(String type) { // decide which entryType object to return Object o = BibtexEntryType.ALL_TYPES.get(type); if (o != null) { return (BibtexEntryType) o; } else { return BibtexEntryType.OTHER; } /* if(type.equals("article")) return BibtexEntryType.ARTICLE; else if(type.equals("book")) return BibtexEntryType.BOOK; else if(type.equals("inproceedings")) return BibtexEntryType.INPROCEEDINGS; */ } /** * This method provides the correct opening brace to use when writing a field * to BibTeX format. * @return A String containing the braces to use. */ public static String getOpeningBrace() { return "{"; /* As of version 2.0, storing all fields with double braces is no longer supported, because it causes problems with e.g. the author field. if (prefs.getBoolean("autoDoubleBraces")) return "{{"; else return "{"; */ } /** * This method provides the correct closing brace to use when writing a field * to BibTeX format. * @return A String containing the braces to use. */ public static String getClosingBrace() { return "}"; /* As of version 2.0, storing all fields with double braces is no longer supported, because it causes problems with e.g. the author field. if (prefs.getBoolean("autoDoubleBraces")) return "}}"; else */ } /* public static void setupKeyBindings(JabRefPreferences prefs) { }*/ public static String getNewFile(JFrame owner, JabRefPreferences prefs, File directory, String extension, int dialogType, boolean updateWorkingDirectory) { return getNewFile(owner, prefs, directory, extension, null, dialogType, updateWorkingDirectory, false); } public static String getNewFile(JFrame owner, JabRefPreferences prefs, File directory, String extension, String description, int dialogType, boolean updateWorkingDirectory) { return getNewFile(owner, prefs, directory, extension, description, dialogType, updateWorkingDirectory, false); } public static String getNewFile(JFrame owner, JabRefPreferences prefs, File directory, String extension, OpenFileFilter off, int dialogType, boolean updateWorkingDirectory) { return getNewFile(owner, prefs, directory, extension, null, off, dialogType, updateWorkingDirectory, false); } public static String getNewDir(JFrame owner, JabRefPreferences prefs, File directory, String extension, int dialogType, boolean updateWorkingDirectory) { return getNewFile(owner, prefs, directory, extension, null, dialogType, updateWorkingDirectory, true); } public static String getNewDir(JFrame owner, JabRefPreferences prefs, File directory, String extension, String description, int dialogType, boolean updateWorkingDirectory) { return getNewFile(owner, prefs, directory, extension, description, dialogType, updateWorkingDirectory, true); } private static String getNewFile(JFrame owner, JabRefPreferences prefs, File directory, String extension, String description, int dialogType, boolean updateWorkingDirectory, boolean dirOnly) { OpenFileFilter off = null; if (extension == null) off = new OpenFileFilter(); else if (!extension.equals(NONE)) off = new OpenFileFilter(extension); return getNewFile(owner, prefs, directory, extension, description, off, dialogType, updateWorkingDirectory, dirOnly); } private static String getNewFile(JFrame owner, JabRefPreferences prefs, File directory, String extension, String description, OpenFileFilter off, int dialogType, boolean updateWorkingDirectory, boolean dirOnly) { if (ON_MAC) { return getNewFileForMac(owner, prefs, directory, extension, dialogType, updateWorkingDirectory, dirOnly, off); } JFileChooser fc = null; try { fc = new JabRefFileChooser(directory); } catch (InternalError errl) { // This try/catch clause was added because a user reported an // InternalError getting thrown on WinNT, presumably because of a // bug in JGoodies Windows PLAF. This clause can be removed if the // bug is fixed, but for now we just resort to the native file // dialog, using the same method as is always used on Mac: return getNewFileForMac(owner, prefs, directory, extension, dialogType, updateWorkingDirectory, dirOnly, off); } if (dirOnly) { fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); } fc.addChoosableFileFilter(off); fc.setDialogType(dialogType); int dialogResult = JFileChooser.CANCEL_OPTION ; if (dialogType == JFileChooser.OPEN_DIALOG) { - dialogResult = fc.showOpenDialog(null); + dialogResult = fc.showOpenDialog(owner); } else if (dialogType == JFileChooser.SAVE_DIALOG){ - dialogResult = fc.showSaveDialog(null); + dialogResult = fc.showSaveDialog(owner); } else { - dialogResult = fc.showDialog(null, description); + dialogResult = fc.showDialog(owner, description); } // the getSelectedFile method returns a valid fileselection // (if something is selected) indepentently from dialog return status if (dialogResult != JFileChooser.APPROVE_OPTION) return null ; // okay button File selectedFile = fc.getSelectedFile(); if (selectedFile == null) { // cancel return null; } // If this is a save dialog, and the user has not chosen "All files" as filter // we enforce the given extension. But only if extension is not null. if ((extension != null) && (dialogType == JFileChooser.SAVE_DIALOG) && (fc.getFileFilter() == off) && !off.accept(selectedFile)) { // add the first extension if there are multiple extensions selectedFile = new File(selectedFile.getPath() + extension.split("[, ]+",0)[0]); } if (updateWorkingDirectory) { prefs.put("workingDirectory", selectedFile.getPath()); } return selectedFile.getAbsolutePath(); } private static String getNewFileForMac(JFrame owner, JabRefPreferences prefs, File directory, String extensions, int dialogType, boolean updateWorkingDirectory, boolean dirOnly, FilenameFilter filter) { FileDialog fc = new FileDialog(owner); //fc.setFilenameFilter(filter); if (directory != null) { fc.setDirectory(directory.getParent()); } if (dialogType == JFileChooser.OPEN_DIALOG) { fc.setMode(FileDialog.LOAD); } else { fc.setMode(FileDialog.SAVE); } fc.show(); if (fc.getFile() != null) { prefs.put("workingDirectory", fc.getDirectory() + fc.getFile()); return fc.getDirectory() + fc.getFile(); } else { return null; } } public static String SPECIAL_COMMAND_CHARS = "\"`^~'c"; public static HashMap HTML_CHARS = new HashMap(), HTMLCHARS = new HashMap(), XML_CHARS = new HashMap(), UNICODE_CHARS = new HashMap(), RTFCHARS = new HashMap(); static { //System.out.println(journalAbbrev.getAbbreviatedName("Journal of Fish Biology", true)); //System.out.println(journalAbbrev.getAbbreviatedName("Journal of Fish Biology", false)); //System.out.println(journalAbbrev.getFullName("Aquaculture Eng.")); /*for (Iterator i=journalAbbrev.fullNameIterator(); i.hasNext();) { String s = (String)i.next(); System.out.println(journalAbbrev.getFullName(s)+" : "+journalAbbrev.getAbbreviatedName(s, true)); } */ // Start the thread that monitors file time stamps. //Util.pr("Starting FileUpdateMonitor thread. Globals line 293."); fileUpdateMonitor.start(); try { SHORTCUT_MASK = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); } catch (Throwable t) { } /* HTML_CHARS.put("\\{\\\\\\\"\\{a\\}\\}", "&auml;"); HTML_CHARS.put("\\{\\\\\\\"\\{A\\}\\}", "&Auml;"); HTML_CHARS.put("\\{\\\\\\\"\\{e\\}\\}", "&euml;"); HTML_CHARS.put("\\{\\\\\\\"\\{E\\}\\}", "&Euml;"); HTML_CHARS.put("\\{\\\\\\\"\\{i\\}\\}", "&iuml;"); HTML_CHARS.put("\\{\\\\\\\"\\{I\\}\\}", "&Iuml;"); HTML_CHARS.put("\\{\\\\\\\"\\{o\\}\\}", "&ouml;"); HTML_CHARS.put("\\{\\\\\\\"\\{O\\}\\}", "&Ouml;"); HTML_CHARS.put("\\{\\\\\\\"\\{u\\}\\}", "&uuml;"); HTML_CHARS.put("\\{\\\\\\\"\\{U\\}\\}", "&Uuml;"); HTML_CHARS.put("\\{\\\\\\`\\{e\\}\\}", "&egrave;"); HTML_CHARS.put("\\{\\\\\\`\\{E\\}\\}", "&Egrave;"); HTML_CHARS.put("\\{\\\\\\`\\{i\\}\\}", "&igrave;"); HTML_CHARS.put("\\{\\\\\\`\\{I\\}\\}", "&Igrave;"); HTML_CHARS.put("\\{\\\\\\`\\{o\\}\\}", "&ograve;"); HTML_CHARS.put("\\{\\\\\\`\\{O\\}\\}", "&Ograve;"); HTML_CHARS.put("\\{\\\\\\`\\{u\\}\\}", "&ugrave;"); HTML_CHARS.put("\\{\\\\\\`\\{U\\}\\}", "&Ugrave;"); HTML_CHARS.put("\\{\\\\\\'\\{e\\}\\}", "&eacute;"); HTML_CHARS.put("\\{\\\\\\'\\{E\\}\\}", "&Eacute;"); HTML_CHARS.put("\\{\\\\\\'\\{i\\}\\}", "&iacute;"); HTML_CHARS.put("\\{\\\\\\'\\{I\\}\\}", "&Iacute;"); HTML_CHARS.put("\\{\\\\\\'\\{o\\}\\}", "&oacute;"); HTML_CHARS.put("\\{\\\\\\'\\{O\\}\\}", "&Oacute;"); HTML_CHARS.put("\\{\\\\\\'\\{u\\}\\}", "&uacute;"); HTML_CHARS.put("\\{\\\\\\'\\{U\\}\\}", "&Uacute;"); HTML_CHARS.put("\\{\\\\\\'\\{a\\}\\}", "&aacute;"); HTML_CHARS.put("\\{\\\\\\'\\{A\\}\\}", "&Aacute;"); HTML_CHARS.put("\\{\\\\\\^\\{o\\}\\}", "&ocirc;"); HTML_CHARS.put("\\{\\\\\\^\\{O\\}\\}", "&Ocirc;"); HTML_CHARS.put("\\{\\\\\\^\\{u\\}\\}", "&ucirc;"); HTML_CHARS.put("\\{\\\\\\^\\{U\\}\\}", "&Ucirc;"); HTML_CHARS.put("\\{\\\\\\^\\{e\\}\\}", "&ecirc;"); HTML_CHARS.put("\\{\\\\\\^\\{E\\}\\}", "&Ecirc;"); HTML_CHARS.put("\\{\\\\\\^\\{i\\}\\}", "&icirc;"); HTML_CHARS.put("\\{\\\\\\^\\{I\\}\\}", "&Icirc;"); HTML_CHARS.put("\\{\\\\\\~\\{o\\}\\}", "&otilde;"); HTML_CHARS.put("\\{\\\\\\~\\{O\\}\\}", "&Otilde;"); HTML_CHARS.put("\\{\\\\\\~\\{n\\}\\}", "&ntilde;"); HTML_CHARS.put("\\{\\\\\\~\\{N\\}\\}", "&Ntilde;"); HTML_CHARS.put("\\{\\\\\\~\\{a\\}\\}", "&atilde;"); HTML_CHARS.put("\\{\\\\\\~\\{A\\}\\}", "&Atilde;"); */ HTMLCHARS.put("\"a", "&auml;"); HTMLCHARS.put("\"A", "&Auml;"); HTMLCHARS.put("\"e", "&euml;"); HTMLCHARS.put("\"E", "&Euml;"); HTMLCHARS.put("\"i", "&iuml;"); HTMLCHARS.put("\"I", "&Iuml;"); HTMLCHARS.put("\"o", "&ouml;"); HTMLCHARS.put("\"O", "&Ouml;"); HTMLCHARS.put("\"u", "&uuml;"); HTMLCHARS.put("\"U", "&Uuml;"); HTMLCHARS.put("`a", "&agrave;"); HTMLCHARS.put("`A", "&Agrave;"); HTMLCHARS.put("`e", "&egrave;"); HTMLCHARS.put("`E", "&Egrave;"); HTMLCHARS.put("`i", "&igrave;"); HTMLCHARS.put("`I", "&Igrave;"); HTMLCHARS.put("`o", "&ograve;"); HTMLCHARS.put("`O", "&Ograve;"); HTMLCHARS.put("`u", "&ugrave;"); HTMLCHARS.put("`U", "&Ugrave;"); HTMLCHARS.put("'e", "&eacute;"); HTMLCHARS.put("'E", "&Eacute;"); HTMLCHARS.put("'i", "&iacute;"); HTMLCHARS.put("'I", "&Iacute;"); HTMLCHARS.put("'o", "&oacute;"); HTMLCHARS.put("'O", "&Oacute;"); HTMLCHARS.put("'u", "&uacute;"); HTMLCHARS.put("'U", "&Uacute;"); HTMLCHARS.put("'a", "&aacute;"); HTMLCHARS.put("'A", "&Aacute;"); HTMLCHARS.put("^o", "&ocirc;"); HTMLCHARS.put("^O", "&Ocirc;"); HTMLCHARS.put("^u", "&ucirc;"); HTMLCHARS.put("^U", "&Ucirc;"); HTMLCHARS.put("^e", "&ecirc;"); HTMLCHARS.put("^E", "&Ecirc;"); HTMLCHARS.put("^i", "&icirc;"); HTMLCHARS.put("^I", "&Icirc;"); HTMLCHARS.put("~o", "&otilde;"); HTMLCHARS.put("~O", "&Otilde;"); HTMLCHARS.put("~n", "&ntilde;"); HTMLCHARS.put("~N", "&Ntilde;"); HTMLCHARS.put("~a", "&atilde;"); HTMLCHARS.put("~A", "&Atilde;"); HTMLCHARS.put("cc", "&ccedil;"); HTMLCHARS.put("cC", "&Ccedil;"); /* HTML_CHARS.put("\\{\\\\\\\"a\\}", "&auml;"); HTML_CHARS.put("\\{\\\\\\\"A\\}", "&Auml;"); HTML_CHARS.put("\\{\\\\\\\"e\\}", "&euml;"); HTML_CHARS.put("\\{\\\\\\\"E\\}", "&Euml;"); HTML_CHARS.put("\\{\\\\\\\"i\\}", "&iuml;"); HTML_CHARS.put("\\{\\\\\\\"I\\}", "&Iuml;"); HTML_CHARS.put("\\{\\\\\\\"o\\}", "&ouml;"); HTML_CHARS.put("\\{\\\\\\\"O\\}", "&Ouml;"); HTML_CHARS.put("\\{\\\\\\\"u\\}", "&uuml;"); HTML_CHARS.put("\\{\\\\\\\"U\\}", "&Uuml;"); HTML_CHARS.put("\\{\\\\\\`e\\}", "&egrave;"); HTML_CHARS.put("\\{\\\\\\`E\\}", "&Egrave;"); HTML_CHARS.put("\\{\\\\\\`i\\}", "&igrave;"); HTML_CHARS.put("\\{\\\\\\`I\\}", "&Igrave;"); HTML_CHARS.put("\\{\\\\\\`o\\}", "&ograve;"); HTML_CHARS.put("\\{\\\\\\`O\\}", "&Ograve;"); HTML_CHARS.put("\\{\\\\\\`u\\}", "&ugrave;"); HTML_CHARS.put("\\{\\\\\\`U\\}", "&Ugrave;"); HTML_CHARS.put("\\{\\\\\\'A\\}", "&eacute;"); HTML_CHARS.put("\\{\\\\\\'E\\}", "&Eacute;"); HTML_CHARS.put("\\{\\\\\\'i\\}", "&iacute;"); HTML_CHARS.put("\\{\\\\\\'I\\}", "&Iacute;"); HTML_CHARS.put("\\{\\\\\\'o\\}", "&oacute;"); HTML_CHARS.put("\\{\\\\\\'O\\}", "&Oacute;"); HTML_CHARS.put("\\{\\\\\\'u\\}", "&uacute;"); HTML_CHARS.put("\\{\\\\\\'U\\}", "&Uacute;"); HTML_CHARS.put("\\{\\\\\\'a\\}", "&aacute;"); HTML_CHARS.put("\\{\\\\\\'A\\}", "&Aacute;"); HTML_CHARS.put("\\{\\\\\\^o\\}", "&ocirc;"); HTML_CHARS.put("\\{\\\\\\^O\\}", "&Ocirc;"); HTML_CHARS.put("\\{\\\\\\^u\\}", "&ucirc;"); HTML_CHARS.put("\\{\\\\\\^U\\}", "&Ucirc;"); HTML_CHARS.put("\\{\\\\\\^e\\}", "&ecirc;"); HTML_CHARS.put("\\{\\\\\\^E\\}", "&Ecirc;"); HTML_CHARS.put("\\{\\\\\\^i\\}", "&icirc;"); HTML_CHARS.put("\\{\\\\\\^I\\}", "&Icirc;"); HTML_CHARS.put("\\{\\\\\\~o\\}", "&otilde;"); HTML_CHARS.put("\\{\\\\\\~O\\}", "&Otilde;"); HTML_CHARS.put("\\{\\\\\\~n\\}", "&ntilde;"); HTML_CHARS.put("\\{\\\\\\~N\\}", "&Ntilde;"); HTML_CHARS.put("\\{\\\\\\~a\\}", "&atilde;"); HTML_CHARS.put("\\{\\\\\\~A\\}", "&Atilde;"); HTML_CHARS.put("\\{\\\\c c\\}", "&ccedil;"); HTML_CHARS.put("\\{\\\\c C\\}", "&Ccedil;"); */ XML_CHARS.put("\\{\\\\\\\"\\{a\\}\\}", "&#x00E4;"); XML_CHARS.put("\\{\\\\\\\"\\{A\\}\\}", "&#x00C4;"); XML_CHARS.put("\\{\\\\\\\"\\{e\\}\\}", "&#x00EB;"); XML_CHARS.put("\\{\\\\\\\"\\{E\\}\\}", "&#x00CB;"); XML_CHARS.put("\\{\\\\\\\"\\{i\\}\\}", "&#x00EF;"); XML_CHARS.put("\\{\\\\\\\"\\{I\\}\\}", "&#x00CF;"); XML_CHARS.put("\\{\\\\\\\"\\{o\\}\\}", "&#x00F6;"); XML_CHARS.put("\\{\\\\\\\"\\{O\\}\\}", "&#x00D6;"); XML_CHARS.put("\\{\\\\\\\"\\{u\\}\\}", "&#x00FC;"); XML_CHARS.put("\\{\\\\\\\"\\{U\\}\\}", "&#x00DC;"); XML_CHARS.put("\\{\\\\\\`\\{e\\}\\}", "&#x00E8;"); XML_CHARS.put("\\{\\\\\\`\\{E\\}\\}", "&#x00C8;"); XML_CHARS.put("\\{\\\\\\`\\{i\\}\\}", "&#x00EC;"); XML_CHARS.put("\\{\\\\\\`\\{I\\}\\}", "&#x00CC;"); XML_CHARS.put("\\{\\\\\\`\\{o\\}\\}", "&#x00F2;"); XML_CHARS.put("\\{\\\\\\`\\{O\\}\\}", "&#x00D2;"); XML_CHARS.put("\\{\\\\\\`\\{u\\}\\}", "&#x00F9;"); XML_CHARS.put("\\{\\\\\\`\\{U\\}\\}", "&#x00D9;"); XML_CHARS.put("\\{\\\\\\'\\{e\\}\\}", "&#x00E9;"); XML_CHARS.put("\\{\\\\\\\uFFFD\\{E\\}\\}", "&#x00C9;"); XML_CHARS.put("\\{\\\\\\\uFFFD\\{i\\}\\}", "&#x00ED;"); XML_CHARS.put("\\{\\\\\\\uFFFD\\{I\\}\\}", "&#x00CD;"); XML_CHARS.put("\\{\\\\\\\uFFFD\\{o\\}\\}", "&#x00F3;"); XML_CHARS.put("\\{\\\\\\\uFFFD\\{O\\}\\}", "&#x00D3;"); XML_CHARS.put("\\{\\\\\\\uFFFD\\{u\\}\\}", "&#x00FA;"); XML_CHARS.put("\\{\\\\\\\uFFFD\\{U\\}\\}", "&#x00DA;"); XML_CHARS.put("\\{\\\\\\\uFFFD\\{a\\}\\}", "&#x00E1;"); XML_CHARS.put("\\{\\\\\\\uFFFD\\{A\\}\\}", "&#x00C1;"); XML_CHARS.put("\\{\\\\\\^\\{o\\}\\}", "&#x00F4;"); XML_CHARS.put("\\{\\\\\\^\\{O\\}\\}", "&#x00D4;"); XML_CHARS.put("\\{\\\\\\^\\{u\\}\\}", "&#x00F9;"); XML_CHARS.put("\\{\\\\\\^\\{U\\}\\}", "&#x00D9;"); XML_CHARS.put("\\{\\\\\\^\\{e\\}\\}", "&#x00EA;"); XML_CHARS.put("\\{\\\\\\^\\{E\\}\\}", "&#x00CA;"); XML_CHARS.put("\\{\\\\\\^\\{i\\}\\}", "&#x00EE;"); XML_CHARS.put("\\{\\\\\\^\\{I\\}\\}", "&#x00CE;"); XML_CHARS.put("\\{\\\\\\~\\{o\\}\\}", "&#x00F5;"); XML_CHARS.put("\\{\\\\\\~\\{O\\}\\}", "&#x00D5;"); XML_CHARS.put("\\{\\\\\\~\\{n\\}\\}", "&#x00F1;"); XML_CHARS.put("\\{\\\\\\~\\{N\\}\\}", "&#x00D1;"); XML_CHARS.put("\\{\\\\\\~\\{a\\}\\}", "&#x00E3;"); XML_CHARS.put("\\{\\\\\\~\\{A\\}\\}", "&#x00C3;"); XML_CHARS.put("\\{\\\\\\\"a\\}", "&#x00E4;"); XML_CHARS.put("\\{\\\\\\\"A\\}", "&#x00C4;"); XML_CHARS.put("\\{\\\\\\\"e\\}", "&#x00EB;"); XML_CHARS.put("\\{\\\\\\\"E\\}", "&#x00CB;"); XML_CHARS.put("\\{\\\\\\\"i\\}", "&#x00EF;"); XML_CHARS.put("\\{\\\\\\\"I\\}", "&#x00CF;"); XML_CHARS.put("\\{\\\\\\\"o\\}", "&#x00F6;"); XML_CHARS.put("\\{\\\\\\\"O\\}", "&#x00D6;"); XML_CHARS.put("\\{\\\\\\\"u\\}", "&#x00FC;"); XML_CHARS.put("\\{\\\\\\\"U\\}", "&#x00DC;"); XML_CHARS.put("\\{\\\\\\`e\\}", "&#x00E8;"); XML_CHARS.put("\\{\\\\\\`E\\}", "&#x00C8;"); XML_CHARS.put("\\{\\\\\\`i\\}", "&#x00EC;"); XML_CHARS.put("\\{\\\\\\`I\\}", "&#x00CC;"); XML_CHARS.put("\\{\\\\\\`o\\}", "&#x00F2;"); XML_CHARS.put("\\{\\\\\\`O\\}", "&#x00D2;"); XML_CHARS.put("\\{\\\\\\`u\\}", "&#x00F9;"); XML_CHARS.put("\\{\\\\\\`U\\}", "&#x00D9;"); XML_CHARS.put("\\{\\\\\\'e\\}", "&#x00E9;"); XML_CHARS.put("\\{\\\\\\'E\\}", "&#x00C9;"); XML_CHARS.put("\\{\\\\\\'i\\}", "&#x00ED;"); XML_CHARS.put("\\{\\\\\\'I\\}", "&#x00CD;"); XML_CHARS.put("\\{\\\\\\'o\\}", "&#x00F3;"); XML_CHARS.put("\\{\\\\\\'O\\}", "&#x00D3;"); XML_CHARS.put("\\{\\\\\\'u\\}", "&#x00FA;"); XML_CHARS.put("\\{\\\\\\'U\\}", "&#x00DA;"); XML_CHARS.put("\\{\\\\\\'a\\}", "&#x00E1;"); XML_CHARS.put("\\{\\\\\\'A\\}", "&#x00C1;"); XML_CHARS.put("\\{\\\\\\^o\\}", "&#x00F4;"); XML_CHARS.put("\\{\\\\\\^O\\}", "&#x00D4;"); XML_CHARS.put("\\{\\\\\\^u\\}", "&#x00F9;"); XML_CHARS.put("\\{\\\\\\^U\\}", "&#x00D9;"); XML_CHARS.put("\\{\\\\\\^e\\}", "&#x00EA;"); XML_CHARS.put("\\{\\\\\\^E\\}", "&#x00CA;"); XML_CHARS.put("\\{\\\\\\^i\\}", "&#x00EE;"); XML_CHARS.put("\\{\\\\\\^I\\}", "&#x00CE;"); XML_CHARS.put("\\{\\\\\\~o\\}", "&#x00F5;"); XML_CHARS.put("\\{\\\\\\~O\\}", "&#x00D5;"); XML_CHARS.put("\\{\\\\\\~n\\}", "&#x00F1;"); XML_CHARS.put("\\{\\\\\\~N\\}", "&#x00D1;"); XML_CHARS.put("\\{\\\\\\~a\\}", "&#x00E3;"); XML_CHARS.put("\\{\\\\\\~A\\}", "&#x00C3;"); UNICODE_CHARS.put("\u00C0", "A"); UNICODE_CHARS.put("\u00C1", "A"); UNICODE_CHARS.put("\u00C2", "A"); UNICODE_CHARS.put("\u00C3", "A"); UNICODE_CHARS.put("\u00C4", "A"); UNICODE_CHARS.put("\u00C5", "Aa"); UNICODE_CHARS.put("\u00C6", "Ae"); UNICODE_CHARS.put("\u00C7", "C"); UNICODE_CHARS.put("\u00C8", "E"); UNICODE_CHARS.put("\u00C9", "E"); UNICODE_CHARS.put("\u00CA", "E"); UNICODE_CHARS.put("\u00CB", "E"); UNICODE_CHARS.put("\u00CC", "I"); UNICODE_CHARS.put("\u00CD", "I"); UNICODE_CHARS.put("\u00CE", "I"); UNICODE_CHARS.put("\u00CF", "I"); UNICODE_CHARS.put("\u00D0", "D"); UNICODE_CHARS.put("\u00D1", "N"); UNICODE_CHARS.put("\u00D2", "O"); UNICODE_CHARS.put("\u00D3", "O"); UNICODE_CHARS.put("\u00D4", "O"); UNICODE_CHARS.put("\u00D5", "O"); UNICODE_CHARS.put("\u00D6", "Oe"); UNICODE_CHARS.put("\u00D8", "Oe"); UNICODE_CHARS.put("\u00D9", "U"); UNICODE_CHARS.put("\u00DA", "U"); UNICODE_CHARS.put("\u00DB", "U"); UNICODE_CHARS.put("\u00DC", "Ue"); // U umlaut .. UNICODE_CHARS.put("\u00DD", "Y"); UNICODE_CHARS.put("\u00DF", "ss"); UNICODE_CHARS.put("\u00E0", "a"); UNICODE_CHARS.put("\u00E1", "a"); UNICODE_CHARS.put("\u00E2", "a"); UNICODE_CHARS.put("\u00E3", "a"); UNICODE_CHARS.put("\u00E4", "ae"); UNICODE_CHARS.put("\u00E5", "aa"); UNICODE_CHARS.put("\u00E6", "ae"); UNICODE_CHARS.put("\u00E7", "c"); UNICODE_CHARS.put("\u00E8", "e"); UNICODE_CHARS.put("\u00E9", "e"); UNICODE_CHARS.put("\u00EA", "e"); UNICODE_CHARS.put("\u00EB", "e"); UNICODE_CHARS.put("\u00EC", "i"); UNICODE_CHARS.put("\u00ED", "i"); UNICODE_CHARS.put("\u00EE", "i"); UNICODE_CHARS.put("\u00EF", "i"); UNICODE_CHARS.put("\u00F0", "o"); UNICODE_CHARS.put("\u00F1", "n"); UNICODE_CHARS.put("\u00F2", "o"); UNICODE_CHARS.put("\u00F3", "o"); UNICODE_CHARS.put("\u00F4", "o"); UNICODE_CHARS.put("\u00F5", "o"); UNICODE_CHARS.put("\u00F6", "oe"); UNICODE_CHARS.put("\u00F8", "oe"); UNICODE_CHARS.put("\u00F9", "u"); UNICODE_CHARS.put("\u00FA", "u"); UNICODE_CHARS.put("\u00FB", "u"); UNICODE_CHARS.put("\u00FC", "ue"); // u umlaut... UNICODE_CHARS.put("\u00FD", "y"); UNICODE_CHARS.put("\u00FF", "y"); UNICODE_CHARS.put("\u0100", "A"); UNICODE_CHARS.put("\u0101", "a"); UNICODE_CHARS.put("\u0102", "A"); UNICODE_CHARS.put("\u0103", "a"); UNICODE_CHARS.put("\u0104", "A"); UNICODE_CHARS.put("\u0105", "a"); UNICODE_CHARS.put("\u0106", "C"); UNICODE_CHARS.put("\u0107", "c"); UNICODE_CHARS.put("\u0108", "C"); UNICODE_CHARS.put("\u0109", "c"); UNICODE_CHARS.put("\u010A", "C"); UNICODE_CHARS.put("\u010B", "c"); UNICODE_CHARS.put("\u010C", "C"); UNICODE_CHARS.put("\u010D", "c"); UNICODE_CHARS.put("\u010E", "D"); UNICODE_CHARS.put("\u010F", "d"); UNICODE_CHARS.put("\u0110", "D"); UNICODE_CHARS.put("\u0111", "d"); UNICODE_CHARS.put("\u0112", "E"); UNICODE_CHARS.put("\u0113", "e"); UNICODE_CHARS.put("\u0114", "E"); UNICODE_CHARS.put("\u0115", "e"); UNICODE_CHARS.put("\u0116", "E"); UNICODE_CHARS.put("\u0117", "e"); UNICODE_CHARS.put("\u0118", "E"); UNICODE_CHARS.put("\u0119", "e"); UNICODE_CHARS.put("\u011A", "E"); UNICODE_CHARS.put("\u011B", "e"); UNICODE_CHARS.put("\u011C", "G"); UNICODE_CHARS.put("\u011D", "g"); UNICODE_CHARS.put("\u011E", "G"); UNICODE_CHARS.put("\u011F", "g"); UNICODE_CHARS.put("\u0120", "G"); UNICODE_CHARS.put("\u0121", "g"); UNICODE_CHARS.put("\u0122", "G"); UNICODE_CHARS.put("\u0123", "g"); UNICODE_CHARS.put("\u0124", "H"); UNICODE_CHARS.put("\u0125", "h"); UNICODE_CHARS.put("\u0127", "h"); UNICODE_CHARS.put("\u0128", "I"); UNICODE_CHARS.put("\u0129", "i"); UNICODE_CHARS.put("\u012A", "I"); UNICODE_CHARS.put("\u012B", "i"); UNICODE_CHARS.put("\u012C", "I"); UNICODE_CHARS.put("\u012D", "i"); //UNICODE_CHARS.put("\u0100", ""); RTFCHARS.put("`a", "\\'e0"); RTFCHARS.put("`e", "\\'e8"); RTFCHARS.put("`i", "\\'ec"); RTFCHARS.put("`o", "\\'f2"); RTFCHARS.put("`u", "\\'f9"); RTFCHARS.put("?a", "\\'e1"); RTFCHARS.put("?e", "\\'e9"); RTFCHARS.put("?i", "\\'ed"); RTFCHARS.put("?o", "\\'f3"); RTFCHARS.put("?u", "\\'fa"); RTFCHARS.put("^a", "\\'e2"); RTFCHARS.put("^e", "\\'ea"); RTFCHARS.put("^i", "\\'ee"); RTFCHARS.put("^o", "\\'f4"); RTFCHARS.put("^u", "\\'fa"); RTFCHARS.put("\"a", "\\'e4"); RTFCHARS.put("\"e", "\\'eb"); RTFCHARS.put("\"i", "\\'ef"); RTFCHARS.put("\"o", "\\'f6"); RTFCHARS.put("\"u", "\\'fc"); RTFCHARS.put("~n", "\\'f1"); RTFCHARS.put("`A", "\\'c0"); RTFCHARS.put("`E", "\\'c8"); RTFCHARS.put("`I", "\\'cc"); RTFCHARS.put("`O", "\\'d2"); RTFCHARS.put("`U", "\\'d9"); RTFCHARS.put("?A", "\\'c1"); RTFCHARS.put("?E", "\\'c9"); RTFCHARS.put("?I", "\\'cd"); RTFCHARS.put("?O", "\\'d3"); RTFCHARS.put("?U", "\\'da"); RTFCHARS.put("^A", "\\'c2"); RTFCHARS.put("^E", "\\'ca"); RTFCHARS.put("^I", "\\'ce"); RTFCHARS.put("^O", "\\'d4"); RTFCHARS.put("^U", "\\'db"); RTFCHARS.put("\"A", "\\'c4"); RTFCHARS.put("\"E", "\\'cb"); RTFCHARS.put("\"I", "\\'cf"); RTFCHARS.put("\"O", "\\'d6"); RTFCHARS.put("\"U", "\\'dc"); //XML_CHARS.put("\\u00E1", "&#x00E1;"); } public static void initializeJournalNames() { journalAbbrev = new JournalAbbreviations();//"/resource/journalList.txt"); // Read external lists, if any (in reverse order, so the upper lists override the lower): String[] lists = prefs.getStringArray("externalJournalLists"); if ((lists != null) && (lists.length > 0)) { for (int i=lists.length-1; i>=0; i--) { try { journalAbbrev.readJournalList(new File(lists[i])); } catch (FileNotFoundException e) { // The file couldn't be found... should we tell anyone? Globals.logger(e.getMessage()); } } } // Read personal list, if set up: if (prefs.get("personalJournalList") != null) { try { journalAbbrev.readJournalList(new File(prefs.get("personalJournalList"))); } catch (FileNotFoundException e) { Globals.logger("Personal journal list file '"+prefs.get("personalJournalList")+ "' not found."); } } } }
false
true
private static String getNewFile(JFrame owner, JabRefPreferences prefs, File directory, String extension, String description, OpenFileFilter off, int dialogType, boolean updateWorkingDirectory, boolean dirOnly) { if (ON_MAC) { return getNewFileForMac(owner, prefs, directory, extension, dialogType, updateWorkingDirectory, dirOnly, off); } JFileChooser fc = null; try { fc = new JabRefFileChooser(directory); } catch (InternalError errl) { // This try/catch clause was added because a user reported an // InternalError getting thrown on WinNT, presumably because of a // bug in JGoodies Windows PLAF. This clause can be removed if the // bug is fixed, but for now we just resort to the native file // dialog, using the same method as is always used on Mac: return getNewFileForMac(owner, prefs, directory, extension, dialogType, updateWorkingDirectory, dirOnly, off); } if (dirOnly) { fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); } fc.addChoosableFileFilter(off); fc.setDialogType(dialogType); int dialogResult = JFileChooser.CANCEL_OPTION ; if (dialogType == JFileChooser.OPEN_DIALOG) { dialogResult = fc.showOpenDialog(null); } else if (dialogType == JFileChooser.SAVE_DIALOG){ dialogResult = fc.showSaveDialog(null); } else { dialogResult = fc.showDialog(null, description); } // the getSelectedFile method returns a valid fileselection // (if something is selected) indepentently from dialog return status if (dialogResult != JFileChooser.APPROVE_OPTION) return null ; // okay button File selectedFile = fc.getSelectedFile(); if (selectedFile == null) { // cancel return null; } // If this is a save dialog, and the user has not chosen "All files" as filter // we enforce the given extension. But only if extension is not null. if ((extension != null) && (dialogType == JFileChooser.SAVE_DIALOG) && (fc.getFileFilter() == off) && !off.accept(selectedFile)) { // add the first extension if there are multiple extensions selectedFile = new File(selectedFile.getPath() + extension.split("[, ]+",0)[0]); } if (updateWorkingDirectory) { prefs.put("workingDirectory", selectedFile.getPath()); } return selectedFile.getAbsolutePath(); }
private static String getNewFile(JFrame owner, JabRefPreferences prefs, File directory, String extension, String description, OpenFileFilter off, int dialogType, boolean updateWorkingDirectory, boolean dirOnly) { if (ON_MAC) { return getNewFileForMac(owner, prefs, directory, extension, dialogType, updateWorkingDirectory, dirOnly, off); } JFileChooser fc = null; try { fc = new JabRefFileChooser(directory); } catch (InternalError errl) { // This try/catch clause was added because a user reported an // InternalError getting thrown on WinNT, presumably because of a // bug in JGoodies Windows PLAF. This clause can be removed if the // bug is fixed, but for now we just resort to the native file // dialog, using the same method as is always used on Mac: return getNewFileForMac(owner, prefs, directory, extension, dialogType, updateWorkingDirectory, dirOnly, off); } if (dirOnly) { fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); } fc.addChoosableFileFilter(off); fc.setDialogType(dialogType); int dialogResult = JFileChooser.CANCEL_OPTION ; if (dialogType == JFileChooser.OPEN_DIALOG) { dialogResult = fc.showOpenDialog(owner); } else if (dialogType == JFileChooser.SAVE_DIALOG){ dialogResult = fc.showSaveDialog(owner); } else { dialogResult = fc.showDialog(owner, description); } // the getSelectedFile method returns a valid fileselection // (if something is selected) indepentently from dialog return status if (dialogResult != JFileChooser.APPROVE_OPTION) return null ; // okay button File selectedFile = fc.getSelectedFile(); if (selectedFile == null) { // cancel return null; } // If this is a save dialog, and the user has not chosen "All files" as filter // we enforce the given extension. But only if extension is not null. if ((extension != null) && (dialogType == JFileChooser.SAVE_DIALOG) && (fc.getFileFilter() == off) && !off.accept(selectedFile)) { // add the first extension if there are multiple extensions selectedFile = new File(selectedFile.getPath() + extension.split("[, ]+",0)[0]); } if (updateWorkingDirectory) { prefs.put("workingDirectory", selectedFile.getPath()); } return selectedFile.getAbsolutePath(); }
diff --git a/main/src/cgeo/geocaching/cgCache.java b/main/src/cgeo/geocaching/cgCache.java index d6e38018a..75c58cb03 100644 --- a/main/src/cgeo/geocaching/cgCache.java +++ b/main/src/cgeo/geocaching/cgCache.java @@ -1,1339 +1,1340 @@ package cgeo.geocaching; import cgeo.geocaching.cgData.StorageLocation; import cgeo.geocaching.activity.IAbstractActivity; import cgeo.geocaching.connector.ConnectorFactory; import cgeo.geocaching.connector.GCConnector; import cgeo.geocaching.connector.IConnector; import cgeo.geocaching.enumerations.CacheSize; import cgeo.geocaching.enumerations.CacheType; import cgeo.geocaching.enumerations.LoadFlags.RemoveFlag; import cgeo.geocaching.enumerations.LogType; import cgeo.geocaching.enumerations.WaypointType; import cgeo.geocaching.geopoint.Geopoint; import cgeo.geocaching.geopoint.GeopointFormatter; import cgeo.geocaching.geopoint.GeopointParser; import cgeo.geocaching.utils.CancellableHandler; import cgeo.geocaching.utils.CryptUtils; import cgeo.geocaching.utils.LogTemplateProvider; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import android.app.Activity; import android.content.Intent; import android.content.res.Resources; import android.net.Uri; import android.os.Handler; import android.text.Spannable; import android.util.Log; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Internal c:geo representation of a "cache" */ public class cgCache implements ICache { private long updated = 0; private long detailedUpdate = 0; private long visitedDate = 0; private int listId = StoredList.TEMPORARY_LIST_ID; private boolean detailed = false; private String geocode = ""; private String cacheId = ""; private String guid = ""; private CacheType cacheType = CacheType.UNKNOWN; private String name = ""; private Spannable nameSp = null; private String owner = ""; private String ownerReal = ""; private Date hidden = null; private String hint = ""; private CacheSize size = CacheSize.UNKNOWN; private float difficulty = 0; private float terrain = 0; private Float direction = null; private Float distance = null; private String latlon = ""; private String location = ""; private Geopoint coords = null; private boolean reliableLatLon = false; private Double elevation = null; private String personalNote = null; private String shortdesc = ""; private String description = null; private boolean disabled = false; private boolean archived = false; private boolean premiumMembersOnly = false; private boolean found = false; private boolean favorite = false; private boolean own = false; private int favoritePoints = 0; private float rating = 0; // valid ratings are larger than zero private int votes = 0; private float myVote = 0; // valid ratings are larger than zero private int inventoryItems = 0; private boolean onWatchlist = false; private List<String> attributes = null; private List<cgWaypoint> waypoints = null; private ArrayList<cgImage> spoilers = null; private List<cgLog> logs = null; private List<cgTrackable> inventory = null; private Map<LogType, Integer> logCounts = new HashMap<LogType, Integer>(); private boolean logOffline = false; private boolean userModifiedCoords = false; // temporary values private boolean statusChecked = false; private boolean statusCheckedView = false; private String directionImg = ""; private String nameForSorting; private final EnumSet<StorageLocation> storageLocation = EnumSet.of(StorageLocation.HEAP); private boolean finalDefined = false; private static final Pattern NUMBER_PATTERN = Pattern.compile("\\d+"); private Handler changeNotificationHandler = null; public void setChangeNotificationHandler(Handler newNotificationHandler) { changeNotificationHandler = newNotificationHandler; } /** * Sends a change notification to interested parties */ private void notifyChange() { if (changeNotificationHandler != null) changeNotificationHandler.sendEmptyMessage(0); } /** * Gather missing information from another cache object. * * @param other * the other version, or null if non-existent * @return true if this cache is "equal" to the other version */ public boolean gatherMissingFrom(final cgCache other) { if (other == null) { return false; } updated = System.currentTimeMillis(); if (!detailed && other.detailed) { detailed = true; detailedUpdate = other.detailedUpdate; coords = other.coords; premiumMembersOnly = other.premiumMembersOnly; reliableLatLon = other.reliableLatLon; archived = other.archived; favorite = other.favorite; onWatchlist = other.onWatchlist; logOffline = other.logOffline; finalDefined = other.finalDefined; } /* * No gathering for boolean members * - found * - own * - disabled * - favorite * - onWatchlist * - logOffline */ if (visitedDate == 0) { visitedDate = other.getVisitedDate(); } if (listId == StoredList.TEMPORARY_LIST_ID) { listId = other.listId; } if (StringUtils.isBlank(geocode)) { geocode = other.getGeocode(); } if (StringUtils.isBlank(cacheId)) { cacheId = other.cacheId; } if (StringUtils.isBlank(guid)) { guid = other.getGuid(); } if (null == cacheType || CacheType.UNKNOWN == cacheType) { cacheType = other.getType(); } if (StringUtils.isBlank(name)) { name = other.getName(); } if (StringUtils.isBlank(nameSp)) { nameSp = other.nameSp; } if (StringUtils.isBlank(owner)) { owner = other.getOwner(); } if (StringUtils.isBlank(ownerReal)) { ownerReal = other.getOwnerReal(); } if (hidden == null) { hidden = other.hidden; } if (StringUtils.isBlank(hint)) { hint = other.hint; } if (size == null || CacheSize.UNKNOWN == size) { size = other.size; } if (difficulty == 0) { difficulty = other.getDifficulty(); } if (terrain == 0) { terrain = other.getTerrain(); } if (direction == null) { direction = other.direction; } if (distance == null) { distance = other.getDistance(); } if (StringUtils.isBlank(latlon)) { latlon = other.latlon; } if (StringUtils.isBlank(location)) { location = other.location; } if (coords == null) { coords = other.getCoords(); } if (elevation == null) { elevation = other.elevation; } if (personalNote == null) { // don't use StringUtils.isBlank here. Otherwise we cannot recognize a note which was deleted on GC personalNote = other.personalNote; } if (StringUtils.isBlank(shortdesc)) { shortdesc = other.getShortdesc(); } if (StringUtils.isBlank(description)) { description = other.description; } if (favoritePoints == 0) { favoritePoints = other.getFavoritePoints(); } if (rating == 0) { rating = other.getRating(); } if (votes == 0) { votes = other.votes; } if (myVote == 0) { myVote = other.getMyVote(); } if (attributes == null) { attributes = other.attributes; } if (waypoints == null) { waypoints = other.waypoints; } else { cgWaypoint.mergeWayPoints(waypoints, other.getWaypoints(), waypoints == null || waypoints.isEmpty()); } if (spoilers == null) { spoilers = other.spoilers; } if (inventory == null) { // If inventoryItems is 0, it can mean both // "don't know" or "0 items". Since we cannot distinguish // them here, only populate inventoryItems from // old data when we have to do it for inventory. inventory = other.inventory; inventoryItems = other.inventoryItems; } if (CollectionUtils.isEmpty(logs)) { // keep last known logs if none logs = other.logs; } if (logCounts.size() == 0) { logCounts = other.logCounts; } if (userModifiedCoords == false) { userModifiedCoords = other.userModifiedCoords; } if (reliableLatLon == false) { reliableLatLon = other.reliableLatLon; } boolean isEqual = isEqualTo(other); - if (!isEqual) + if (!isEqual) { notifyChange(); + } return isEqual; } /** * Compare two caches quickly. For map and list fields only the references are compared ! * * @param other * @return true if both caches have the same content */ public boolean isEqualTo(cgCache other) { if (other == null) { return false; } if ( // updated // detailedUpdate // visitedDate detailed == other.detailed && geocode.equalsIgnoreCase(other.geocode) && name.equalsIgnoreCase(other.name) && cacheType == other.cacheType && size == other.size && found == other.found && own == other.own && premiumMembersOnly == other.premiumMembersOnly && difficulty == other.difficulty && terrain == other.terrain && (coords != null ? coords.isEqualTo(other.coords) : coords == other.coords) && reliableLatLon == other.reliableLatLon && disabled == other.disabled && archived == other.archived && listId == other.listId && owner.equalsIgnoreCase(other.owner) && ownerReal.equalsIgnoreCase(other.ownerReal) && (description != null ? description.equalsIgnoreCase(other.description) : description == other.description) && (personalNote != null ? personalNote.equalsIgnoreCase(other.personalNote) : personalNote == other.personalNote) && shortdesc.equalsIgnoreCase(other.shortdesc) && latlon.equalsIgnoreCase(other.latlon) && location.equalsIgnoreCase(other.location) && favorite == other.favorite && favoritePoints == other.favoritePoints && onWatchlist == other.onWatchlist && (hidden != null ? hidden.compareTo(other.hidden) == 0 : hidden == other.hidden) && guid.equalsIgnoreCase(other.guid) && hint.equalsIgnoreCase(other.hint) && cacheId.equalsIgnoreCase(other.cacheId) && direction == other.direction && distance == other.distance && elevation == other.elevation && nameSp == other.nameSp && rating == other.rating && votes == other.votes && myVote == other.myVote && inventoryItems == other.inventoryItems && attributes == other.attributes && waypoints == other.waypoints && spoilers == other.spoilers && logs == other.logs && inventory == other.inventory && logCounts == other.logCounts && logOffline == other.logOffline && finalDefined == other.finalDefined) { return true; } return false; } public boolean hasTrackables() { return inventoryItems > 0; } public boolean canBeAddedToCalendar() { // is event type? if (!isEventCache()) { return false; } // has event date set? if (hidden == null) { return false; } // is not in the past? final Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); if (hidden.compareTo(cal.getTime()) < 0) { return false; } return true; } /** * checks if a page contains the guid of a cache * * @param cache * the cache to look for * @param page * the page to search in * * @return true: page contains guid of cache, false: otherwise */ boolean isGuidContainedInPage(final String page) { if (StringUtils.isBlank(page)) { return false; } // check if the guid of the cache is anywhere in the page if (StringUtils.isBlank(guid)) { return false; } Pattern patternOk = Pattern.compile(guid, Pattern.CASE_INSENSITIVE); Matcher matcherOk = patternOk.matcher(page); if (matcherOk.find()) { Log.i(Settings.tag, "cgCache.isGuidContainedInPage: guid '" + guid + "' found"); return true; } else { Log.i(Settings.tag, "cgCache.isGuidContainedInPage: guid '" + guid + "' not found"); return false; } } public boolean isEventCache() { return CacheType.EVENT == cacheType || CacheType.MEGA_EVENT == cacheType || CacheType.CITO == cacheType || CacheType.LOSTANDFOUND == cacheType; } public boolean logVisit(IAbstractActivity fromActivity) { if (StringUtils.isBlank(cacheId)) { fromActivity.showToast(((Activity) fromActivity).getResources().getString(R.string.err_cannot_log_visit)); return true; } Intent logVisitIntent = new Intent((Activity) fromActivity, VisitCacheActivity.class); logVisitIntent.putExtra(VisitCacheActivity.EXTRAS_ID, cacheId); logVisitIntent.putExtra(VisitCacheActivity.EXTRAS_GEOCODE, geocode.toUpperCase()); logVisitIntent.putExtra(VisitCacheActivity.EXTRAS_FOUND, found); ((Activity) fromActivity).startActivity(logVisitIntent); return true; } public boolean logOffline(final IAbstractActivity fromActivity, final LogType logType) { String log = ""; if (StringUtils.isNotBlank(Settings.getSignature()) && Settings.isAutoInsertSignature()) { log = LogTemplateProvider.applyTemplates(Settings.getSignature(), true); } logOffline(fromActivity, log, Calendar.getInstance(), logType); return true; } void logOffline(final IAbstractActivity fromActivity, final String log, Calendar date, final LogType logType) { if (logType == LogType.LOG_UNKNOWN) { return; } cgeoapplication app = (cgeoapplication) ((Activity) fromActivity).getApplication(); final boolean status = app.saveLogOffline(geocode, date.getTime(), logType, log); notifyChange(); Resources res = ((Activity) fromActivity).getResources(); if (status) { fromActivity.showToast(res.getString(R.string.info_log_saved)); app.saveVisitDate(geocode); } else { fromActivity.showToast(res.getString(R.string.err_log_post_failed)); } } public List<LogType> getPossibleLogTypes() { boolean isOwner = owner != null && owner.equalsIgnoreCase(Settings.getUsername()); List<LogType> logTypes = new ArrayList<LogType>(); if (isEventCache()) { logTypes.add(LogType.LOG_WILL_ATTEND); logTypes.add(LogType.LOG_NOTE); logTypes.add(LogType.LOG_ATTENDED); logTypes.add(LogType.LOG_NEEDS_ARCHIVE); if (isOwner) { logTypes.add(LogType.LOG_ANNOUNCEMENT); } } else if (CacheType.WEBCAM == cacheType) { logTypes.add(LogType.LOG_WEBCAM_PHOTO_TAKEN); logTypes.add(LogType.LOG_DIDNT_FIND_IT); logTypes.add(LogType.LOG_NOTE); logTypes.add(LogType.LOG_NEEDS_ARCHIVE); logTypes.add(LogType.LOG_NEEDS_MAINTENANCE); } else { logTypes.add(LogType.LOG_FOUND_IT); logTypes.add(LogType.LOG_DIDNT_FIND_IT); logTypes.add(LogType.LOG_NOTE); logTypes.add(LogType.LOG_NEEDS_ARCHIVE); logTypes.add(LogType.LOG_NEEDS_MAINTENANCE); } if (isOwner) { logTypes.add(LogType.LOG_OWNER_MAINTENANCE); logTypes.add(LogType.LOG_TEMP_DISABLE_LISTING); logTypes.add(LogType.LOG_ENABLE_LISTING); logTypes.add(LogType.LOG_ARCHIVE); logTypes.remove(LogType.LOG_UPDATE_COORDINATES); } return logTypes; } public void openInBrowser(Activity fromActivity) { fromActivity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(getCacheUrl()))); } private String getCacheUrl() { return getConnector().getCacheUrl(this); } private IConnector getConnector() { return ConnectorFactory.getConnector(this); } public boolean canOpenInBrowser() { return getCacheUrl() != null; } public boolean supportsRefresh() { return getConnector().supportsRefreshCache(this); } public boolean supportsWatchList() { return getConnector().supportsWatchList(); } public boolean supportsLogging() { return getConnector().supportsLogging(); } @Override public float getDifficulty() { return difficulty; } @Override public String getGeocode() { return geocode; } @Override public String getLatitude() { return coords != null ? coords.format(GeopointFormatter.Format.LAT_DECMINUTE) : null; } @Override public String getLongitude() { return coords != null ? coords.format(GeopointFormatter.Format.LON_DECMINUTE) : null; } @Override public String getOwner() { return owner; } @Override public CacheSize getSize() { if (size == null) { return CacheSize.UNKNOWN; } return size; } @Override public float getTerrain() { return terrain; } @Override public boolean isArchived() { return archived; } @Override public boolean isDisabled() { return disabled; } @Override public boolean isPremiumMembersOnly() { return premiumMembersOnly; } public void setPremiumMembersOnly(boolean members) { this.premiumMembersOnly = members; } @Override public boolean isOwn() { return own; } @Override public String getOwnerReal() { return ownerReal; } @Override public String getHint() { return hint; } @Override public String getDescription() { if (description == null) { description = StringUtils.defaultString(cgeoapplication.getInstance().getCacheDescription(geocode)); } return description; } @Override public String getShortDescription() { return shortdesc; } @Override public String getName() { return name; } @Override public String getCacheId() { if (StringUtils.isBlank(cacheId) && getConnector().equals(GCConnector.getInstance())) { return CryptUtils.convertToGcBase31(geocode); } return cacheId; } @Override public String getGuid() { return guid; } @Override public String getLocation() { return location; } @Override public String getPersonalNote() { // non premium members have no personal notes, premium members have an empty string by default. // map both to null, so other code doesn't need to differentiate if (StringUtils.isBlank(personalNote)) { return null; } return personalNote; } public boolean supportsUserActions() { return getConnector().supportsUserActions(); } public boolean supportsCachesAround() { return getConnector().supportsCachesAround(); } public void shareCache(Activity fromActivity, Resources res) { if (geocode == null) { return; } StringBuilder subject = new StringBuilder("Geocache "); subject.append(geocode.toUpperCase()); if (StringUtils.isNotBlank(name)) { subject.append(" - ").append(name); } final Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_SUBJECT, subject.toString()); intent.putExtra(Intent.EXTRA_TEXT, getUrl()); fromActivity.startActivity(Intent.createChooser(intent, res.getText(R.string.action_bar_share_title))); } public String getUrl() { return getConnector().getCacheUrl(this); } public boolean supportsGCVote() { return StringUtils.startsWithIgnoreCase(geocode, "GC"); } public void setDescription(final String description) { this.description = description; } @Override public boolean isFound() { return found; } @Override public boolean isFavorite() { return favorite; } public void setFavorite(boolean favourite) { this.favorite = favourite; } @Override public boolean isWatchlist() { return onWatchlist; } @Override public Date getHiddenDate() { return hidden; } @Override public List<String> getAttributes() { if (attributes == null) { return Collections.emptyList(); } return Collections.unmodifiableList(attributes); } @Override public List<cgTrackable> getInventory() { return inventory; } @Override public ArrayList<cgImage> getSpoilers() { return spoilers; } @Override public Map<LogType, Integer> getLogCounts() { return logCounts; } @Override public int getFavoritePoints() { return favoritePoints; } @Override public String getNameForSorting() { if (null == nameForSorting) { final Matcher matcher = NUMBER_PATTERN.matcher(name); if (matcher.find()) { nameForSorting = name.replace(matcher.group(), StringUtils.leftPad(matcher.group(), 6, '0')); } else { nameForSorting = name; } } return nameForSorting; } public boolean isVirtual() { return CacheType.VIRTUAL == cacheType || CacheType.WEBCAM == cacheType || CacheType.EARTH == cacheType; } public boolean showSize() { return !((isEventCache() || isVirtual()) && size == CacheSize.NOT_CHOSEN); } public long getUpdated() { return updated; } public void setUpdated(long updated) { this.updated = updated; } public long getDetailedUpdate() { return detailedUpdate; } public void setDetailedUpdate(long detailedUpdate) { this.detailedUpdate = detailedUpdate; } public long getVisitedDate() { return visitedDate; } public void setVisitedDate(long visitedDate) { this.visitedDate = visitedDate; } public int getListId() { return listId; } public void setListId(int listId) { this.listId = listId; } public boolean isDetailed() { return detailed; } public void setDetailed(boolean detailed) { this.detailed = detailed; } public Spannable getNameSp() { return nameSp; } public void setNameSp(Spannable nameSp) { this.nameSp = nameSp; } public void setHidden(final Date hidden) { if (hidden == null) { this.hidden = null; } else { this.hidden = new Date(hidden.getTime()); // avoid storing the external reference in this object } } public Float getDirection() { return direction; } public void setDirection(Float direction) { this.direction = direction; } public Float getDistance() { return distance; } public void setDistance(Float distance) { this.distance = distance; } public String getLatlon() { return latlon; } public void setLatlon(String latlon) { this.latlon = latlon; } public Geopoint getCoords() { return coords; } public void setCoords(Geopoint coords) { this.coords = coords; } /** * @return true if the coords are from the cache details page and the user has been logged in */ public boolean isReliableLatLon() { return getConnector().isReliableLatLon(reliableLatLon); } public void setReliableLatLon(boolean reliableLatLon) { this.reliableLatLon = reliableLatLon; } public Double getElevation() { return elevation; } public void setElevation(Double elevation) { this.elevation = elevation; } public String getShortdesc() { return shortdesc; } public void setShortdesc(String shortdesc) { this.shortdesc = shortdesc; } public void setFavoritePoints(int favoriteCnt) { this.favoritePoints = favoriteCnt; } public float getRating() { return rating; } public void setRating(float rating) { this.rating = rating; } public int getVotes() { return votes; } public void setVotes(int votes) { this.votes = votes; } public float getMyVote() { return myVote; } public void setMyVote(float myVote) { this.myVote = myVote; } public int getInventoryItems() { return inventoryItems; } public void setInventoryItems(int inventoryItems) { this.inventoryItems = inventoryItems; } public boolean isOnWatchlist() { return onWatchlist; } public void setOnWatchlist(boolean onWatchlist) { this.onWatchlist = onWatchlist; } /** * return an immutable list of waypoints. * * @return always non <code>null</code> */ public List<cgWaypoint> getWaypoints() { if (waypoints == null) { return Collections.emptyList(); } return Collections.unmodifiableList(waypoints); } public void setWaypoints(List<cgWaypoint> waypoints) { this.waypoints = waypoints; finalDefined = false; if (waypoints != null) { for (cgWaypoint waypoint : waypoints) { waypoint.setGeocode(geocode); if (isFinalWithCoords(waypoint)) { finalDefined = true; } } } } public List<cgLog> getLogs() { return getLogs(true); } /** * @param allLogs * true for all logs, false for friend logs only * @return the logs with all entries or just the entries of the friends, never <code>null</code> */ public List<cgLog> getLogs(boolean allLogs) { if (logs == null) { return Collections.emptyList(); } if (allLogs) { return logs; } ArrayList<cgLog> friendLogs = new ArrayList<cgLog>(); for (cgLog log : logs) { if (log.friend) { friendLogs.add(log); } } return friendLogs; } /** * @param logs * the log entries */ public void setLogs(List<cgLog> logs) { this.logs = logs; } public boolean isLogOffline() { return logOffline; } public void setLogOffline(boolean logOffline) { this.logOffline = logOffline; } public boolean isStatusChecked() { return statusChecked; } public void setStatusChecked(boolean statusChecked) { this.statusChecked = statusChecked; } public boolean isStatusCheckedView() { return statusCheckedView; } public void setStatusCheckedView(boolean statusCheckedView) { this.statusCheckedView = statusCheckedView; } public String getDirectionImg() { return directionImg; } public void setDirectionImg(String directionImg) { this.directionImg = directionImg; } public void setGeocode(String geocode) { this.geocode = geocode; } public void setCacheId(String cacheId) { this.cacheId = cacheId; } public void setGuid(String guid) { this.guid = guid; } public void setName(String name) { this.name = name; } public void setOwner(String owner) { this.owner = owner; } public void setOwnerReal(String ownerReal) { this.ownerReal = ownerReal; } public void setHint(String hint) { this.hint = hint; } public void setSize(CacheSize size) { if (size == null) { this.size = CacheSize.UNKNOWN; } else { this.size = size; } } public void setDifficulty(float difficulty) { this.difficulty = difficulty; } public void setTerrain(float terrain) { this.terrain = terrain; } public void setLocation(String location) { this.location = location; } public void setPersonalNote(String personalNote) { this.personalNote = personalNote; } public void setDisabled(boolean disabled) { this.disabled = disabled; } public void setArchived(boolean archived) { this.archived = archived; } public void setFound(boolean found) { this.found = found; } public void setOwn(boolean own) { this.own = own; } public void setAttributes(List<String> attributes) { this.attributes = attributes; } public void setSpoilers(ArrayList<cgImage> spoilers) { this.spoilers = spoilers; } public void setInventory(List<cgTrackable> inventory) { this.inventory = inventory; } public void setLogCounts(Map<LogType, Integer> logCounts) { this.logCounts = logCounts; } /* * (non-Javadoc) * * @see cgeo.geocaching.IBasicCache#getType() * * @returns Never null */ @Override public CacheType getType() { return cacheType; } public void setType(CacheType cacheType) { if (cacheType == null || CacheType.ALL == cacheType) { throw new IllegalArgumentException("Illegal cache type"); } this.cacheType = cacheType; } public boolean hasDifficulty() { return difficulty > 0f; } public boolean hasTerrain() { return terrain > 0f; } /** * @return the storageLocation */ public EnumSet<StorageLocation> getStorageLocation() { return storageLocation; } /** * @param storageLocation * the storageLocation to set */ public void addStorageLocation(StorageLocation sl) { this.storageLocation.add(sl); } public void addWaypoint(final cgWaypoint waypoint) { if (null == waypoints) { waypoints = new ArrayList<cgWaypoint>(); } waypoints.add(waypoint); waypoint.setGeocode(geocode); if (isFinalWithCoords(waypoint)) { finalDefined = true; } } public boolean hasWaypoints() { return CollectionUtils.isNotEmpty(waypoints); } public boolean hasFinalDefined() { return finalDefined; } // Only for loading public void setFinalDefined(boolean finalDefined) { this.finalDefined = finalDefined; } /** * Checks whether a given waypoint is a final and has coordinates * * @param waypoint * Waypoint to check * @return True - waypoint is final and has coordinates, False - otherwise */ private static boolean isFinalWithCoords(cgWaypoint waypoint) { if (null != waypoint.getWaypointType() && WaypointType.FINAL == waypoint.getWaypointType()) { if (null != waypoint.getCoords()) { return true; } } return false; } public boolean hasUserModifiedCoords() { return userModifiedCoords; } public void setUserModifiedCoords(boolean coordsChanged) { this.userModifiedCoords = coordsChanged; } /** * @param index * @return <code>true</code>, if the waypoint was duplicated */ public boolean duplicateWaypoint(int index) { if (!isValidWaypointIndex(index)) { return false; } final cgWaypoint copy = new cgWaypoint(waypoints.get(index)); copy.setUserDefined(); copy.setName(cgeoapplication.getInstance().getString(R.string.waypoint_copy_of) + " " + copy.getName()); waypoints.add(index + 1, copy); return cgeoapplication.getInstance().saveOwnWaypoint(-1, geocode, copy); } private boolean isValidWaypointIndex(int index) { if (!hasWaypoints()) { return false; } if (index < 0 || index >= waypoints.size()) { return false; } return true; } /** * delete a user defined waypoint * * @param index * @return <code>true</code>, if the waypoint was deleted */ public boolean deleteWaypoint(int index) { if (!isValidWaypointIndex(index)) { return false; } final cgWaypoint waypoint = waypoints.get(index); if (waypoint.isUserDefined()) { waypoints.remove(index); cgeoapplication.getInstance().deleteWaypoint(waypoint.getId()); cgeoapplication.getInstance().removeCache(geocode, EnumSet.of(RemoveFlag.REMOVE_CACHE)); // Check status if Final is defined if (isFinalWithCoords(waypoint)) { finalDefined = false; for (cgWaypoint wp : waypoints) { if (isFinalWithCoords(wp)) { finalDefined = true; } } } return true; } return false; } /** * @param index * @return waypoint or <code>null</code> */ public cgWaypoint getWaypoint(int index) { if (!isValidWaypointIndex(index)) { return null; } return waypoints.get(index); } /** * @param index * @return waypoint or <code>null</code> */ public cgWaypoint getWaypointById(int id) { for (cgWaypoint waypoint : waypoints) { if (waypoint.getId() == id) { return waypoint; } } return null; } public void parseWaypointsFromNote() { try { if (StringUtils.isBlank(getPersonalNote())) { return; } final Pattern coordPattern = Pattern.compile("\\b[nNsS]{1}\\s*\\d"); // begin of coordinates int count = 1; String note = getPersonalNote(); Matcher matcher = coordPattern.matcher(note); while (matcher.find()) { try { final Geopoint point = GeopointParser.parse(note.substring(matcher.start())); // coords must have non zero latitude and longitude and at least one part shall have fractional degrees if (point != null && point.getLatitudeE6() != 0 && point.getLongitudeE6() != 0 && ((point.getLatitudeE6() % 1000) != 0 || (point.getLongitudeE6() % 1000) != 0)) { final String name = cgeoapplication.getInstance().getString(R.string.cache_personal_note) + " " + count; final cgWaypoint waypoint = new cgWaypoint(name, WaypointType.WAYPOINT, false); waypoint.setCoords(point); addWaypoint(waypoint); count++; } } catch (GeopointParser.ParseException e) { // ignore } note = note.substring(matcher.start() + 1); matcher = coordPattern.matcher(note); } } catch (Exception e) { Log.e(Settings.tag, "cgCache.parseWaypointsFromNote: " + e.toString()); } } public void addAttribute(final String attribute) { if (attributes == null) { attributes = new ArrayList<String>(); } attributes.add(attribute); } public boolean hasAttributes() { return attributes != null && attributes.size() > 0; } public void prependLog(final cgLog log) { if (logs == null) { logs = new ArrayList<cgLog>(); } logs.add(0, log); } public void appendLog(final cgLog log) { if (logs == null) { logs = new ArrayList<cgLog>(); } logs.add(log); } /* * For working in the debugger * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return this.geocode + " " + this.name; } @Override public int hashCode() { return geocode.hashCode() * name.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } // just compare the geocode even if that is not what "equals" normaly does return geocode != null ? geocode.compareTo(((cgCache) obj).geocode) == 0 : false; } public void store(Activity activity, CancellableHandler handler) { final int listId = Math.max(getListId(), StoredList.STANDARD_LIST_ID); cgBase.storeCache(activity, this, null, listId, handler); } }
false
true
public boolean gatherMissingFrom(final cgCache other) { if (other == null) { return false; } updated = System.currentTimeMillis(); if (!detailed && other.detailed) { detailed = true; detailedUpdate = other.detailedUpdate; coords = other.coords; premiumMembersOnly = other.premiumMembersOnly; reliableLatLon = other.reliableLatLon; archived = other.archived; favorite = other.favorite; onWatchlist = other.onWatchlist; logOffline = other.logOffline; finalDefined = other.finalDefined; } /* * No gathering for boolean members * - found * - own * - disabled * - favorite * - onWatchlist * - logOffline */ if (visitedDate == 0) { visitedDate = other.getVisitedDate(); } if (listId == StoredList.TEMPORARY_LIST_ID) { listId = other.listId; } if (StringUtils.isBlank(geocode)) { geocode = other.getGeocode(); } if (StringUtils.isBlank(cacheId)) { cacheId = other.cacheId; } if (StringUtils.isBlank(guid)) { guid = other.getGuid(); } if (null == cacheType || CacheType.UNKNOWN == cacheType) { cacheType = other.getType(); } if (StringUtils.isBlank(name)) { name = other.getName(); } if (StringUtils.isBlank(nameSp)) { nameSp = other.nameSp; } if (StringUtils.isBlank(owner)) { owner = other.getOwner(); } if (StringUtils.isBlank(ownerReal)) { ownerReal = other.getOwnerReal(); } if (hidden == null) { hidden = other.hidden; } if (StringUtils.isBlank(hint)) { hint = other.hint; } if (size == null || CacheSize.UNKNOWN == size) { size = other.size; } if (difficulty == 0) { difficulty = other.getDifficulty(); } if (terrain == 0) { terrain = other.getTerrain(); } if (direction == null) { direction = other.direction; } if (distance == null) { distance = other.getDistance(); } if (StringUtils.isBlank(latlon)) { latlon = other.latlon; } if (StringUtils.isBlank(location)) { location = other.location; } if (coords == null) { coords = other.getCoords(); } if (elevation == null) { elevation = other.elevation; } if (personalNote == null) { // don't use StringUtils.isBlank here. Otherwise we cannot recognize a note which was deleted on GC personalNote = other.personalNote; } if (StringUtils.isBlank(shortdesc)) { shortdesc = other.getShortdesc(); } if (StringUtils.isBlank(description)) { description = other.description; } if (favoritePoints == 0) { favoritePoints = other.getFavoritePoints(); } if (rating == 0) { rating = other.getRating(); } if (votes == 0) { votes = other.votes; } if (myVote == 0) { myVote = other.getMyVote(); } if (attributes == null) { attributes = other.attributes; } if (waypoints == null) { waypoints = other.waypoints; } else { cgWaypoint.mergeWayPoints(waypoints, other.getWaypoints(), waypoints == null || waypoints.isEmpty()); } if (spoilers == null) { spoilers = other.spoilers; } if (inventory == null) { // If inventoryItems is 0, it can mean both // "don't know" or "0 items". Since we cannot distinguish // them here, only populate inventoryItems from // old data when we have to do it for inventory. inventory = other.inventory; inventoryItems = other.inventoryItems; } if (CollectionUtils.isEmpty(logs)) { // keep last known logs if none logs = other.logs; } if (logCounts.size() == 0) { logCounts = other.logCounts; } if (userModifiedCoords == false) { userModifiedCoords = other.userModifiedCoords; } if (reliableLatLon == false) { reliableLatLon = other.reliableLatLon; } boolean isEqual = isEqualTo(other); if (!isEqual) notifyChange(); return isEqual; }
public boolean gatherMissingFrom(final cgCache other) { if (other == null) { return false; } updated = System.currentTimeMillis(); if (!detailed && other.detailed) { detailed = true; detailedUpdate = other.detailedUpdate; coords = other.coords; premiumMembersOnly = other.premiumMembersOnly; reliableLatLon = other.reliableLatLon; archived = other.archived; favorite = other.favorite; onWatchlist = other.onWatchlist; logOffline = other.logOffline; finalDefined = other.finalDefined; } /* * No gathering for boolean members * - found * - own * - disabled * - favorite * - onWatchlist * - logOffline */ if (visitedDate == 0) { visitedDate = other.getVisitedDate(); } if (listId == StoredList.TEMPORARY_LIST_ID) { listId = other.listId; } if (StringUtils.isBlank(geocode)) { geocode = other.getGeocode(); } if (StringUtils.isBlank(cacheId)) { cacheId = other.cacheId; } if (StringUtils.isBlank(guid)) { guid = other.getGuid(); } if (null == cacheType || CacheType.UNKNOWN == cacheType) { cacheType = other.getType(); } if (StringUtils.isBlank(name)) { name = other.getName(); } if (StringUtils.isBlank(nameSp)) { nameSp = other.nameSp; } if (StringUtils.isBlank(owner)) { owner = other.getOwner(); } if (StringUtils.isBlank(ownerReal)) { ownerReal = other.getOwnerReal(); } if (hidden == null) { hidden = other.hidden; } if (StringUtils.isBlank(hint)) { hint = other.hint; } if (size == null || CacheSize.UNKNOWN == size) { size = other.size; } if (difficulty == 0) { difficulty = other.getDifficulty(); } if (terrain == 0) { terrain = other.getTerrain(); } if (direction == null) { direction = other.direction; } if (distance == null) { distance = other.getDistance(); } if (StringUtils.isBlank(latlon)) { latlon = other.latlon; } if (StringUtils.isBlank(location)) { location = other.location; } if (coords == null) { coords = other.getCoords(); } if (elevation == null) { elevation = other.elevation; } if (personalNote == null) { // don't use StringUtils.isBlank here. Otherwise we cannot recognize a note which was deleted on GC personalNote = other.personalNote; } if (StringUtils.isBlank(shortdesc)) { shortdesc = other.getShortdesc(); } if (StringUtils.isBlank(description)) { description = other.description; } if (favoritePoints == 0) { favoritePoints = other.getFavoritePoints(); } if (rating == 0) { rating = other.getRating(); } if (votes == 0) { votes = other.votes; } if (myVote == 0) { myVote = other.getMyVote(); } if (attributes == null) { attributes = other.attributes; } if (waypoints == null) { waypoints = other.waypoints; } else { cgWaypoint.mergeWayPoints(waypoints, other.getWaypoints(), waypoints == null || waypoints.isEmpty()); } if (spoilers == null) { spoilers = other.spoilers; } if (inventory == null) { // If inventoryItems is 0, it can mean both // "don't know" or "0 items". Since we cannot distinguish // them here, only populate inventoryItems from // old data when we have to do it for inventory. inventory = other.inventory; inventoryItems = other.inventoryItems; } if (CollectionUtils.isEmpty(logs)) { // keep last known logs if none logs = other.logs; } if (logCounts.size() == 0) { logCounts = other.logCounts; } if (userModifiedCoords == false) { userModifiedCoords = other.userModifiedCoords; } if (reliableLatLon == false) { reliableLatLon = other.reliableLatLon; } boolean isEqual = isEqualTo(other); if (!isEqual) { notifyChange(); } return isEqual; }
diff --git a/src/main/java/mobisocial/cocoon/server/AMQPush.java b/src/main/java/mobisocial/cocoon/server/AMQPush.java index 60a7de2..7bade30 100644 --- a/src/main/java/mobisocial/cocoon/server/AMQPush.java +++ b/src/main/java/mobisocial/cocoon/server/AMQPush.java @@ -1,484 +1,485 @@ package mobisocial.cocoon.server; import java.io.IOException; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.TimeUnit; import javapns.Push; import javapns.devices.Device; import javapns.devices.exceptions.InvalidDeviceTokenFormatException; import javapns.notification.PushNotificationPayload; import javapns.notification.PushedNotification; import javapns.notification.PushedNotifications; import javapns.notification.ResponsePacket; import javapns.notification.transmission.PushQueue; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import mobisocial.cocoon.model.Listener; import mobisocial.cocoon.util.Database; import mobisocial.crypto.CorruptIdentity; import mobisocial.crypto.IBHashedIdentity; import mobisocial.musubi.protocol.Message; import net.vz.mongodb.jackson.JacksonDBCollection; import org.apache.commons.codec.binary.Base64; import org.codehaus.jackson.map.ObjectMapper; import org.json.JSONException; import com.mongodb.DBCollection; import com.rabbitmq.client.AMQP.BasicProperties; import com.rabbitmq.client.AMQP.Queue.DeclareOk; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.DefaultConsumer; import com.rabbitmq.client.Envelope; import com.sun.jersey.spi.resource.Singleton; import de.undercouch.bson4jackson.BsonFactory; import de.undercouch.bson4jackson.BsonParser.Feature; @Singleton @Path("/api/0/") public class AMQPush { static class BadgeData { public int amqp; public int local; public Date last; } ObjectMapper mMapper = new ObjectMapper(new BsonFactory().enable(Feature.HONOR_DOCUMENT_LENGTH)); HashMap<String, BadgeData> mCounts = new HashMap<String, BadgeData>(); HashMap<String, String> mQueues = new HashMap<String, String>(); HashMap<String, String> mConsumers = new HashMap<String, String>(); HashMap<String, HashSet<String>> mNotifiers = new HashMap<String, HashSet<String>>(); HashMap<String, Listener> mListeners = new HashMap<String, Listener>(); LinkedBlockingDeque<Runnable> mJobs = new LinkedBlockingDeque<Runnable>(); String encodeAMQPname(String prefix, byte[] key) { //TODO: WTF doesnt this put the = at the end automatically? int excess = (key.length * 8 % 6); String pad = ""; int equals = (6 - excess) / 2; for( int i = 0; i < equals; ++i) pad += "="; return prefix + Base64.encodeBase64URLSafeString(key) + pad + "\n"; } byte[] decodeAMQPname(String prefix, String name) { if(!name.startsWith(prefix)) return null; //URL-safe? automatically, no param necessary? return Base64.decodeBase64(name.substring(prefix.length())); } AMQPushThread mPushThread = new AMQPushThread(); class AMQPushThread extends Thread{ Channel mIncomingChannel; private DefaultConsumer mConsumer; @Override public void run() { for(;;) { try { amqp(); } catch (Throwable e) { throw new RuntimeException(e); } try { Thread.sleep(30000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } void amqp() throws Throwable { final PushQueue dev_queue = Push.queue("push.p12", "pusubi", false, 1); dev_queue.start(); final PushQueue prod_queue = Push.queue("pushprod.p12", "pusubi", true, 1); prod_queue.start(); for(;;) { ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setHost("bumblebee.musubi.us"); connectionFactory.setConnectionTimeout(30 * 1000); connectionFactory.setRequestedHeartbeat(30); Connection connection = connectionFactory.newConnection(); mIncomingChannel = connection.createChannel(); mConsumer = new DefaultConsumer(mIncomingChannel) { @Override public void handleDelivery(final String consumerTag, final Envelope envelope, final BasicProperties properties, final byte[] body) throws IOException { HashSet<String> threadDevices = new HashSet<String>(); synchronized (mNotifiers) { String identity = mConsumers.get(consumerTag); if(identity == null) return; HashSet<String> devices = mNotifiers.get(identity); if(devices == null) return; threadDevices.addAll(devices); } Message m = null; try { m = mMapper.readValue(body, Message.class); } catch (IOException e) { new RuntimeException("Failed to parse BSON of outer message", e).printStackTrace(); return; } //don't notify for blind (profile/delete/like msgs) if(m.l) return; String sender_exchange; try { sender_exchange = encodeAMQPname("ibeidentity-", new IBHashedIdentity(m.s.i).at(0).identity_); } catch (CorruptIdentity e) { e.printStackTrace(); return; } Date now = new Date(); for(String device : threadDevices) { try { int new_value = 0; int amqp = 0; int local = 0; Date last; boolean production = false; Listener l; synchronized (mNotifiers) { l = mListeners.get(device); } production = l.production != null && l.production != false; //no self notify if(l.identityExchanges.contains(sender_exchange)) continue; synchronized (mCounts) { BadgeData bd = mCounts.get(device); if(bd == null) { bd = new BadgeData(); mCounts.put(device, bd); } bd.amqp++; amqp = bd.amqp; local = bd.local; new_value = bd.amqp + bd.local; last = bd.last; if(bd.last == null) { bd.last = now; } else if(bd.last != null && now.getTime() - bd.last.getTime() > 3 * 60 * 1000) { - bd.last = null; + bd.last = now; + last = null; } } PushNotificationPayload payload = PushNotificationPayload.complex(); try { if(last == null) { payload.addAlert("New message"); payload.addSound("default"); } payload.addBadge(new_value); payload.addCustomDictionary("local", local); payload.addCustomDictionary("amqp", amqp); } catch (JSONException e) { //logic error, not runtime e.printStackTrace(); System.exit(1); } if(!production) dev_queue.add(payload, device); else prod_queue.add(payload, device); } catch (InvalidDeviceTokenFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }; System.out.println("doing registrations"); Set<String> notifiers = new HashSet<String>(); synchronized(mNotifiers) { notifiers.addAll(mNotifiers.keySet()); } for(String identity : notifiers) { DeclareOk x = mIncomingChannel.queueDeclare(); System.out.println("listening " + identity); mIncomingChannel.exchangeDeclare(identity, "fanout", true); mIncomingChannel.queueBind(x.getQueue(), identity, ""); String consumerTag = mIncomingChannel.basicConsume(x.getQueue(), true, mConsumer); synchronized(mNotifiers) { mQueues.put(identity, x.getQueue()); mConsumers.put(consumerTag, identity); } } System.out.println("done registrations"); //TODO: don't do all the feedback stuff on one thread long last = new Date().getTime(); for(;;) { Runnable job = mJobs.poll(60, TimeUnit.SECONDS); long current = new Date().getTime(); if(current - last > 60 * 1000) { PushedNotifications ps = dev_queue.getPushedNotifications(); for(PushedNotification p : ps) { if(p.isSuccessful()) continue; String invalidToken = p.getDevice().getToken(); System.err.println("unregistering invalid token " + invalidToken); unregister(invalidToken); /* Find out more about what the problem was */ Exception theProblem = p.getException(); theProblem.printStackTrace(); /* If the problem was an error-response packet returned by Apple, get it */ ResponsePacket theErrorResponse = p.getResponse(); if (theErrorResponse != null) { System.out.println(theErrorResponse.getMessage()); } } last = new Date().getTime(); List<Device> inactiveDevices = Push.feedback("push.p12", "pusubi", false); for(Device d : inactiveDevices) { String invalidToken = d.getToken(); System.err.println("unregistering feedback failed token token " + invalidToken); unregister(invalidToken); } } if(job == null) continue; job.run(); } } } }; public AMQPush() { loadAll(); mPushThread.start(); } private void loadAll() { DBCollection rawCol = Database.dbInstance().getCollection(Listener.COLLECTION); JacksonDBCollection<Listener, String> col = JacksonDBCollection.wrap(rawCol, Listener.class, String.class); for(Listener l : col.find()) { mListeners.put(l.deviceToken, l); //add all registrations for(String ident : l.identityExchanges) { HashSet<String> listeners = mNotifiers.get(ident); if(listeners == null) { listeners = new HashSet<String>(); mNotifiers.put(ident, listeners); } listeners.add(l.deviceToken); } } } @POST @Path("register") @Produces("application/json") public String register(Listener l) throws IOException { boolean needs_update = true; synchronized(mNotifiers) { System.out.println( new Date() + "Registering device: " + l.deviceToken + " for identities " + Arrays.toString(l.identityExchanges.toArray())); //clear pending message count on registration (e.g. amqp connected to drain messages) //TODO: this is not really right if the client fails to download all messages //before disconnecting synchronized (mCounts) { BadgeData bd = mCounts.get(l.deviceToken); if(bd == null) { bd = new BadgeData(); mCounts.put(l.deviceToken, bd); } if(l.localUnread != null) bd.local = l.localUnread; } Listener existing = mListeners.get(l.deviceToken); if(existing != null && existing.production == l.production && existing.identityExchanges.size() == l.identityExchanges.size()) { needs_update = false; Iterator<String> a = existing.identityExchanges.iterator(); Iterator<String> b = l.identityExchanges.iterator(); while(a.hasNext()) { String aa = a.next(); String bb = b.next(); if(!aa.equals(bb)) { needs_update = true; break; } } } if(!needs_update) return "ok"; mListeners.put(l.deviceToken, l); //TODO: set intersection to not wasteful tear up and down if(existing != null) { //remove all old registrations for(String ident : existing.identityExchanges) { HashSet<String> listeners = mNotifiers.get(ident); assert(listeners != null); listeners.remove(l.deviceToken); if(listeners.size() == 0) { amqpUnregister(ident); mNotifiers.remove(ident); } } } //add all new registrations for(String ident : l.identityExchanges) { HashSet<String> listeners = mNotifiers.get(ident); if(listeners == null) { listeners = new HashSet<String>(); mNotifiers.put(ident, listeners); amqpRegister(ident); } listeners.add(l.deviceToken); } } DBCollection rawCol = Database.dbInstance().getCollection(Listener.COLLECTION); JacksonDBCollection<Listener, String> col = JacksonDBCollection.wrap(rawCol, Listener.class, String.class); Listener match = new Listener(); match.deviceToken = l.deviceToken; col.update(match, l, true, false); return "ok"; } @POST @Path("clearunread") @Produces("application/json") public String clearUnread(String deviceToken) throws IOException { System.out.println( new Date() + "Clear unread " + deviceToken); synchronized(mCounts) { BadgeData bd = mCounts.get(deviceToken); if(bd == null) { bd = new BadgeData(); mCounts.put(deviceToken, bd); } bd.amqp = 0; } return "ok"; } public static class ResetUnread { public String deviceToken; public int count; public Boolean background; } @POST @Path("resetunread") @Produces("application/json") public String resetUnread(ResetUnread ru) throws IOException { System.out.println( new Date() + "reset unread " + ru.deviceToken + " to " + ru.count); synchronized (mCounts) { BadgeData bd = mCounts.get(ru.deviceToken); if(bd == null) { bd = new BadgeData(); mCounts.put(ru.deviceToken, bd); } if(ru.background == null || !ru.background) { bd.last = null; } bd.local = ru.count; } return "ok"; } void amqpRegister(final String identity) { mJobs.add(new Runnable() { @Override public void run() { try { DeclareOk x = mPushThread.mIncomingChannel.queueDeclare(); System.out.println("listening " + identity); mPushThread.mIncomingChannel.exchangeDeclare(identity, "fanout", true); mPushThread.mIncomingChannel.queueBind(x.getQueue(), identity, ""); String consumerTag = mPushThread.mIncomingChannel.basicConsume(x.getQueue(), true, mPushThread.mConsumer); synchronized(mNotifiers) { mQueues.put(identity, x.getQueue()); mConsumers.put(consumerTag, identity); } } catch (Throwable t) { throw new RuntimeException("failed to register", t); } } }); } void amqpUnregister(final String identity) { mJobs.add(new Runnable() { @Override public void run() { String queue = null; synchronized(mNotifiers) { queue = mQueues.get(identity); //probably an error if(queue == null) return; mQueues.remove(identity); //TODO: update consumers } System.out.println("stop listening " + identity); try { mPushThread.mIncomingChannel.queueUnbind(queue, identity, ""); } catch (Throwable t) { throw new RuntimeException("removing queue dynamically", t); } } }); } @POST @Path("unregister") @Produces("application/json") public String unregister(String deviceToken) throws IOException { synchronized(mNotifiers) { Listener existing = mListeners.get(deviceToken); if(existing == null) return "ok"; mListeners.remove(deviceToken); synchronized (mCounts) { mListeners.remove(deviceToken); } //remove all old registrations for(String ident : existing.identityExchanges) { HashSet<String> listeners = mNotifiers.get(ident); assert(listeners != null); listeners.remove(deviceToken); if(listeners.size() == 0) { amqpUnregister(ident); mNotifiers.remove(ident); } } } DBCollection rawCol = Database.dbInstance().getCollection(Listener.COLLECTION); JacksonDBCollection<Listener, String> col = JacksonDBCollection.wrap(rawCol, Listener.class, String.class); Listener match = new Listener(); match.deviceToken = deviceToken; col.remove(match); return "ok"; } }
true
true
void amqp() throws Throwable { final PushQueue dev_queue = Push.queue("push.p12", "pusubi", false, 1); dev_queue.start(); final PushQueue prod_queue = Push.queue("pushprod.p12", "pusubi", true, 1); prod_queue.start(); for(;;) { ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setHost("bumblebee.musubi.us"); connectionFactory.setConnectionTimeout(30 * 1000); connectionFactory.setRequestedHeartbeat(30); Connection connection = connectionFactory.newConnection(); mIncomingChannel = connection.createChannel(); mConsumer = new DefaultConsumer(mIncomingChannel) { @Override public void handleDelivery(final String consumerTag, final Envelope envelope, final BasicProperties properties, final byte[] body) throws IOException { HashSet<String> threadDevices = new HashSet<String>(); synchronized (mNotifiers) { String identity = mConsumers.get(consumerTag); if(identity == null) return; HashSet<String> devices = mNotifiers.get(identity); if(devices == null) return; threadDevices.addAll(devices); } Message m = null; try { m = mMapper.readValue(body, Message.class); } catch (IOException e) { new RuntimeException("Failed to parse BSON of outer message", e).printStackTrace(); return; } //don't notify for blind (profile/delete/like msgs) if(m.l) return; String sender_exchange; try { sender_exchange = encodeAMQPname("ibeidentity-", new IBHashedIdentity(m.s.i).at(0).identity_); } catch (CorruptIdentity e) { e.printStackTrace(); return; } Date now = new Date(); for(String device : threadDevices) { try { int new_value = 0; int amqp = 0; int local = 0; Date last; boolean production = false; Listener l; synchronized (mNotifiers) { l = mListeners.get(device); } production = l.production != null && l.production != false; //no self notify if(l.identityExchanges.contains(sender_exchange)) continue; synchronized (mCounts) { BadgeData bd = mCounts.get(device); if(bd == null) { bd = new BadgeData(); mCounts.put(device, bd); } bd.amqp++; amqp = bd.amqp; local = bd.local; new_value = bd.amqp + bd.local; last = bd.last; if(bd.last == null) { bd.last = now; } else if(bd.last != null && now.getTime() - bd.last.getTime() > 3 * 60 * 1000) { bd.last = null; } } PushNotificationPayload payload = PushNotificationPayload.complex(); try { if(last == null) { payload.addAlert("New message"); payload.addSound("default"); } payload.addBadge(new_value); payload.addCustomDictionary("local", local); payload.addCustomDictionary("amqp", amqp); } catch (JSONException e) { //logic error, not runtime e.printStackTrace(); System.exit(1); } if(!production) dev_queue.add(payload, device); else prod_queue.add(payload, device); } catch (InvalidDeviceTokenFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }; System.out.println("doing registrations"); Set<String> notifiers = new HashSet<String>(); synchronized(mNotifiers) { notifiers.addAll(mNotifiers.keySet()); } for(String identity : notifiers) { DeclareOk x = mIncomingChannel.queueDeclare(); System.out.println("listening " + identity); mIncomingChannel.exchangeDeclare(identity, "fanout", true); mIncomingChannel.queueBind(x.getQueue(), identity, ""); String consumerTag = mIncomingChannel.basicConsume(x.getQueue(), true, mConsumer); synchronized(mNotifiers) { mQueues.put(identity, x.getQueue()); mConsumers.put(consumerTag, identity); } } System.out.println("done registrations"); //TODO: don't do all the feedback stuff on one thread long last = new Date().getTime(); for(;;) { Runnable job = mJobs.poll(60, TimeUnit.SECONDS); long current = new Date().getTime(); if(current - last > 60 * 1000) { PushedNotifications ps = dev_queue.getPushedNotifications(); for(PushedNotification p : ps) { if(p.isSuccessful()) continue; String invalidToken = p.getDevice().getToken(); System.err.println("unregistering invalid token " + invalidToken); unregister(invalidToken); /* Find out more about what the problem was */ Exception theProblem = p.getException(); theProblem.printStackTrace(); /* If the problem was an error-response packet returned by Apple, get it */ ResponsePacket theErrorResponse = p.getResponse(); if (theErrorResponse != null) { System.out.println(theErrorResponse.getMessage()); } } last = new Date().getTime(); List<Device> inactiveDevices = Push.feedback("push.p12", "pusubi", false); for(Device d : inactiveDevices) { String invalidToken = d.getToken(); System.err.println("unregistering feedback failed token token " + invalidToken); unregister(invalidToken); } } if(job == null) continue; job.run(); } } }
void amqp() throws Throwable { final PushQueue dev_queue = Push.queue("push.p12", "pusubi", false, 1); dev_queue.start(); final PushQueue prod_queue = Push.queue("pushprod.p12", "pusubi", true, 1); prod_queue.start(); for(;;) { ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setHost("bumblebee.musubi.us"); connectionFactory.setConnectionTimeout(30 * 1000); connectionFactory.setRequestedHeartbeat(30); Connection connection = connectionFactory.newConnection(); mIncomingChannel = connection.createChannel(); mConsumer = new DefaultConsumer(mIncomingChannel) { @Override public void handleDelivery(final String consumerTag, final Envelope envelope, final BasicProperties properties, final byte[] body) throws IOException { HashSet<String> threadDevices = new HashSet<String>(); synchronized (mNotifiers) { String identity = mConsumers.get(consumerTag); if(identity == null) return; HashSet<String> devices = mNotifiers.get(identity); if(devices == null) return; threadDevices.addAll(devices); } Message m = null; try { m = mMapper.readValue(body, Message.class); } catch (IOException e) { new RuntimeException("Failed to parse BSON of outer message", e).printStackTrace(); return; } //don't notify for blind (profile/delete/like msgs) if(m.l) return; String sender_exchange; try { sender_exchange = encodeAMQPname("ibeidentity-", new IBHashedIdentity(m.s.i).at(0).identity_); } catch (CorruptIdentity e) { e.printStackTrace(); return; } Date now = new Date(); for(String device : threadDevices) { try { int new_value = 0; int amqp = 0; int local = 0; Date last; boolean production = false; Listener l; synchronized (mNotifiers) { l = mListeners.get(device); } production = l.production != null && l.production != false; //no self notify if(l.identityExchanges.contains(sender_exchange)) continue; synchronized (mCounts) { BadgeData bd = mCounts.get(device); if(bd == null) { bd = new BadgeData(); mCounts.put(device, bd); } bd.amqp++; amqp = bd.amqp; local = bd.local; new_value = bd.amqp + bd.local; last = bd.last; if(bd.last == null) { bd.last = now; } else if(bd.last != null && now.getTime() - bd.last.getTime() > 3 * 60 * 1000) { bd.last = now; last = null; } } PushNotificationPayload payload = PushNotificationPayload.complex(); try { if(last == null) { payload.addAlert("New message"); payload.addSound("default"); } payload.addBadge(new_value); payload.addCustomDictionary("local", local); payload.addCustomDictionary("amqp", amqp); } catch (JSONException e) { //logic error, not runtime e.printStackTrace(); System.exit(1); } if(!production) dev_queue.add(payload, device); else prod_queue.add(payload, device); } catch (InvalidDeviceTokenFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }; System.out.println("doing registrations"); Set<String> notifiers = new HashSet<String>(); synchronized(mNotifiers) { notifiers.addAll(mNotifiers.keySet()); } for(String identity : notifiers) { DeclareOk x = mIncomingChannel.queueDeclare(); System.out.println("listening " + identity); mIncomingChannel.exchangeDeclare(identity, "fanout", true); mIncomingChannel.queueBind(x.getQueue(), identity, ""); String consumerTag = mIncomingChannel.basicConsume(x.getQueue(), true, mConsumer); synchronized(mNotifiers) { mQueues.put(identity, x.getQueue()); mConsumers.put(consumerTag, identity); } } System.out.println("done registrations"); //TODO: don't do all the feedback stuff on one thread long last = new Date().getTime(); for(;;) { Runnable job = mJobs.poll(60, TimeUnit.SECONDS); long current = new Date().getTime(); if(current - last > 60 * 1000) { PushedNotifications ps = dev_queue.getPushedNotifications(); for(PushedNotification p : ps) { if(p.isSuccessful()) continue; String invalidToken = p.getDevice().getToken(); System.err.println("unregistering invalid token " + invalidToken); unregister(invalidToken); /* Find out more about what the problem was */ Exception theProblem = p.getException(); theProblem.printStackTrace(); /* If the problem was an error-response packet returned by Apple, get it */ ResponsePacket theErrorResponse = p.getResponse(); if (theErrorResponse != null) { System.out.println(theErrorResponse.getMessage()); } } last = new Date().getTime(); List<Device> inactiveDevices = Push.feedback("push.p12", "pusubi", false); for(Device d : inactiveDevices) { String invalidToken = d.getToken(); System.err.println("unregistering feedback failed token token " + invalidToken); unregister(invalidToken); } } if(job == null) continue; job.run(); } } }
diff --git a/src/visibilityGraph/Graph.java b/src/visibilityGraph/Graph.java index d695adf..dd89b7b 100644 --- a/src/visibilityGraph/Graph.java +++ b/src/visibilityGraph/Graph.java @@ -1,103 +1,103 @@ package visibilityGraph; import geometry.GeometryException; import geometry.Point; import geometry.Vector; import java.util.ArrayList; import java.util.Collections; import octree.OctNode; import octree.OctNodeException; import octree.Octree; public class Graph { private ArrayList<GraphNode> nodes = new ArrayList<GraphNode>(); private ArrayList<GraphEdge> edges = new ArrayList<GraphEdge>(); private int numOfDims; private Octree surface; public Graph(ArrayList<Point> nds, int dims, Octree tree) throws GraphException,GraphNodeException{ if(dims < 1 ) throw new InvalidGraphNumberOfDimensionsException(); if(nds.isEmpty()) throw new EmptyNodeSetException(); numOfDims = dims; for(Point p : nds){ nodes.add(new GraphNode(dims, p)); } surface = tree; } public int getNumOfDims(){ return this.numOfDims; } public GraphNode getNodeAtPosition(int x){ return nodes.get(x); } public GraphEdge getEdgeAtPosition(int x){ return edges.get(x); } private void recurseGetOctreeLeafs(Point origin, Vector ray, ArrayList<Point> visible, OctNode root) throws GeometryException, OctNodeException{ if(root.getBoundingBox().intersectWithRay(ray, origin, Boolean.FALSE)){ if(root.getNodeType() == OctNode.OCTNODE_LEAF){ visible.add(root.getPoint()); } if(root.getNodeType() == OctNode.OCTNODE_INTERMEDIATE){ ArrayList<OctNode> children = root.getChildren(); for(OctNode n : children) recurseGetOctreeLeafs(origin,ray,visible,n); } } } private ArrayList<Point> getOctreeLeafs(Point origin,Vector ray) throws GeometryException, OctNodeException{ ArrayList<Point> visible = new ArrayList<Point>(); recurseGetOctreeLeafs(origin,ray,visible,this.surface.getRoot()); return visible; } public void iterateToCreateEdges() throws GeometryException, OctNodeException, GraphException, GraphEdgeException{ for(int i=0;i<nodes.size();i++){ for(int j=i+1;j<nodes.size();j++){ //create ray and call octree code here Vector ray = new Vector(nodes.get(i).getPoint(),nodes.get(j).getPoint()); ArrayList<Point> visibleList = getOctreeLeafs(nodes.get(i).getPoint(), ray); ArrayList<Float> projections = new ArrayList<Float>(); for(Point p : visibleList){ Vector v = new Vector(p); projections.add(ray.getProjection(v)); } if(projections.isEmpty()) throw new ZeroProjectedClustersException(); Collections.sort(projections); boolean visible=false; int clusterCount = 1; float D = surface.getMinNodeLength(); float distance; for(int k=1;(k<projections.size() && clusterCount < 3);k++){ distance = projections.get(i) - projections.get(i-1); if(distance > (1.5f*D)) clusterCount++; } switch(clusterCount){ case 1: visible=true; break; case 2: //arkoudia here break; case 3: visible=false; break; default: - throw new GraphException("Default switch case on clusers"); + throw new GraphException("Default switch case on clusters"); } if(visible) edges.add(new GraphEdge(i, j, nodes.get(i).getPoint().minkowskiDistanceFrom(nodes.get(j).getPoint(), 2))); } } } }
true
true
public void iterateToCreateEdges() throws GeometryException, OctNodeException, GraphException, GraphEdgeException{ for(int i=0;i<nodes.size();i++){ for(int j=i+1;j<nodes.size();j++){ //create ray and call octree code here Vector ray = new Vector(nodes.get(i).getPoint(),nodes.get(j).getPoint()); ArrayList<Point> visibleList = getOctreeLeafs(nodes.get(i).getPoint(), ray); ArrayList<Float> projections = new ArrayList<Float>(); for(Point p : visibleList){ Vector v = new Vector(p); projections.add(ray.getProjection(v)); } if(projections.isEmpty()) throw new ZeroProjectedClustersException(); Collections.sort(projections); boolean visible=false; int clusterCount = 1; float D = surface.getMinNodeLength(); float distance; for(int k=1;(k<projections.size() && clusterCount < 3);k++){ distance = projections.get(i) - projections.get(i-1); if(distance > (1.5f*D)) clusterCount++; } switch(clusterCount){ case 1: visible=true; break; case 2: //arkoudia here break; case 3: visible=false; break; default: throw new GraphException("Default switch case on clusers"); } if(visible) edges.add(new GraphEdge(i, j, nodes.get(i).getPoint().minkowskiDistanceFrom(nodes.get(j).getPoint(), 2))); } } }
public void iterateToCreateEdges() throws GeometryException, OctNodeException, GraphException, GraphEdgeException{ for(int i=0;i<nodes.size();i++){ for(int j=i+1;j<nodes.size();j++){ //create ray and call octree code here Vector ray = new Vector(nodes.get(i).getPoint(),nodes.get(j).getPoint()); ArrayList<Point> visibleList = getOctreeLeafs(nodes.get(i).getPoint(), ray); ArrayList<Float> projections = new ArrayList<Float>(); for(Point p : visibleList){ Vector v = new Vector(p); projections.add(ray.getProjection(v)); } if(projections.isEmpty()) throw new ZeroProjectedClustersException(); Collections.sort(projections); boolean visible=false; int clusterCount = 1; float D = surface.getMinNodeLength(); float distance; for(int k=1;(k<projections.size() && clusterCount < 3);k++){ distance = projections.get(i) - projections.get(i-1); if(distance > (1.5f*D)) clusterCount++; } switch(clusterCount){ case 1: visible=true; break; case 2: //arkoudia here break; case 3: visible=false; break; default: throw new GraphException("Default switch case on clusters"); } if(visible) edges.add(new GraphEdge(i, j, nodes.get(i).getPoint().minkowskiDistanceFrom(nodes.get(j).getPoint(), 2))); } } }
diff --git a/workspace/Plugins/src/cz/zcu/kiv/kc/plugin/create/CreateFilePlugin.java b/workspace/Plugins/src/cz/zcu/kiv/kc/plugin/create/CreateFilePlugin.java index a7d5775..933240f 100644 --- a/workspace/Plugins/src/cz/zcu/kiv/kc/plugin/create/CreateFilePlugin.java +++ b/workspace/Plugins/src/cz/zcu/kiv/kc/plugin/create/CreateFilePlugin.java @@ -1,30 +1,30 @@ package cz.zcu.kiv.kc.plugin.create; import java.io.File; import java.io.IOException; import java.util.List; public class CreateFilePlugin implements ICreateFilePlugin { @Override public void executeAction(List<File> selectedFiles, String destinationPath, String sourcePath) { try { - new File(destinationPath + File.pathSeparator + System.nanoTime()).createNewFile(); + new File(destinationPath + File.separator + System.nanoTime()).createNewFile(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public String getId() { return "create"; } @Override public String getName() { return "Create"; } }
true
true
public void executeAction(List<File> selectedFiles, String destinationPath, String sourcePath) { try { new File(destinationPath + File.pathSeparator + System.nanoTime()).createNewFile(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public void executeAction(List<File> selectedFiles, String destinationPath, String sourcePath) { try { new File(destinationPath + File.separator + System.nanoTime()).createNewFile(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
diff --git a/src/ibis/satin/impl/SharedObjects.java b/src/ibis/satin/impl/SharedObjects.java index 3f57f6ad..0ecdf681 100644 --- a/src/ibis/satin/impl/SharedObjects.java +++ b/src/ibis/satin/impl/SharedObjects.java @@ -1,579 +1,579 @@ package ibis.satin.impl; import ibis.ipl.IbisIdentifier; import ibis.ipl.ReceivePort; import ibis.ipl.ReceivePortIdentifier; import ibis.ipl.StaticProperties; import ibis.ipl.WriteMessage; import ibis.satin.so.SharedObject; import ibis.util.messagecombining.MessageSplitter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Hashtable; import java.util.Map; import java.util.Vector; public abstract class SharedObjects extends TupleSpace implements Protocol { /*@todo: rethink the way objects are shipped, both at the beginning of the computation and in case of inconsistencies; instead of waiting for some time and only then shipping, start shipping immediately and if the object arrives in the meantime, cancel the request*/ HashMap sharedObjects = new HashMap(); private HashMap ports = new HashMap(); boolean gotObject = false; SharedObject object = null; ArrayList toConnect = new ArrayList(); Vector soInvocationsToSend = new Vector(); long soInvocationsToSendTimer = -1; int writtenInvocations = 0; Map soSendPorts = new Hashtable(); final static int WAIT_FOR_UPDATES_TIME = 5000; final static int WAIT_FOR_OBJECT_TIME = 8000; final static int LOOKUP_WAIT_TIME = 10000; public void broadcastSharedObject(SharedObject object) { WriteMessage w = null; long size = 0; if (SCALABLE) { doConnectSendPort(); } if (SO_TIMING) { handleSOTransferTimer.start(); } try { if (soInvocationsDelay > 0) { //do message combining w = soMessageCombiner.newMessage(); } else { w = soSendPort.newMessage(); } if (SO_TIMING) { soSerializationTimer.start(); } w.writeByte(SO_TRANSFER); w.writeObject(object); size = w.finish(); if (SO_TIMING) { soSerializationTimer.stop(); } if (soInvocationsDelay > 0) { soMessageCombiner.sendAccumulatedMessages(); } } catch (IOException e) { System.err.println("SATIN '" + ident.name() + "': unable to broadcast a shared object: " + e); } /*Iterator iter = soSendPorts.values().iterator(); while (iter.hasNext()) { try { if (soInvocationsDelay > 0) { MessageCombiner mc = (MessageCombiner) iter.next(); w = mc.newMessage(); if (soInvocationsDelayTimer == -1) { soInvocationsDelayTimer = System.currentTimeMillis(); } } else { SendPort send = (SendPort) iter.next(); w = send.newMessage(); } if (SO_TIMING) { soSerializationTimer.start(); } w.writeByte(SO_TRANSFER); w.writeObject(object); size = w.finish(); if (SO_TIMING) { soSerializationTimer.stop(); } } catch (IOException e) { System.err.println("SATIN '" + ident.name() + "': unable to send a shared object: " + e); } }*/ //stats soTransfers += soSendPort.connectedTo().length; //soTransfers += soSendPorts.size(); soTransfersBytes += size; if (SO_TIMING) { handleSOTransferTimer.stop(); } } /** Add an object to the object table*/ public void addObject(SharedObject object) { synchronized (this) { sharedObjects.put(object.objectId, object); } } void sendAccumulatedSOInvocations() { long currTime = System.currentTimeMillis(); long elapsed = currTime - soInvocationsDelayTimer; if (soInvocationsDelayTimer > 0 && (elapsed > soInvocationsDelay || soCurrTotalMessageSize > soMaxMessageSize)) { try { if (SO_TIMING) { broadcastSOInvocationsTimer.start(); } soMessageCombiner.sendAccumulatedMessages(); //WriteMessage w = soSendPort.newMessage(); //w.writeInt(soInvocationsToSend.size()); //while(true) { // if( soInvocationsToSend.size() == 0) { // break; // } // SOInvocationRecord soir = // (SOInvocationRecord) soInvocationsToSend.remove(0); // w.writeObject(soir); //} //long byteCount = w.finish(); //soInvocationsBytes += byteCount; } catch (IOException e) { System.err.println("SATIN '" + ident.name() + "': unable to broadcast shared object invocations " + e); } /*Iterator iter = soSendPorts.values().iterator(); while (iter.hasNext()) { try { MessageCombiner mc = (MessageCombiner) iter.next(); mc.sendAccumulatedMessages(); } catch (IOException e) { System.err.println("SATIN '" + ident.name() + "': unable to send shared object invocations " + e); } }*/ soRealMessageCount++; writtenInvocations = 0; soCurrTotalMessageSize = 0; soInvocationsDelayTimer = -1; // @@@ AARG, this line was outside the if, that can't be correct, right? Rob if (SO_TIMING) { broadcastSOInvocationsTimer.stop(); } } } /** Broadcast an so invocation*/ public void broadcastSOInvocation(SOInvocationRecord r) { long byteCount = 0; // int numToSend; WriteMessage w = null; if (SO_TIMING) { broadcastSOInvocationsTimer.start(); } if (SCALABLE) { doConnectSendPort(); } if (soSendPort.connectedTo().length > 0) { try { if (soInvocationsDelay > 0) { //do message combining w = soMessageCombiner.newMessage(); //soInvocationsToSend.add(r); if (soInvocationsDelayTimer == -1) { soInvocationsDelayTimer = System.currentTimeMillis(); } writtenInvocations++; } else { w = soSendPort.newMessage(); // w.writeInt(1); //w.writeObject(r); //byteCount = w.finish(); } w.writeByte(SO_INVOCATION); w.writeObject(r); byteCount = w.finish(); if (soInvocationsDelay > 0) { soCurrTotalMessageSize += byteCount; } } catch (IOException e) { System.err .println("SATIN '" + ident.name() + "': unable to broadcast a shared object invocation: " + e); } } /*Iterator iter = soSendPorts.values().iterator(); while (iter.hasNext()) { try { if (soInvocationsDelay > 0) { MessageCombiner mc = (MessageCombiner) iter.next(); w = mc.newMessage(); if (soInvocationsDelayTimer == -1) { soInvocationsDelayTimer = System.currentTimeMillis(); } } else { SendPort send = (SendPort) iter.next(); w = send.newMessage(); } w.writeByte(SO_INVOCATION); w.writeObject(r); byteCount = w.finish(); } catch (IOException e) { System.err.println("SATIN '" + ident.name() + "': unable to send a shared object invocation: " + e); } }*/ //stats soInvocations++; soInvocationsBytes += byteCount; + if (SO_TIMING) { + broadcastSOInvocationsTimer.stop(); + } // @@@ I added this code, shouldn't we try to send immediately if needed? // We might not reach a safe point for a considerable time if (soInvocationsDelay > 0) { sendAccumulatedSOInvocations(); } - if (SO_TIMING) { - broadcastSOInvocationsTimer.stop(); - } } /** Execute all the so invocations stored in the so invocations list */ void handleSOInvocations() { SharedObject so = null; SOInvocationRecord soir = null; String soid = null; gotSOInvocations = false; while (true) { if (SO_TIMING) { handleSOInvocationsTimer.start(); } // synchronized (this) { if (soInvocationList.size() == 0) { if (SO_TIMING) { handleSOInvocationsTimer.stop(); } return; } soir = (SOInvocationRecord) soInvocationList.remove(0); soid = soir.objectId; so = (SharedObject) sharedObjects.get(soid); if (so == null) { if (SO_TIMING) { handleSOInvocationsTimer.stop(); } return; } //invoke while holding a lock. //otherwise object transfer requests can be handled //in the middle of a method invocation soir.invoke(so); // } if (SO_TIMING) { handleSOInvocationsTimer.stop(); } } } /** Return a reference to a shared object */ public SharedObject getSOReference(String objectId) { synchronized (this) { SharedObject obj = (SharedObject) sharedObjects.get(objectId); if (obj == null) { System.err.println("OOPS, object not found in getSOReference"); } return obj; } } /** Check if the given shared object is in the table, if not, ship it from source */ public void setSOReference(String objectId, IbisIdentifier source) throws SOReferenceSourceCrashedException { SharedObject obj = null; synchronized (this) { obj = (SharedObject) sharedObjects.get(objectId); } if (obj == null) { if (!initialNode) { shipObject(objectId, source); } else { //just wait, object has been broadcast long startTime = System.currentTimeMillis(); while (System.currentTimeMillis() - startTime < WAIT_FOR_OBJECT_TIME) { handleDelayedMessages(); synchronized (this) { obj = (SharedObject) sharedObjects.get(objectId); } if (obj != null) { break; } } if (obj == null) { shipObject(objectId, source); } } } } /** Receive a shared object from another node (called by the MessageHandler */ public void receiveObject(SharedObject obj) { synchronized (this) { gotObject = true; object = obj; } } /** Add a shared object invocation record to the so invocation record list; the invocation will be executed later */ public void addSOInvocation(SOInvocationRecord soir) { synchronized (this) { soInvocationList.add(soir); gotSOInvocations = true; } } /** * Creates SO receive ports for new Satin instances. * Do this first, to make them available as soon as possible. */ public void createSoReceivePorts(IbisIdentifier[] joiners) { for (int i = 0; i < joiners.length; i++) { //create a receive port for this guy try { SOInvocationHandler soInvocationHandler = new SOInvocationHandler( Satin.this_satin); ReceivePort rec = soPortType.createReceivePort( "satin so receive port on " + ident.name() + " for " + joiners[i].name(), soInvocationHandler); if (soInvocationsDelay > 0) { StaticProperties s = new StaticProperties(); s.add("serialization", "ibis"); soInvocationHandler.setMessageSplitter(new MessageSplitter( s, rec)); } rec.enableConnections(); rec.enableUpcalls(); } catch (Exception e) { System.err.println("SATIN '" + ident.name() + "': unable to create so receive port"); e.printStackTrace(); } } } private synchronized void doConnectSendPort() { for (int i = 0; i < toConnect.size(); i++) { IbisIdentifier id = (IbisIdentifier) toConnect.get(i); ReceivePortIdentifier r = lookup_wait("satin so receive port on " + id.name() + " for " + ident.name(), LOOKUP_WAIT_TIME); //and connect if (r == null || !Satin.connect(soSendPort/*send*/, r, connectTimeout)) { System.err.println("SATN '" + ident.name() + "': unable to connect to so receive port "); } else { ports.put(id, r); } } toConnect.clear(); } /** Add a new connection to the soSendPort */ public void addSOConnection(IbisIdentifier id) { if (ASSERTS) { Satin.assertLocked(this); } if (SCALABLE) { toConnect.add(id); return; } //create a send port for this guy /*SendPort send = soPortType.createSendPort("satin so send port on " + ident.name() + " for " + id.name()); if (soInvocationsDelay > 0) { StaticProperties s = new StaticProperties(); s.add("serialization", "ibis"); MessageCombiner mc = new MessageCombiner(s, send); soSendPorts.put(id, mc); } else { soSendPorts.put(id, send); }*/ //lookup his receive port ReceivePortIdentifier r = lookup_wait("satin so receive port on " + id.name() + " for " + ident.name(), LOOKUP_WAIT_TIME); /* r = lookup_wait("satin so receive port on " + id.name(), LOOKUP_WAIT_TIME);*/ //and connect if (r == null || !Satin.connect(soSendPort/*send*/, r, connectTimeout)) { System.err.println("SATN '" + ident.name() + "': unable to connect to so receive port "); } else { ports.put(id, r); } } /** Remove a new connection to the soSendPort */ public void removeSOConnection(IbisIdentifier id) { if (ASSERTS) { Satin.assertLocked(this); } ReceivePortIdentifier r = (ReceivePortIdentifier) ports.remove(id); //and disconnect if (r != null) { Satin.disconnect(soSendPort, r); } } /** Execute the guard of the invocation record r, wait for updates, if necessary, ship objects if necessary */ void executeGuard(InvocationRecord r) throws SOReferenceSourceCrashedException { boolean satisfied; long startTime; satisfied = r.guard(); if (!satisfied) { if (soLogger.isInfoEnabled()) { soLogger.info("SATIN '" + ident.name() + "': " + "guard not satisfied, waiting for updates.."); } startTime = System.currentTimeMillis(); while (System.currentTimeMillis() - startTime < WAIT_FOR_UPDATES_TIME && !satisfied) { handleDelayedMessages(); satisfied = r.guard(); } if (!satisfied) { //try to ship the object from the owner of the job if (soLogger.isInfoEnabled()) { soLogger .info("SATIN '" + ident.name() + "': " + "guard not satisfied, trying to ship shared objects ..."); } Vector objRefs = r.getSOReferences(); if (ASSERTS && objRefs == null) { soLogger.fatal("SATIN '" + ident.name() + "': " + "oops, so references vector null!"); System.exit(1); // Failed assert } while (!objRefs.isEmpty()) { String ref = (String) objRefs.remove(0); shipObject(ref, r.owner); } if (ASSERTS) { if (soLogger.isInfoEnabled()) { soLogger.info("SATIN '" + ident.name() + "': " + "objects shipped, checking again.."); } if (!r.guard()) { soLogger.fatal("SATIN '" + ident.name() + "':" + " panic! inconsistent after shipping objects"); System.exit(1); // Failed assert } } } } } /** Ship a shared object from another node */ private void shipObject(String objectId, IbisIdentifier source) throws SOReferenceSourceCrashedException { //request the shared object from the source if (SO_TIMING) { soTransferTimer.start(); } try { //System.err.println("sending so request to " + source + ", objectId: " + objectId); currentVictim = source; Victim v = getVictimWait(source); WriteMessage w = v.newMessage(); w.writeByte(SO_REQUEST); w.writeString(objectId); w.finish(); } catch (IOException e) { //hm we've got a problem here //push the job somewhere else? soLogger.error("SATIN '" + ident.name() + "': could not " + "write shared-object request", e); if (SO_TIMING) { soTransferTimer.stop(); } throw new SOReferenceSourceCrashedException(); } //wait for the reply while (true) { // handleDelayedMessages(); synchronized (this) { if (gotObject) { gotObject = false; currentVictimCrashed = false; break; } if (currentVictimCrashed) { currentVictimCrashed = false; break; } } } if (SO_TIMING) { soTransferTimer.stop(); } if (object == null) { //the source has crashed, abort the job throw new SOReferenceSourceCrashedException(); } synchronized (this) { sharedObjects.put(object.objectId, object); } object = null; soLogger.info("SATIN '" + ident.name() + "': received shared object from " + source); handleDelayedMessages(); } }
false
true
public void broadcastSOInvocation(SOInvocationRecord r) { long byteCount = 0; // int numToSend; WriteMessage w = null; if (SO_TIMING) { broadcastSOInvocationsTimer.start(); } if (SCALABLE) { doConnectSendPort(); } if (soSendPort.connectedTo().length > 0) { try { if (soInvocationsDelay > 0) { //do message combining w = soMessageCombiner.newMessage(); //soInvocationsToSend.add(r); if (soInvocationsDelayTimer == -1) { soInvocationsDelayTimer = System.currentTimeMillis(); } writtenInvocations++; } else { w = soSendPort.newMessage(); // w.writeInt(1); //w.writeObject(r); //byteCount = w.finish(); } w.writeByte(SO_INVOCATION); w.writeObject(r); byteCount = w.finish(); if (soInvocationsDelay > 0) { soCurrTotalMessageSize += byteCount; } } catch (IOException e) { System.err .println("SATIN '" + ident.name() + "': unable to broadcast a shared object invocation: " + e); } } /*Iterator iter = soSendPorts.values().iterator(); while (iter.hasNext()) { try { if (soInvocationsDelay > 0) { MessageCombiner mc = (MessageCombiner) iter.next(); w = mc.newMessage(); if (soInvocationsDelayTimer == -1) { soInvocationsDelayTimer = System.currentTimeMillis(); } } else { SendPort send = (SendPort) iter.next(); w = send.newMessage(); } w.writeByte(SO_INVOCATION); w.writeObject(r); byteCount = w.finish(); } catch (IOException e) { System.err.println("SATIN '" + ident.name() + "': unable to send a shared object invocation: " + e); } }*/ //stats soInvocations++; soInvocationsBytes += byteCount; // @@@ I added this code, shouldn't we try to send immediately if needed? // We might not reach a safe point for a considerable time if (soInvocationsDelay > 0) { sendAccumulatedSOInvocations(); } if (SO_TIMING) { broadcastSOInvocationsTimer.stop(); } }
public void broadcastSOInvocation(SOInvocationRecord r) { long byteCount = 0; // int numToSend; WriteMessage w = null; if (SO_TIMING) { broadcastSOInvocationsTimer.start(); } if (SCALABLE) { doConnectSendPort(); } if (soSendPort.connectedTo().length > 0) { try { if (soInvocationsDelay > 0) { //do message combining w = soMessageCombiner.newMessage(); //soInvocationsToSend.add(r); if (soInvocationsDelayTimer == -1) { soInvocationsDelayTimer = System.currentTimeMillis(); } writtenInvocations++; } else { w = soSendPort.newMessage(); // w.writeInt(1); //w.writeObject(r); //byteCount = w.finish(); } w.writeByte(SO_INVOCATION); w.writeObject(r); byteCount = w.finish(); if (soInvocationsDelay > 0) { soCurrTotalMessageSize += byteCount; } } catch (IOException e) { System.err .println("SATIN '" + ident.name() + "': unable to broadcast a shared object invocation: " + e); } } /*Iterator iter = soSendPorts.values().iterator(); while (iter.hasNext()) { try { if (soInvocationsDelay > 0) { MessageCombiner mc = (MessageCombiner) iter.next(); w = mc.newMessage(); if (soInvocationsDelayTimer == -1) { soInvocationsDelayTimer = System.currentTimeMillis(); } } else { SendPort send = (SendPort) iter.next(); w = send.newMessage(); } w.writeByte(SO_INVOCATION); w.writeObject(r); byteCount = w.finish(); } catch (IOException e) { System.err.println("SATIN '" + ident.name() + "': unable to send a shared object invocation: " + e); } }*/ //stats soInvocations++; soInvocationsBytes += byteCount; if (SO_TIMING) { broadcastSOInvocationsTimer.stop(); } // @@@ I added this code, shouldn't we try to send immediately if needed? // We might not reach a safe point for a considerable time if (soInvocationsDelay > 0) { sendAccumulatedSOInvocations(); } }
diff --git a/gui/src/main/java/org/jboss/as/console/client/shared/runtime/jpa/JPAMetricPresenter.java b/gui/src/main/java/org/jboss/as/console/client/shared/runtime/jpa/JPAMetricPresenter.java index 5cef7c46..d05aa7b3 100644 --- a/gui/src/main/java/org/jboss/as/console/client/shared/runtime/jpa/JPAMetricPresenter.java +++ b/gui/src/main/java/org/jboss/as/console/client/shared/runtime/jpa/JPAMetricPresenter.java @@ -1,396 +1,396 @@ package org.jboss.as.console.client.shared.runtime.jpa; import com.google.gwt.core.client.Scheduler; import com.google.web.bindery.event.shared.EventBus; import com.google.inject.Inject; import com.gwtplatform.mvp.client.Presenter; import com.gwtplatform.mvp.client.View; import com.gwtplatform.mvp.client.annotations.NameToken; import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit; import com.gwtplatform.mvp.client.proxy.Place; import com.gwtplatform.mvp.client.proxy.PlaceManager; import com.gwtplatform.mvp.client.proxy.PlaceRequest; import com.gwtplatform.mvp.client.proxy.Proxy; import org.jboss.as.console.client.Console; import org.jboss.as.console.client.core.NameTokens; import org.jboss.as.console.client.domain.model.ServerInstance; import org.jboss.as.console.client.domain.model.SimpleCallback; import org.jboss.as.console.client.shared.BeanFactory; import org.jboss.as.console.client.shared.dispatch.DispatchAsync; import org.jboss.as.console.client.shared.dispatch.impl.DMRAction; import org.jboss.as.console.client.shared.dispatch.impl.DMRResponse; import org.jboss.as.console.client.shared.runtime.Metric; import org.jboss.as.console.client.shared.runtime.RuntimeBaseAddress; import org.jboss.as.console.client.shared.runtime.jpa.model.JPADeployment; import org.jboss.as.console.client.shared.state.CurrentServerSelection; import org.jboss.as.console.client.shared.state.ServerSelectionEvent; import org.jboss.as.console.client.shared.subsys.RevealStrategy; import org.jboss.as.console.client.widgets.forms.ApplicationMetaData; import org.jboss.as.console.client.widgets.forms.EntityAdapter; import org.jboss.dmr.client.ModelNode; import org.jboss.dmr.client.Property; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import static org.jboss.dmr.client.ModelDescriptionConstants.*; /** * @author Heiko Braun * @date 1/19/12 */ public class JPAMetricPresenter extends Presenter<JPAMetricPresenter.MyView, JPAMetricPresenter.MyProxy> implements ServerSelectionEvent.ServerSelectionListener { private DispatchAsync dispatcher; private RevealStrategy revealStrategy; private CurrentServerSelection serverSelection; private BeanFactory factory; private PlaceManager placeManager; private String[] selectedUnit; private EntityAdapter<JPADeployment> adapter; public PlaceManager getPlaceManager() { return placeManager; } @ProxyCodeSplit @NameToken(NameTokens.JPAMetricPresenter) public interface MyProxy extends Proxy<JPAMetricPresenter>, Place { } public interface MyView extends View { void setPresenter(JPAMetricPresenter presenter); void setJpaUnits(List<JPADeployment> jpaUnits); void setSelectedUnit(String[] strings); void updateMetric(UnitMetric unitMetric); void clearValues(); } @Inject public JPAMetricPresenter( EventBus eventBus, MyView view, MyProxy proxy, DispatchAsync dispatcher, ApplicationMetaData metaData, RevealStrategy revealStrategy, CurrentServerSelection serverSelection, BeanFactory factory, PlaceManager placeManager) { super(eventBus, view, proxy); this.dispatcher = dispatcher; this.revealStrategy = revealStrategy; this.placeManager = placeManager; this.serverSelection = serverSelection; this.factory = factory; adapter = new EntityAdapter<JPADeployment>(JPADeployment.class, metaData); } @Override protected void onBind() { super.onBind(); getView().setPresenter(this); getEventBus().addHandler(ServerSelectionEvent.TYPE, JPAMetricPresenter.this); } @Override public void prepareFromRequest(PlaceRequest request) { String dpl = request.getParameter("dpl", null); if(dpl!=null) { this.selectedUnit = new String[] { dpl, request.getParameter("unit", null) }; } else { this.selectedUnit = null; } } @Override protected void onReset() { super.onReset(); if(isVisible()) refresh(true); } @Override protected void revealInParent() { revealStrategy.revealInRuntimeParent(this); } @Override public void onServerSelection(String hostName, ServerInstance server, ServerSelectionEvent.Source source) { Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() { @Override public void execute() { refresh(true); } }); } public void refresh(final boolean paging) { if(!serverSelection.isActive()) { Console.warning(Console.CONSTANTS.common_err_server_not_active()); getView().clearValues(); getView().setJpaUnits(Collections.EMPTY_LIST); return; } ModelNode operation = new ModelNode(); operation.get(ADDRESS).setEmptyList(); operation.get(OP).set(COMPOSITE); List<ModelNode> steps = new ArrayList<ModelNode>(); ModelNode deploymentsOp = new ModelNode(); deploymentsOp.get(OP).set(READ_RESOURCE_OPERATION); deploymentsOp.get(ADDRESS).set(RuntimeBaseAddress.get()); deploymentsOp.get(ADDRESS).add("deployment", "*"); deploymentsOp.get(ADDRESS).add("subsystem", "jpa"); deploymentsOp.get(ADDRESS).add("hibernate-persistence-unit", "*"); deploymentsOp.get(INCLUDE_RUNTIME).set(true); ModelNode subdeploymentOp = new ModelNode(); subdeploymentOp.get(OP).set(READ_RESOURCE_OPERATION); subdeploymentOp.get(ADDRESS).set(RuntimeBaseAddress.get()); subdeploymentOp.get(ADDRESS).add("deployment", "*"); subdeploymentOp.get(ADDRESS).add("subdeployment", "*"); subdeploymentOp.get(ADDRESS).add("subsystem", "jpa"); subdeploymentOp.get(ADDRESS).add("hibernate-persistence-unit", "*"); subdeploymentOp.get(INCLUDE_RUNTIME).set(true); steps.add(deploymentsOp); steps.add(subdeploymentOp); operation.get(STEPS).set(steps); dispatcher.execute(new DMRAction(operation), new SimpleCallback<DMRResponse>() { @Override public void onSuccess(DMRResponse result) { ModelNode compositeResponse = result.get(); if(compositeResponse.isFailure()) { Console.error(Console.MESSAGES.failed("JPA Deployments"), compositeResponse.getFailureDescription()); } else { List<JPADeployment> jpaUnits = new ArrayList<JPADeployment>(); ModelNode compositeResult = compositeResponse.get(RESULT); ModelNode mainResponse = compositeResult.get("step-1").asObject(); ModelNode subdeploymentResponse = compositeResult.get("step-2").asObject(); parseJpaResources(mainResponse, jpaUnits); parseJpaResources(subdeploymentResponse, jpaUnits); getView().setJpaUnits(jpaUnits); } // update selection (paging) if(paging) getView().setSelectedUnit(selectedUnit); } }); } private void parseJpaResources(ModelNode response, List<JPADeployment> jpaUnits) { List<ModelNode> deployments = response.get(RESULT).asList(); for(ModelNode deployment : deployments) { ModelNode deploymentValue = deployment.get(RESULT).asObject(); List<Property> addressTokens = deployment.get(ADDRESS).asPropertyList(); Property unit = addressTokens.get(addressTokens.size()-1); JPADeployment jpaDeployment = factory.jpaDeployment().as(); String tokenString = unit.getValue().asString(); String[] tokens = tokenString.split("#"); jpaDeployment.setDeploymentName(tokens[0]); jpaDeployment.setPersistenceUnit(tokens[1]); // https://issues.jboss.org/browse/AS7-5157 boolean enabled = deploymentValue.hasDefined("enabled") ? deploymentValue.get("enabled").asBoolean() : false; jpaDeployment.setMetricEnabled(enabled); jpaUnits.add(jpaDeployment); } } public void loadMetrics(String[] tokens) { ModelNode operation = new ModelNode(); operation.get(ADDRESS).set(RuntimeBaseAddress.get()); // parent deployment names if(tokens[0].indexOf("/")!=-1) { String[] parent = tokens[0].split("/"); operation.get(ADDRESS).add("deployment", parent[0]); operation.get(ADDRESS).add("subdeployment", parent[1]); } else { operation.get(ADDRESS).add("deployment", tokens[0]); } operation.get(ADDRESS).add("subsystem", "jpa"); operation.get(ADDRESS).add("hibernate-persistence-unit", tokens[0]+"#"+tokens[1]); operation.get(OP).set(READ_RESOURCE_OPERATION); operation.get(INCLUDE_RUNTIME).set(true); dispatcher.execute(new DMRAction(operation), new SimpleCallback<DMRResponse>() { @Override public void onSuccess(DMRResponse result) { ModelNode response = result.get(); if(response.isFailure()) { Console.error( Console.MESSAGES.failed("JPA Metrics"), response.getFailureDescription() ); } else { ModelNode payload = response.get(RESULT).asObject(); boolean isEnabled = payload.get("enabled").asBoolean(); if(!isEnabled) { getView().updateMetric( new UnitMetric(false) ); } else { Metric txMetric = new Metric( payload.get("completed-transaction-count").asLong(), payload.get("successful-transaction-count").asLong() ); // ---- Metric queryExecMetric = new Metric( payload.get("query-execution-count").asLong(), payload.get("query-execution-max-time").asLong() ); queryExecMetric.add( payload.get("query-execution-max-time-query-string").asString() ); // ---- Metric queryCacheMetric = new Metric( payload.get("query-cache-put-count").asLong(), payload.get("query-cache-hit-count").asLong(), payload.get("query-cache-miss-count").asLong() ); // ---- Metric secondLevelCacheMetric = new Metric( payload.get("second-level-cache-put-count").asLong(), payload.get("second-level-cache-hit-count").asLong(), payload.get("second-level-cache-miss-count").asLong() ); Metric connectionMetric = new Metric( - payload.get("connect-count").asLong(), payload.get("session-open-count").asLong(), - payload.get("session-close-count").asLong() + payload.get("session-close-count").asLong(), + payload.get("connect-count").asLong() ); getView().updateMetric( new UnitMetric( txMetric, queryCacheMetric, queryExecMetric, secondLevelCacheMetric, connectionMetric ) ); } } } }); } public void onSaveJPADeployment(JPADeployment editedEntity, Map<String, Object> changeset) { ModelNode address = new ModelNode(); address.get(ADDRESS).set(RuntimeBaseAddress.get()); // parent deployment names if(editedEntity.getDeploymentName().indexOf("/")!=-1) { String[] parent = editedEntity.getDeploymentName().split("/"); address.get(ADDRESS).add("deployment", parent[0]); address.get(ADDRESS).add("subdeployment", parent[1]); } else { address.get(ADDRESS).add("deployment", editedEntity.getDeploymentName()); } address.get(ADDRESS).add("subsystem", "jpa"); address.get(ADDRESS).add("hibernate-persistence-unit", editedEntity.getDeploymentName()+"#"+editedEntity.getPersistenceUnit()); ModelNode operation = adapter.fromChangeset(changeset, address); dispatcher.execute(new DMRAction(operation), new SimpleCallback<DMRResponse>() { @Override public void onSuccess(DMRResponse result) { ModelNode response = result.get(); if(response.isFailure()) { Console.error( Console.MESSAGES.modificationFailed("JPA Deployment"), response.getFailureDescription()); } else { Console.info(Console.MESSAGES.modified("JPA Deployment")); refresh(false); } } }); } }
false
true
public void loadMetrics(String[] tokens) { ModelNode operation = new ModelNode(); operation.get(ADDRESS).set(RuntimeBaseAddress.get()); // parent deployment names if(tokens[0].indexOf("/")!=-1) { String[] parent = tokens[0].split("/"); operation.get(ADDRESS).add("deployment", parent[0]); operation.get(ADDRESS).add("subdeployment", parent[1]); } else { operation.get(ADDRESS).add("deployment", tokens[0]); } operation.get(ADDRESS).add("subsystem", "jpa"); operation.get(ADDRESS).add("hibernate-persistence-unit", tokens[0]+"#"+tokens[1]); operation.get(OP).set(READ_RESOURCE_OPERATION); operation.get(INCLUDE_RUNTIME).set(true); dispatcher.execute(new DMRAction(operation), new SimpleCallback<DMRResponse>() { @Override public void onSuccess(DMRResponse result) { ModelNode response = result.get(); if(response.isFailure()) { Console.error( Console.MESSAGES.failed("JPA Metrics"), response.getFailureDescription() ); } else { ModelNode payload = response.get(RESULT).asObject(); boolean isEnabled = payload.get("enabled").asBoolean(); if(!isEnabled) { getView().updateMetric( new UnitMetric(false) ); } else { Metric txMetric = new Metric( payload.get("completed-transaction-count").asLong(), payload.get("successful-transaction-count").asLong() ); // ---- Metric queryExecMetric = new Metric( payload.get("query-execution-count").asLong(), payload.get("query-execution-max-time").asLong() ); queryExecMetric.add( payload.get("query-execution-max-time-query-string").asString() ); // ---- Metric queryCacheMetric = new Metric( payload.get("query-cache-put-count").asLong(), payload.get("query-cache-hit-count").asLong(), payload.get("query-cache-miss-count").asLong() ); // ---- Metric secondLevelCacheMetric = new Metric( payload.get("second-level-cache-put-count").asLong(), payload.get("second-level-cache-hit-count").asLong(), payload.get("second-level-cache-miss-count").asLong() ); Metric connectionMetric = new Metric( payload.get("connect-count").asLong(), payload.get("session-open-count").asLong(), payload.get("session-close-count").asLong() ); getView().updateMetric( new UnitMetric( txMetric, queryCacheMetric, queryExecMetric, secondLevelCacheMetric, connectionMetric ) ); } } } }); }
public void loadMetrics(String[] tokens) { ModelNode operation = new ModelNode(); operation.get(ADDRESS).set(RuntimeBaseAddress.get()); // parent deployment names if(tokens[0].indexOf("/")!=-1) { String[] parent = tokens[0].split("/"); operation.get(ADDRESS).add("deployment", parent[0]); operation.get(ADDRESS).add("subdeployment", parent[1]); } else { operation.get(ADDRESS).add("deployment", tokens[0]); } operation.get(ADDRESS).add("subsystem", "jpa"); operation.get(ADDRESS).add("hibernate-persistence-unit", tokens[0]+"#"+tokens[1]); operation.get(OP).set(READ_RESOURCE_OPERATION); operation.get(INCLUDE_RUNTIME).set(true); dispatcher.execute(new DMRAction(operation), new SimpleCallback<DMRResponse>() { @Override public void onSuccess(DMRResponse result) { ModelNode response = result.get(); if(response.isFailure()) { Console.error( Console.MESSAGES.failed("JPA Metrics"), response.getFailureDescription() ); } else { ModelNode payload = response.get(RESULT).asObject(); boolean isEnabled = payload.get("enabled").asBoolean(); if(!isEnabled) { getView().updateMetric( new UnitMetric(false) ); } else { Metric txMetric = new Metric( payload.get("completed-transaction-count").asLong(), payload.get("successful-transaction-count").asLong() ); // ---- Metric queryExecMetric = new Metric( payload.get("query-execution-count").asLong(), payload.get("query-execution-max-time").asLong() ); queryExecMetric.add( payload.get("query-execution-max-time-query-string").asString() ); // ---- Metric queryCacheMetric = new Metric( payload.get("query-cache-put-count").asLong(), payload.get("query-cache-hit-count").asLong(), payload.get("query-cache-miss-count").asLong() ); // ---- Metric secondLevelCacheMetric = new Metric( payload.get("second-level-cache-put-count").asLong(), payload.get("second-level-cache-hit-count").asLong(), payload.get("second-level-cache-miss-count").asLong() ); Metric connectionMetric = new Metric( payload.get("session-open-count").asLong(), payload.get("session-close-count").asLong(), payload.get("connect-count").asLong() ); getView().updateMetric( new UnitMetric( txMetric, queryCacheMetric, queryExecMetric, secondLevelCacheMetric, connectionMetric ) ); } } } }); }
diff --git a/src/gtpdisplay/Main.java b/src/gtpdisplay/Main.java index b45f10ac..e9045ee5 100644 --- a/src/gtpdisplay/Main.java +++ b/src/gtpdisplay/Main.java @@ -1,90 +1,82 @@ //---------------------------------------------------------------------------- // $Id$ // $Source$ //---------------------------------------------------------------------------- package gtpdisplay; import java.awt.*; import java.io.*; import java.util.*; import game.*; import go.*; import gtp.*; import gui.*; import utils.*; import version.*; //---------------------------------------------------------------------------- public class Main { public static void main(String[] args) { try { String options[] = { "config:", "help", "size:", "verbose", "version", "version2" }; Options opt = new Options(args, options); opt.handleConfigOption(); if (opt.isSet("help")) { printUsage(System.out); System.exit(0); } if (opt.isSet("version")) { System.out.println("GtpDisplay " + Version.get()); System.exit(0); } boolean verbose = opt.isSet("verbose"); boolean version2 = opt.isSet("version2"); int size = opt.getInteger("size", -1); Vector arguments = opt.getArguments(); if (arguments.size() != 1) { printUsage(System.err); System.exit(-1); } - PrintStream log = null; - if (opt.isSet("log")) - { - File file = new File(opt.getString("log")); - log = new PrintStream(new FileOutputStream(file)); - } String program = (String)arguments.get(0); GtpDisplay gtpDisplay = new GtpDisplay(System.in, System.out, program, verbose); gtpDisplay.mainLoop(); gtpDisplay.close(); - if (log != null) - log.close(); } catch (Throwable t) { StringUtils.printException(t); System.exit(-1); } } private static void printUsage(PrintStream out) { String helpText = "Usage: java -jar gtpdisplay.jar program\n" + "\n" + "-config config file\n" + "-help print help and exit\n" + "-size accept only this board size\n" + "-verbose log GTP stream to stderr\n" + "-version print version and exit\n"; out.print(helpText); } } //----------------------------------------------------------------------------
false
true
public static void main(String[] args) { try { String options[] = { "config:", "help", "size:", "verbose", "version", "version2" }; Options opt = new Options(args, options); opt.handleConfigOption(); if (opt.isSet("help")) { printUsage(System.out); System.exit(0); } if (opt.isSet("version")) { System.out.println("GtpDisplay " + Version.get()); System.exit(0); } boolean verbose = opt.isSet("verbose"); boolean version2 = opt.isSet("version2"); int size = opt.getInteger("size", -1); Vector arguments = opt.getArguments(); if (arguments.size() != 1) { printUsage(System.err); System.exit(-1); } PrintStream log = null; if (opt.isSet("log")) { File file = new File(opt.getString("log")); log = new PrintStream(new FileOutputStream(file)); } String program = (String)arguments.get(0); GtpDisplay gtpDisplay = new GtpDisplay(System.in, System.out, program, verbose); gtpDisplay.mainLoop(); gtpDisplay.close(); if (log != null) log.close(); } catch (Throwable t) { StringUtils.printException(t); System.exit(-1); } }
public static void main(String[] args) { try { String options[] = { "config:", "help", "size:", "verbose", "version", "version2" }; Options opt = new Options(args, options); opt.handleConfigOption(); if (opt.isSet("help")) { printUsage(System.out); System.exit(0); } if (opt.isSet("version")) { System.out.println("GtpDisplay " + Version.get()); System.exit(0); } boolean verbose = opt.isSet("verbose"); boolean version2 = opt.isSet("version2"); int size = opt.getInteger("size", -1); Vector arguments = opt.getArguments(); if (arguments.size() != 1) { printUsage(System.err); System.exit(-1); } String program = (String)arguments.get(0); GtpDisplay gtpDisplay = new GtpDisplay(System.in, System.out, program, verbose); gtpDisplay.mainLoop(); gtpDisplay.close(); } catch (Throwable t) { StringUtils.printException(t); System.exit(-1); } }
diff --git a/src/com/entrocorp/linearlogic/oneinthegun/commands/CommandJoin.java b/src/com/entrocorp/linearlogic/oneinthegun/commands/CommandJoin.java index 8d7f9fd..99b962c 100644 --- a/src/com/entrocorp/linearlogic/oneinthegun/commands/CommandJoin.java +++ b/src/com/entrocorp/linearlogic/oneinthegun/commands/CommandJoin.java @@ -1,44 +1,45 @@ package com.entrocorp.linearlogic.oneinthegun.commands; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import com.entrocorp.linearlogic.oneinthegun.OITG; public class CommandJoin extends OITGArenaCommand { public CommandJoin(CommandSender sender, String[] args) { super(sender, args, 1, false, "join <arena>", "oneinthegun.arena.join", true); } public void run() { Player player = (Player) sender; if (arena.isIngame()) { player.sendMessage(OITG.prefix + ChatColor.RED + "A game is already in progress in that arena, choose another."); return; } if (arena.isClosed()) { player.sendMessage(OITG.prefix + ChatColor.RED + "That arena is closed, choose another."); return; } if (arena.getPlayerCount() >= arena.getPlayerLimit()) { player.sendMessage(OITG.prefix + ChatColor.RED + "That arena is full, choose another."); return; } if (arena.getLobby() == null) { player.sendMessage(OITG.prefix + ChatColor.RED + "That arena has not been set up: no lobby has been set."); return; } if (arena.getSpawns().length == 0) { player.sendMessage(OITG.prefix + ChatColor.RED + "That arena has not been set up: no spawn points have been set."); return; } if (OITG.instance.getArenaManager().getArena(player) != null) { player.sendMessage(OITG.prefix + ChatColor.RED + "You are already in an arena!"); return; } arena.addPlayer((Player) sender); + player.teleport(arena.getLobby()); } }
true
true
public void run() { Player player = (Player) sender; if (arena.isIngame()) { player.sendMessage(OITG.prefix + ChatColor.RED + "A game is already in progress in that arena, choose another."); return; } if (arena.isClosed()) { player.sendMessage(OITG.prefix + ChatColor.RED + "That arena is closed, choose another."); return; } if (arena.getPlayerCount() >= arena.getPlayerLimit()) { player.sendMessage(OITG.prefix + ChatColor.RED + "That arena is full, choose another."); return; } if (arena.getLobby() == null) { player.sendMessage(OITG.prefix + ChatColor.RED + "That arena has not been set up: no lobby has been set."); return; } if (arena.getSpawns().length == 0) { player.sendMessage(OITG.prefix + ChatColor.RED + "That arena has not been set up: no spawn points have been set."); return; } if (OITG.instance.getArenaManager().getArena(player) != null) { player.sendMessage(OITG.prefix + ChatColor.RED + "You are already in an arena!"); return; } arena.addPlayer((Player) sender); }
public void run() { Player player = (Player) sender; if (arena.isIngame()) { player.sendMessage(OITG.prefix + ChatColor.RED + "A game is already in progress in that arena, choose another."); return; } if (arena.isClosed()) { player.sendMessage(OITG.prefix + ChatColor.RED + "That arena is closed, choose another."); return; } if (arena.getPlayerCount() >= arena.getPlayerLimit()) { player.sendMessage(OITG.prefix + ChatColor.RED + "That arena is full, choose another."); return; } if (arena.getLobby() == null) { player.sendMessage(OITG.prefix + ChatColor.RED + "That arena has not been set up: no lobby has been set."); return; } if (arena.getSpawns().length == 0) { player.sendMessage(OITG.prefix + ChatColor.RED + "That arena has not been set up: no spawn points have been set."); return; } if (OITG.instance.getArenaManager().getArena(player) != null) { player.sendMessage(OITG.prefix + ChatColor.RED + "You are already in an arena!"); return; } arena.addPlayer((Player) sender); player.teleport(arena.getLobby()); }
diff --git a/src/test/java/org/ini4j/IniHandlerTest.java b/src/test/java/org/ini4j/IniHandlerTest.java index c3dce2e..fd3a57c 100755 --- a/src/test/java/org/ini4j/IniHandlerTest.java +++ b/src/test/java/org/ini4j/IniHandlerTest.java @@ -1,146 +1,146 @@ /* * Copyright 2005 [ini4j] Development Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ini4j; import junit.framework.Test; import junit.framework.TestSuite; import org.easymock.classextension.EasyMock; /** * JUnit test of IniParser class. */ public class IniHandlerTest extends AbstractTestBase { private static final String DOPEY_WEIGHT = "${bashful/weight}"; private static final String DOPEY_HEIGHT = "${doc/height}"; private static final String GRUMPY_HEIGHT = "${dopey/height}"; private static final String SLEEPY_HEIGHT = "${doc/height}8"; private static final String SNEEZY_HOME_PAGE = "${happy/homePage}/~sneezy"; /** * Instantiate test. * * @param testName name of the test */ public IniHandlerTest(String name) { super(name); } /** * Create test suite. * * @return new test suite */ public static Test suite() { return new TestSuite(IniHandlerTest.class); } protected IniHandler newHandler() throws Exception { IniHandler handler = EasyMock.createMock(IniHandler.class); Dwarfs dwarfs = newDwarfs(); Dwarf dwarf; handler.startIni(); dwarf = dwarfs.getBashful(); handler.startSection(Dwarfs.PROP_BASHFUL); handler.handleOption(Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); handler.handleOption(Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); handler.endSection(); dwarf = dwarfs.getDoc(); handler.startSection(Dwarfs.PROP_DOC); handler.handleOption(Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); handler.handleOption(Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); handler.endSection(); dwarf = dwarfs.getDopey(); handler.startSection(Dwarfs.PROP_DOPEY); handler.handleOption(Dwarf.PROP_WEIGHT, DOPEY_WEIGHT); handler.handleOption(Dwarf.PROP_HEIGHT, DOPEY_HEIGHT); handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); handler.endSection(); dwarf = dwarfs.getGrumpy(); handler.startSection(Dwarfs.PROP_GRUMPY); handler.handleOption(Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); handler.handleOption(Dwarf.PROP_HEIGHT, GRUMPY_HEIGHT); handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); handler.endSection(); dwarf = dwarfs.getHappy(); handler.startSection(Dwarfs.PROP_HAPPY); handler.handleOption(Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); handler.handleOption(Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); - handler.handleOption(Dwarf.PROP_HOME_PAGE, "dummy"); + handler.handleOption(EasyMock.eq(Dwarf.PROP_HOME_PAGE), (String)EasyMock.anyObject()); handler.endSection(); dwarf = dwarfs.getSleepy(); handler.startSection(Dwarfs.PROP_SLEEPY); handler.handleOption(Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); handler.handleOption(Dwarf.PROP_HEIGHT, SLEEPY_HEIGHT); handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); handler.endSection(); dwarf = dwarfs.getSneezy(); handler.startSection(Dwarfs.PROP_SNEEZY); handler.handleOption(Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); handler.handleOption(Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); handler.handleOption(Dwarf.PROP_HOME_PAGE, SNEEZY_HOME_PAGE); handler.endSection(); dwarf = dwarfs.getHappy(); handler.startSection(Dwarfs.PROP_HAPPY); handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); handler.endSection(); handler.endIni(); return handler; } public void testHandler() throws Exception { IniParser parser = new IniParser(); IniHandler handler; handler = newHandler(); EasyMock.replay(handler); parser.parse(getClass().getClassLoader().getResourceAsStream(DWARFS_INI), handler); EasyMock.verify(handler); handler = newHandler(); EasyMock.replay(handler); parser.parseXML(getClass().getClassLoader().getResourceAsStream(DWARFS_XML), handler); EasyMock.verify(handler); } }
true
true
protected IniHandler newHandler() throws Exception { IniHandler handler = EasyMock.createMock(IniHandler.class); Dwarfs dwarfs = newDwarfs(); Dwarf dwarf; handler.startIni(); dwarf = dwarfs.getBashful(); handler.startSection(Dwarfs.PROP_BASHFUL); handler.handleOption(Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); handler.handleOption(Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); handler.endSection(); dwarf = dwarfs.getDoc(); handler.startSection(Dwarfs.PROP_DOC); handler.handleOption(Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); handler.handleOption(Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); handler.endSection(); dwarf = dwarfs.getDopey(); handler.startSection(Dwarfs.PROP_DOPEY); handler.handleOption(Dwarf.PROP_WEIGHT, DOPEY_WEIGHT); handler.handleOption(Dwarf.PROP_HEIGHT, DOPEY_HEIGHT); handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); handler.endSection(); dwarf = dwarfs.getGrumpy(); handler.startSection(Dwarfs.PROP_GRUMPY); handler.handleOption(Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); handler.handleOption(Dwarf.PROP_HEIGHT, GRUMPY_HEIGHT); handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); handler.endSection(); dwarf = dwarfs.getHappy(); handler.startSection(Dwarfs.PROP_HAPPY); handler.handleOption(Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); handler.handleOption(Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); handler.handleOption(Dwarf.PROP_HOME_PAGE, "dummy"); handler.endSection(); dwarf = dwarfs.getSleepy(); handler.startSection(Dwarfs.PROP_SLEEPY); handler.handleOption(Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); handler.handleOption(Dwarf.PROP_HEIGHT, SLEEPY_HEIGHT); handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); handler.endSection(); dwarf = dwarfs.getSneezy(); handler.startSection(Dwarfs.PROP_SNEEZY); handler.handleOption(Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); handler.handleOption(Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); handler.handleOption(Dwarf.PROP_HOME_PAGE, SNEEZY_HOME_PAGE); handler.endSection(); dwarf = dwarfs.getHappy(); handler.startSection(Dwarfs.PROP_HAPPY); handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); handler.endSection(); handler.endIni(); return handler; }
protected IniHandler newHandler() throws Exception { IniHandler handler = EasyMock.createMock(IniHandler.class); Dwarfs dwarfs = newDwarfs(); Dwarf dwarf; handler.startIni(); dwarf = dwarfs.getBashful(); handler.startSection(Dwarfs.PROP_BASHFUL); handler.handleOption(Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); handler.handleOption(Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); handler.endSection(); dwarf = dwarfs.getDoc(); handler.startSection(Dwarfs.PROP_DOC); handler.handleOption(Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); handler.handleOption(Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); handler.endSection(); dwarf = dwarfs.getDopey(); handler.startSection(Dwarfs.PROP_DOPEY); handler.handleOption(Dwarf.PROP_WEIGHT, DOPEY_WEIGHT); handler.handleOption(Dwarf.PROP_HEIGHT, DOPEY_HEIGHT); handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); handler.endSection(); dwarf = dwarfs.getGrumpy(); handler.startSection(Dwarfs.PROP_GRUMPY); handler.handleOption(Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); handler.handleOption(Dwarf.PROP_HEIGHT, GRUMPY_HEIGHT); handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); handler.endSection(); dwarf = dwarfs.getHappy(); handler.startSection(Dwarfs.PROP_HAPPY); handler.handleOption(Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); handler.handleOption(Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); handler.handleOption(EasyMock.eq(Dwarf.PROP_HOME_PAGE), (String)EasyMock.anyObject()); handler.endSection(); dwarf = dwarfs.getSleepy(); handler.startSection(Dwarfs.PROP_SLEEPY); handler.handleOption(Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); handler.handleOption(Dwarf.PROP_HEIGHT, SLEEPY_HEIGHT); handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); handler.endSection(); dwarf = dwarfs.getSneezy(); handler.startSection(Dwarfs.PROP_SNEEZY); handler.handleOption(Dwarf.PROP_WEIGHT, String.valueOf(dwarf.getWeight())); handler.handleOption(Dwarf.PROP_HEIGHT, String.valueOf(dwarf.getHeight())); handler.handleOption(Dwarf.PROP_AGE, String.valueOf(dwarf.getAge())); handler.handleOption(Dwarf.PROP_HOME_PAGE, SNEEZY_HOME_PAGE); handler.endSection(); dwarf = dwarfs.getHappy(); handler.startSection(Dwarfs.PROP_HAPPY); handler.handleOption(Dwarf.PROP_HOME_PAGE, String.valueOf(dwarf.getHomePage())); handler.endSection(); handler.endIni(); return handler; }
diff --git a/jetty/src/main/java/org/mortbay/jetty/AbstractConnector.java b/jetty/src/main/java/org/mortbay/jetty/AbstractConnector.java index 87378af59..1ec0a30c2 100644 --- a/jetty/src/main/java/org/mortbay/jetty/AbstractConnector.java +++ b/jetty/src/main/java/org/mortbay/jetty/AbstractConnector.java @@ -1,784 +1,789 @@ //======================================================================== //$Id: AbstractConnector.java,v 1.9 2005/11/14 11:00:31 gregwilkins Exp $ //Copyright 2004-2005 Mort Bay Consulting Pty. Ltd. //------------------------------------------------------------------------ //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at //http://www.apache.org/licenses/LICENSE-2.0 //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. //======================================================================== package org.mortbay.jetty; import java.io.IOException; import java.net.Socket; import java.util.ArrayList; import org.mortbay.component.AbstractLifeCycle; import org.mortbay.component.LifeCycle; import org.mortbay.io.Buffer; import org.mortbay.io.EndPoint; import org.mortbay.log.Log; import org.mortbay.thread.ThreadPool; import org.mortbay.util.ajax.Continuation; import org.mortbay.util.ajax.WaitingContinuation; /** Abstract Connector implementation. * This abstract implemenation of the Connector interface provides:<ul> * <li>AbstractLifeCycle implementation</li> * <li>Implementations for connector getters and setters</li> * <li>Buffer management</li> * <li>Socket configuration</li> * <li>Base acceptor thread</li> * </ul> * * @author gregw * * TODO - allow multiple Acceptor threads */ public abstract class AbstractConnector extends AbstractBuffers implements Connector { private String _name; private Server _server; private ThreadPool _threadPool; private String _host; private int _port=0; private String _integralScheme=HttpSchemes.HTTPS; private int _integralPort=0; private String _confidentialScheme=HttpSchemes.HTTPS; private int _confidentialPort=0; private int _acceptQueueSize=0; private int _acceptors=1; private int _acceptorPriorityOffset=0; private boolean _useDNS; protected int _maxIdleTime=200000; protected int _lowResourceMaxIdleTime=-1; protected int _soLingerTime=-1; private transient Thread[] _acceptorThread; Object _statsLock = new Object(); transient long _statsStartedAt=-1; transient int _requests; transient int _connections; // total number of connections made to server transient int _connectionsOpen; // number of connections currently open transient int _connectionsOpenMin; // min number of connections open simultaneously transient int _connectionsOpenMax; // max number of connections open simultaneously transient long _connectionsDurationMin; // min duration of a connection transient long _connectionsDurationMax; // max duration of a connection transient long _connectionsDurationTotal; // total duration of all coneection transient int _connectionsRequestsMin; // min requests per connection transient int _connectionsRequestsMax; // max requests per connection /* ------------------------------------------------------------------------------- */ /** */ public AbstractConnector() { } /* ------------------------------------------------------------------------------- */ /* */ public Server getServer() { return _server; } /* ------------------------------------------------------------------------------- */ public void setServer(Server server) { _server=server; } /* ------------------------------------------------------------------------------- */ /* * @see org.mortbay.jetty.HttpListener#getHttpServer() */ public ThreadPool getThreadPool() { return _threadPool; } /* ------------------------------------------------------------------------------- */ public void setThreadPool(ThreadPool pool) { _threadPool=pool; } /* ------------------------------------------------------------------------------- */ /** */ public void setHost(String host) { _host=host; } /* ------------------------------------------------------------------------------- */ /* */ public String getHost() { return _host; } /* ------------------------------------------------------------------------------- */ /* * @see org.mortbay.jetty.HttpListener#setPort(int) */ public void setPort(int port) { _port=port; } /* ------------------------------------------------------------------------------- */ /* * @see org.mortbay.jetty.HttpListener#getPort() */ public int getPort() { return _port; } /* ------------------------------------------------------------ */ /** * @return Returns the maxIdleTime. */ public int getMaxIdleTime() { return _maxIdleTime; } /* ------------------------------------------------------------ */ /** * @param maxIdleTime The maxIdleTime to set. */ public void setMaxIdleTime(int maxIdleTime) { _maxIdleTime = maxIdleTime; } /* ------------------------------------------------------------ */ /** * @return Returns the maxIdleTime. */ public int getLowResourceMaxIdleTime() { return _lowResourceMaxIdleTime; } /* ------------------------------------------------------------ */ /** * @param maxIdleTime The maxIdleTime to set. */ public void setLowResourceMaxIdleTime(int maxIdleTime) { _lowResourceMaxIdleTime = maxIdleTime; } /* ------------------------------------------------------------ */ /** * @return Returns the soLingerTime. */ public long getSoLingerTime() { return _soLingerTime; } /* ------------------------------------------------------------ */ /** * @return Returns the acceptQueueSize. */ public int getAcceptQueueSize() { return _acceptQueueSize; } /* ------------------------------------------------------------ */ /** * @param acceptQueueSize The acceptQueueSize to set. */ public void setAcceptQueueSize(int acceptQueueSize) { _acceptQueueSize = acceptQueueSize; } /* ------------------------------------------------------------ */ /** * @return Returns the number of acceptor threads. */ public int getAcceptors() { return _acceptors; } /* ------------------------------------------------------------ */ /** * @param acceptors The number of acceptor threads to set. */ public void setAcceptors(int acceptors) { _acceptors = acceptors; } /* ------------------------------------------------------------ */ /** * @param soLingerTime The soLingerTime to set or -1 to disable. */ public void setSoLingerTime(int soLingerTime) { _soLingerTime = soLingerTime; } /* ------------------------------------------------------------ */ protected void doStart() throws Exception { if (_server==null) throw new IllegalStateException("No server"); // open listener port open(); super.doStart(); if (_threadPool==null) _threadPool=_server.getThreadPool(); if (_threadPool!=_server.getThreadPool() && (_threadPool instanceof LifeCycle)) ((LifeCycle)_threadPool).start(); // Start selector thread synchronized(this) { _acceptorThread=new Thread[getAcceptors()]; for (int i=0;i<_acceptorThread.length;i++) { if (!_threadPool.dispatch(new Acceptor(i))) { Log.warn("insufficient maxThreads configured for {}",this); break; } } } Log.info("Started {}",this); } /* ------------------------------------------------------------ */ protected void doStop() throws Exception { try{close();} catch(IOException e) {Log.warn(e);} if (_threadPool==_server.getThreadPool()) _threadPool=null; else if (_threadPool instanceof LifeCycle) ((LifeCycle)_threadPool).stop(); super.doStop(); Thread[] acceptors=null; synchronized(this) { acceptors=_acceptorThread; _acceptorThread=null; } if (acceptors != null) { for (int i=0;i<acceptors.length;i++) { Thread thread=acceptors[i]; if (thread!=null) thread.interrupt(); } } } /* ------------------------------------------------------------ */ public void join() throws InterruptedException { Thread[] threads=_acceptorThread; if (threads!=null) for (int i=0;i<threads.length;i++) if (threads[i]!=null) threads[i].join(); } /* ------------------------------------------------------------ */ protected void configure(Socket socket) throws IOException { try { socket.setTcpNoDelay(true); if (_maxIdleTime >= 0) socket.setSoTimeout(_maxIdleTime); if (_soLingerTime >= 0) socket.setSoLinger(true, _soLingerTime/1000); else socket.setSoLinger(false, 0); } catch (Exception e) { Log.ignore(e); } } /* ------------------------------------------------------------ */ public void customize(EndPoint endpoint, Request request) throws IOException { } /* ------------------------------------------------------------ */ public void persist(EndPoint endpoint) throws IOException { } /* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */ /* * @see org.mortbay.jetty.Connector#getConfidentialPort() */ public int getConfidentialPort() { return _confidentialPort; } /* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */ /* * @see org.mortbay.jetty.Connector#getConfidentialScheme() */ public String getConfidentialScheme() { return _confidentialScheme; } /* ------------------------------------------------------------ */ /* * @see org.mortbay.jetty.Connector#isConfidential(org.mortbay.jetty.Request) */ public boolean isIntegral(Request request) { return false; } /* ------------------------------------------------------------ */ /* * @see org.mortbay.jetty.Connector#getConfidentialPort() */ public int getIntegralPort() { return _integralPort; } /* ------------------------------------------------------------ */ /* * @see org.mortbay.jetty.Connector#getIntegralScheme() */ public String getIntegralScheme() { return _integralScheme; } /* ------------------------------------------------------------ */ /* * @see org.mortbay.jetty.Connector#isConfidential(org.mortbay.jetty.Request) */ public boolean isConfidential(Request request) { return false; } /* ------------------------------------------------------------ */ /** * @param confidentialPort The confidentialPort to set. */ public void setConfidentialPort(int confidentialPort) { _confidentialPort = confidentialPort; } /* ------------------------------------------------------------ */ /** * @param confidentialScheme The confidentialScheme to set. */ public void setConfidentialScheme(String confidentialScheme) { _confidentialScheme = confidentialScheme; } /* ------------------------------------------------------------ */ /** * @param integralPort The integralPort to set. */ public void setIntegralPort(int integralPort) { _integralPort = integralPort; } /* ------------------------------------------------------------ */ /** * @param integralScheme The integralScheme to set. */ public void setIntegralScheme(String integralScheme) { _integralScheme = integralScheme; } /* ------------------------------------------------------------ */ public Continuation newContinuation() { return new WaitingContinuation(); } /* ------------------------------------------------------------ */ protected abstract void accept(int acceptorID) throws IOException, InterruptedException; /* ------------------------------------------------------------ */ public void stopAccept(int acceptorID) throws Exception { } /* ------------------------------------------------------------ */ public boolean getResolveNames() { return _useDNS; } /* ------------------------------------------------------------ */ public void setResolveNames(boolean resolve) { _useDNS=resolve; } /* ------------------------------------------------------------ */ public String toString() { String name = this.getClass().getName(); int dot = name.lastIndexOf('.'); if (dot>0) name=name.substring(dot+1); return name+"@"+(getHost()==null?"0.0.0.0":getHost())+":"+(getLocalPort()<=0?getPort():getLocalPort()); } /* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */ private class Acceptor implements Runnable { int _acceptor=0; Acceptor(int id) { _acceptor=id; } /* ------------------------------------------------------------ */ public void run() { Thread current = Thread.currentThread(); synchronized(AbstractConnector.this) { if (_acceptorThread==null) return; _acceptorThread[_acceptor]=current; } String name =_acceptorThread[_acceptor].getName(); current.setName(name+" - Acceptor"+_acceptor+" "+AbstractConnector.this); int old_priority=current.getPriority(); try { current.setPriority(old_priority-_acceptorPriorityOffset); while (isRunning() && getConnection()!=null) { try { accept(_acceptor); } catch(EofException e) { Log.ignore(e); } catch(IOException e) { Log.ignore(e); } - catch(Exception e) + catch(ThreadDeath e) + { + Log.warn(e); + throw e; + } + catch(Throwable e) { Log.warn(e); } } } finally { current.setPriority(old_priority); current.setName(name); try { if (_acceptor==0) close(); } catch (IOException e) { Log.warn(e); } synchronized(AbstractConnector.this) { if (_acceptorThread!=null) _acceptorThread[_acceptor]=null; } } } } /* ------------------------------------------------------------ */ public String getName() { if (_name==null) _name= (getHost()==null?"0.0.0.0":getHost())+":"+(getLocalPort()<=0?getPort():getLocalPort()); return _name; } /* ------------------------------------------------------------ */ public void setName(String name) { _name = name; } /* ------------------------------------------------------------ */ /** * @return Get the number of requests handled by this context * since last call of statsReset(). If setStatsOn(false) then this * is undefined. */ public int getRequests() {return _requests;} /* ------------------------------------------------------------ */ /** * @return Returns the connectionsDurationMin. */ public long getConnectionsDurationMin() { return _connectionsDurationMin; } /* ------------------------------------------------------------ */ /** * @return Returns the connectionsDurationTotal. */ public long getConnectionsDurationTotal() { return _connectionsDurationTotal; } /* ------------------------------------------------------------ */ /** * @return Returns the connectionsOpenMin. */ public int getConnectionsOpenMin() { return _connectionsOpenMin; } /* ------------------------------------------------------------ */ /** * @return Returns the connectionsRequestsMin. */ public int getConnectionsRequestsMin() { return _connectionsRequestsMin; } /* ------------------------------------------------------------ */ /** * @return Number of connections accepted by the server since * statsReset() called. Undefined if setStatsOn(false). */ public int getConnections() {return _connections;} /* ------------------------------------------------------------ */ /** * @return Number of connections currently open that were opened * since statsReset() called. Undefined if setStatsOn(false). */ public int getConnectionsOpen() {return _connectionsOpen;} /* ------------------------------------------------------------ */ /** * @return Maximum number of connections opened simultaneously * since statsReset() called. Undefined if setStatsOn(false). */ public int getConnectionsOpenMax() {return _connectionsOpenMax;} /* ------------------------------------------------------------ */ /** * @return Average duration in milliseconds of open connections * since statsReset() called. Undefined if setStatsOn(false). */ public long getConnectionsDurationAve() {return _connections==0?0:(_connectionsDurationTotal/_connections);} /* ------------------------------------------------------------ */ /** * @return Maximum duration in milliseconds of an open connection * since statsReset() called. Undefined if setStatsOn(false). */ public long getConnectionsDurationMax() {return _connectionsDurationMax;} /* ------------------------------------------------------------ */ /** * @return Average number of requests per connection * since statsReset() called. Undefined if setStatsOn(false). */ public int getConnectionsRequestsAve() {return _connections==0?0:(_requests/_connections);} /* ------------------------------------------------------------ */ /** * @return Maximum number of requests per connection * since statsReset() called. Undefined if setStatsOn(false). */ public int getConnectionsRequestsMax() {return _connectionsRequestsMax;} /* ------------------------------------------------------------ */ /** Reset statistics. */ public void statsReset() { _statsStartedAt=_statsStartedAt==-1?-1:System.currentTimeMillis(); _connections=0; _connectionsOpenMin=_connectionsOpen; _connectionsOpenMax=_connectionsOpen; _connectionsOpen=0; _connectionsDurationMin=0; _connectionsDurationMax=0; _connectionsDurationTotal=0; _requests=0; _connectionsRequestsMin=0; _connectionsRequestsMax=0; } /* ------------------------------------------------------------ */ public void setStatsOn(boolean on) { if (on && _statsStartedAt!=-1) return; Log.debug("Statistics on = "+on+" for "+this); statsReset(); _statsStartedAt=on?System.currentTimeMillis():-1; } /* ------------------------------------------------------------ */ /** * @return True if statistics collection is turned on. */ public boolean getStatsOn() { return _statsStartedAt!=-1; } /* ------------------------------------------------------------ */ /** * @return Timestamp stats were started at. */ public long getStatsOnMs() { return (_statsStartedAt!=-1)?(System.currentTimeMillis()-_statsStartedAt):0; } /* ------------------------------------------------------------ */ protected void connectionOpened(HttpConnection connection) { if (_statsStartedAt==-1) return; synchronized(_statsLock) { _connectionsOpen++; if (_connectionsOpen > _connectionsOpenMax) _connectionsOpenMax=_connectionsOpen; } } /* ------------------------------------------------------------ */ protected void connectionClosed(HttpConnection connection) { if (_statsStartedAt>=0) { long duration=System.currentTimeMillis()-connection.getTimeStamp(); int requests=connection.getRequests(); synchronized(_statsLock) { _requests+=requests; _connections++; _connectionsOpen--; _connectionsDurationTotal+=duration; if (_connectionsOpen<0) _connectionsOpen=0; if (_connectionsOpen<_connectionsOpenMin) _connectionsOpenMin=_connectionsOpen; if (_connectionsDurationMin==0 || duration<_connectionsDurationMin) _connectionsDurationMin=duration; if (duration>_connectionsDurationMax) _connectionsDurationMax=duration; if (_connectionsRequestsMin==0 || requests<_connectionsRequestsMin) _connectionsRequestsMin=requests; if (requests>_connectionsRequestsMax) _connectionsRequestsMax=requests; } } connection.destroy(); } /* ------------------------------------------------------------ */ /** * @return the acceptorPriority */ public int getAcceptorPriorityOffset() { return _acceptorPriorityOffset; } /* ------------------------------------------------------------ */ /** * Set the priority offset of the acceptor threads. The priority is adjusted by * this amount (default 0) to either favour the acceptance of new threads and newly active * connections or to favour the handling of already dispatched connections. * @param offset the amount to alter the priority of the acceptor threads. */ public void setAcceptorPriorityOffset(int offset) { _acceptorPriorityOffset=offset; } }
true
true
public void run() { Thread current = Thread.currentThread(); synchronized(AbstractConnector.this) { if (_acceptorThread==null) return; _acceptorThread[_acceptor]=current; } String name =_acceptorThread[_acceptor].getName(); current.setName(name+" - Acceptor"+_acceptor+" "+AbstractConnector.this); int old_priority=current.getPriority(); try { current.setPriority(old_priority-_acceptorPriorityOffset); while (isRunning() && getConnection()!=null) { try { accept(_acceptor); } catch(EofException e) { Log.ignore(e); } catch(IOException e) { Log.ignore(e); } catch(Exception e) { Log.warn(e); } } } finally { current.setPriority(old_priority); current.setName(name); try { if (_acceptor==0) close(); } catch (IOException e) { Log.warn(e); } synchronized(AbstractConnector.this) { if (_acceptorThread!=null) _acceptorThread[_acceptor]=null; } } }
public void run() { Thread current = Thread.currentThread(); synchronized(AbstractConnector.this) { if (_acceptorThread==null) return; _acceptorThread[_acceptor]=current; } String name =_acceptorThread[_acceptor].getName(); current.setName(name+" - Acceptor"+_acceptor+" "+AbstractConnector.this); int old_priority=current.getPriority(); try { current.setPriority(old_priority-_acceptorPriorityOffset); while (isRunning() && getConnection()!=null) { try { accept(_acceptor); } catch(EofException e) { Log.ignore(e); } catch(IOException e) { Log.ignore(e); } catch(ThreadDeath e) { Log.warn(e); throw e; } catch(Throwable e) { Log.warn(e); } } } finally { current.setPriority(old_priority); current.setName(name); try { if (_acceptor==0) close(); } catch (IOException e) { Log.warn(e); } synchronized(AbstractConnector.this) { if (_acceptorThread!=null) _acceptorThread[_acceptor]=null; } } }
diff --git a/src/frontend/org/voltdb/PartitionDRGateway.java b/src/frontend/org/voltdb/PartitionDRGateway.java index a84b10ad3..4e3427efd 100644 --- a/src/frontend/org/voltdb/PartitionDRGateway.java +++ b/src/frontend/org/voltdb/PartitionDRGateway.java @@ -1,96 +1,96 @@ /* This file is part of VoltDB. * Copyright (C) 2008-2013 VoltDB Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with VoltDB. If not, see <http://www.gnu.org/licenses/>. */ package org.voltdb; import java.io.IOException; import java.lang.reflect.Constructor; import org.voltdb.licensetool.LicenseApi; /** * Stub class that provides a gateway to the InvocationBufferServer when * DR is enabled. If no DR, then it acts as a noop stub. * */ public class PartitionDRGateway { protected final boolean m_iv2Enabled; /** * Load the full subclass if it should, otherwise load the * noop stub. * @param partitionId partition id * @param overflowDir * @return Instance of PartitionDRGateway */ public static PartitionDRGateway getInstance(int partitionId, NodeDRGateway nodeGateway, - boolean isRejoin, - boolean iv2Enabled) + boolean iv2Enabled, + boolean isRejoin) { final VoltDBInterface vdb = VoltDB.instance(); LicenseApi api = vdb.getLicenseApi(); final boolean licensedToDR = api.isDrReplicationAllowed(); // if this is a primary cluster in a DR-enabled scenario // try to load the real version of this class PartitionDRGateway pdrg = null; if (licensedToDR && nodeGateway != null) { pdrg = tryToLoadProVersion(iv2Enabled); } if (pdrg == null) { pdrg = new PartitionDRGateway(iv2Enabled); } // init the instance and return try { pdrg.init(partitionId, nodeGateway, isRejoin); } catch (IOException e) { VoltDB.crashLocalVoltDB(e.getMessage(), false, e); } return pdrg; } private static PartitionDRGateway tryToLoadProVersion(boolean iv2Enalbed) { try { Class<?> pdrgiClass = Class.forName("org.voltdb.dr.PartitionDRGatewayImpl"); Constructor<?> constructor = pdrgiClass.getConstructor(boolean.class); Object obj = constructor.newInstance(iv2Enalbed); return (PartitionDRGateway) obj; } catch (Exception e) { } return null; } public PartitionDRGateway(boolean iv2Enabled) { m_iv2Enabled = iv2Enabled; } // empty methods for community edition protected void init(int partitionId, NodeDRGateway gateway, boolean isRejoin) throws IOException {} public void onSuccessfulProcedureCall(long txnId, long uniqueId, int hash, StoredProcedureInvocation spi, ClientResponseImpl response) {} public void onSuccessfulMPCall(long spHandle, long txnId, long uniqueId, int hash, StoredProcedureInvocation spi, ClientResponseImpl response) {} public void tick(long txnId) {} }
true
true
public static PartitionDRGateway getInstance(int partitionId, NodeDRGateway nodeGateway, boolean isRejoin, boolean iv2Enabled) { final VoltDBInterface vdb = VoltDB.instance(); LicenseApi api = vdb.getLicenseApi(); final boolean licensedToDR = api.isDrReplicationAllowed(); // if this is a primary cluster in a DR-enabled scenario // try to load the real version of this class PartitionDRGateway pdrg = null; if (licensedToDR && nodeGateway != null) { pdrg = tryToLoadProVersion(iv2Enabled); } if (pdrg == null) { pdrg = new PartitionDRGateway(iv2Enabled); } // init the instance and return try { pdrg.init(partitionId, nodeGateway, isRejoin); } catch (IOException e) { VoltDB.crashLocalVoltDB(e.getMessage(), false, e); } return pdrg; }
public static PartitionDRGateway getInstance(int partitionId, NodeDRGateway nodeGateway, boolean iv2Enabled, boolean isRejoin) { final VoltDBInterface vdb = VoltDB.instance(); LicenseApi api = vdb.getLicenseApi(); final boolean licensedToDR = api.isDrReplicationAllowed(); // if this is a primary cluster in a DR-enabled scenario // try to load the real version of this class PartitionDRGateway pdrg = null; if (licensedToDR && nodeGateway != null) { pdrg = tryToLoadProVersion(iv2Enabled); } if (pdrg == null) { pdrg = new PartitionDRGateway(iv2Enabled); } // init the instance and return try { pdrg.init(partitionId, nodeGateway, isRejoin); } catch (IOException e) { VoltDB.crashLocalVoltDB(e.getMessage(), false, e); } return pdrg; }
diff --git a/src/com/tactfactory/mda/template/ProviderGenerator.java b/src/com/tactfactory/mda/template/ProviderGenerator.java index 582f4017..1c398976 100644 --- a/src/com/tactfactory/mda/template/ProviderGenerator.java +++ b/src/com/tactfactory/mda/template/ProviderGenerator.java @@ -1,220 +1,220 @@ /** * This file is part of the Harmony package. * * (c) Mickael Gaillard <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ package com.tactfactory.mda.template; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Comparator; import java.util.List; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.Namespace; import org.jdom2.input.SAXBuilder; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import com.google.common.base.CaseFormat; import com.tactfactory.mda.meta.TranslationMetadata; import com.tactfactory.mda.meta.TranslationMetadata.Group; import com.tactfactory.mda.plateforme.BaseAdapter; import com.tactfactory.mda.utils.ConsoleUtils; import com.tactfactory.mda.utils.TactFileUtils; import com.tactfactory.mda.utils.PackageUtils; /** * The provider generator. * */ public class ProviderGenerator extends BaseGenerator { /** The local name space. */ private String localNameSpace; /** The provider name. */ private String nameProvider; /** * Constructor. * @param adapter The adapter to use. * @throws Exception */ public ProviderGenerator(final BaseAdapter adapter) throws Exception { super(adapter); this.nameProvider = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, this.getAppMetas().getName() + "Provider"); this.localNameSpace = this.getAppMetas().getProjectNameSpace().replace('/', '.') + "." + this.getAdapter().getProvider(); this.setDatamodel(this.getAppMetas().toMap(this.getAdapter())); this.getDatamodel().put( TagConstant.LOCAL_NAMESPACE, this.localNameSpace); } /** * Generate the provider. */ public final void generateProvider() { try { this.makeSourceProvider("TemplateProvider.java", this.nameProvider + ".java", false); this.makeSourceProvider("TemplateProviderBase.java", this.nameProvider + "Base.java", true); this.updateManifest(); TranslationMetadata.addDefaultTranslation( "uri_not_supported", "URI not supported", Group.PROVIDER); TranslationMetadata.addDefaultTranslation( "app_provider_name", "Provider of " + this.getAppMetas().getName(), Group.PROVIDER); TranslationMetadata.addDefaultTranslation( "app_provider_description", "Provider of " + this.getAppMetas().getName() + " for acces to data", Group.PROVIDER); new TranslationGenerator(this.getAdapter()).generateStringsXml(); } catch (final Exception e) { ConsoleUtils.displayError(e); } } /** * Make Java Source Code. * * @param template Template path file. * <br/>For list activity is "TemplateListActivity.java" * @param filename The destination file name */ private void makeSourceProvider(final String template, final String filename, final boolean overwrite) { final String fullFilePath = String.format("%s%s/%s", this.getAdapter().getSourcePath(), PackageUtils.extractPath(this.localNameSpace) .toLowerCase(), filename); final String fullTemplatePath = String.format("%s%s", this.getAdapter().getTemplateSourceProviderPath(), template); super.makeSource(fullTemplatePath, fullFilePath, overwrite); } /** * Update Android Manifest. */ private void updateManifest() { final String pathRelatif = String.format("%s.%s", this.localNameSpace, this.nameProvider); // Debug Log ConsoleUtils.displayDebug("Update Manifest : " + pathRelatif); try { // Make engine final SAXBuilder builder = new SAXBuilder(); final File xmlFile = TactFileUtils.makeFile( this.getAdapter().getManifestPathFile()); // Load XML File final Document doc = builder.build(xmlFile); // Load Root element final Element rootNode = doc.getRootElement(); // Load Name space (required for manipulate attributes) final Namespace ns = rootNode.getNamespace("android"); // Find Application Node Element findProvider = null; // Find a element final Element applicationNode = rootNode.getChild("application"); if (applicationNode != null) { // Find Activity Node final List<Element> providers = applicationNode.getChildren("provider"); // Find many elements for (final Element provider : providers) { if (provider.hasAttributes() && provider.getAttributeValue("name", ns) .equals(pathRelatif)) { // Load attribute value findProvider = provider; break; } } // If not found Node, create it if (findProvider == null) { // Create new element findProvider = new Element("provider"); // Add Attributes to element findProvider.setAttribute("name", pathRelatif, ns); applicationNode.addContent(findProvider); } // Set values findProvider.setAttribute("authorities", this.getAppMetas().getProjectNameSpace() - .replace('/', '.') + "provider", + .replace('/', '.') + ".provider", ns); findProvider.setAttribute("label", "@string/app_provider_name", ns); findProvider.setAttribute("description", "@string/app_provider_description", ns); // Clean code applicationNode.sortChildren(new Comparator<Element>() { @Override public int compare(final Element o1, final Element o2) { return o1.getName().compareToIgnoreCase(o2.getName()); } }); } // Write to File final XMLOutputter xmlOutput = new XMLOutputter(); // Make beautiful file with indent !!! xmlOutput.setFormat(Format.getPrettyFormat()); xmlOutput.output(doc, new OutputStreamWriter( new FileOutputStream(xmlFile.getAbsoluteFile()), TactFileUtils.DEFAULT_ENCODING)); } catch (final IOException io) { ConsoleUtils.displayError(io); } catch (final JDOMException e) { ConsoleUtils.displayError(e); } } }
true
true
private void updateManifest() { final String pathRelatif = String.format("%s.%s", this.localNameSpace, this.nameProvider); // Debug Log ConsoleUtils.displayDebug("Update Manifest : " + pathRelatif); try { // Make engine final SAXBuilder builder = new SAXBuilder(); final File xmlFile = TactFileUtils.makeFile( this.getAdapter().getManifestPathFile()); // Load XML File final Document doc = builder.build(xmlFile); // Load Root element final Element rootNode = doc.getRootElement(); // Load Name space (required for manipulate attributes) final Namespace ns = rootNode.getNamespace("android"); // Find Application Node Element findProvider = null; // Find a element final Element applicationNode = rootNode.getChild("application"); if (applicationNode != null) { // Find Activity Node final List<Element> providers = applicationNode.getChildren("provider"); // Find many elements for (final Element provider : providers) { if (provider.hasAttributes() && provider.getAttributeValue("name", ns) .equals(pathRelatif)) { // Load attribute value findProvider = provider; break; } } // If not found Node, create it if (findProvider == null) { // Create new element findProvider = new Element("provider"); // Add Attributes to element findProvider.setAttribute("name", pathRelatif, ns); applicationNode.addContent(findProvider); } // Set values findProvider.setAttribute("authorities", this.getAppMetas().getProjectNameSpace() .replace('/', '.') + "provider", ns); findProvider.setAttribute("label", "@string/app_provider_name", ns); findProvider.setAttribute("description", "@string/app_provider_description", ns); // Clean code applicationNode.sortChildren(new Comparator<Element>() { @Override public int compare(final Element o1, final Element o2) { return o1.getName().compareToIgnoreCase(o2.getName()); } }); } // Write to File final XMLOutputter xmlOutput = new XMLOutputter(); // Make beautiful file with indent !!! xmlOutput.setFormat(Format.getPrettyFormat()); xmlOutput.output(doc, new OutputStreamWriter( new FileOutputStream(xmlFile.getAbsoluteFile()), TactFileUtils.DEFAULT_ENCODING)); } catch (final IOException io) { ConsoleUtils.displayError(io); } catch (final JDOMException e) { ConsoleUtils.displayError(e); } }
private void updateManifest() { final String pathRelatif = String.format("%s.%s", this.localNameSpace, this.nameProvider); // Debug Log ConsoleUtils.displayDebug("Update Manifest : " + pathRelatif); try { // Make engine final SAXBuilder builder = new SAXBuilder(); final File xmlFile = TactFileUtils.makeFile( this.getAdapter().getManifestPathFile()); // Load XML File final Document doc = builder.build(xmlFile); // Load Root element final Element rootNode = doc.getRootElement(); // Load Name space (required for manipulate attributes) final Namespace ns = rootNode.getNamespace("android"); // Find Application Node Element findProvider = null; // Find a element final Element applicationNode = rootNode.getChild("application"); if (applicationNode != null) { // Find Activity Node final List<Element> providers = applicationNode.getChildren("provider"); // Find many elements for (final Element provider : providers) { if (provider.hasAttributes() && provider.getAttributeValue("name", ns) .equals(pathRelatif)) { // Load attribute value findProvider = provider; break; } } // If not found Node, create it if (findProvider == null) { // Create new element findProvider = new Element("provider"); // Add Attributes to element findProvider.setAttribute("name", pathRelatif, ns); applicationNode.addContent(findProvider); } // Set values findProvider.setAttribute("authorities", this.getAppMetas().getProjectNameSpace() .replace('/', '.') + ".provider", ns); findProvider.setAttribute("label", "@string/app_provider_name", ns); findProvider.setAttribute("description", "@string/app_provider_description", ns); // Clean code applicationNode.sortChildren(new Comparator<Element>() { @Override public int compare(final Element o1, final Element o2) { return o1.getName().compareToIgnoreCase(o2.getName()); } }); } // Write to File final XMLOutputter xmlOutput = new XMLOutputter(); // Make beautiful file with indent !!! xmlOutput.setFormat(Format.getPrettyFormat()); xmlOutput.output(doc, new OutputStreamWriter( new FileOutputStream(xmlFile.getAbsoluteFile()), TactFileUtils.DEFAULT_ENCODING)); } catch (final IOException io) { ConsoleUtils.displayError(io); } catch (final JDOMException e) { ConsoleUtils.displayError(e); } }
diff --git a/trunk/test/java/TestVisibility.java b/trunk/test/java/TestVisibility.java index 3c6e113..ddd8d1e 100644 --- a/trunk/test/java/TestVisibility.java +++ b/trunk/test/java/TestVisibility.java @@ -1,95 +1,95 @@ import java.util.List; import org.apache.log4j.Logger; import com.xerox.amazonws.sqs.QueueService; import com.xerox.amazonws.sqs.Message; import com.xerox.amazonws.sqs.MessageQueue; import com.xerox.amazonws.tools.LoggingConfigurator; public class TestVisibility { private static Logger log = LoggingConfigurator.configureLogging(TestVisibility.class); public static void main(String [] args) throws Exception { final String AWSAccessKeyId = "[AWS Access Id]"; final String SecretAccessKey = "[AWS Access Id]"; QueueService qs = new QueueService(AWSAccessKeyId, SecretAccessKey); MessageQueue mq = qs.getOrCreateMessageQueue(args[0]); int timeout = mq.getVisibilityTimeout(); log.debug("Queue timeout = "+timeout); mq.sendMessage("Testing 1, 2, 3"); try { Thread.sleep(5000); } catch (InterruptedException ex) {} Message msg = mq.receiveMessage(); log.debug("Message = "+msg.getMessageBody()); int i=0; long start = System.currentTimeMillis(); while ((msg = mq.receiveMessage()) == null) { log.debug("."); try { Thread.sleep(1000); } catch (InterruptedException ex) {} i++; } long end = System.currentTimeMillis(); log.debug("Message was invisible for "+(end-start)/1000.0+" seconds"); mq.deleteMessage(msg.getMessageId()); // test queue visibility log.debug("setting timeout to 10 seconds."); mq.setVisibilityTimeout(10); mq.sendMessage("Testing 1, 2, 3"); try { Thread.sleep(5000); } catch (InterruptedException ex) {} msg = mq.receiveMessage(); log.debug("Message = "+msg.getMessageBody()); i=0; start = System.currentTimeMillis(); while ((msg = mq.receiveMessage()) == null) { log.debug("."); try { Thread.sleep(1000); } catch (InterruptedException ex) {} i++; } end = System.currentTimeMillis(); log.debug("Message was invisible for "+(end-start)/1000.0+" seconds"); mq.deleteMessage(msg.getMessageId()); // test change message visibility log.debug("setting timeout to 10 seconds."); mq.setVisibilityTimeout(10); String msgId = mq.sendMessage("Testing 1, 2, 3"); try { Thread.sleep(5000); } catch (InterruptedException ex) {} msg = mq.receiveMessage(); log.debug("Message = "+msg.getMessageBody()); i=0; start = System.currentTimeMillis(); while ((msg = mq.receiveMessage()) == null) { log.debug("."); if (i == 4) { log.debug("change timeout to 60 seconds."); - mq.setMessageVisibilityTimeout(msgId, 60); + mq.setVisibilityTimeout(msgId, 60); } try { Thread.sleep(1000); } catch (InterruptedException ex) {} i++; } end = System.currentTimeMillis(); log.debug("Message was invisible for "+(end-start)/1000.0+" seconds"); mq.deleteMessage(msg.getMessageId()); // test receive visibility mq.sendMessage("Testing 1, 2, 3"); try { Thread.sleep(5000); } catch (InterruptedException ex) {} msg = mq.receiveMessage(30); log.debug("Message = "+msg.getMessageBody()); i=0; start = System.currentTimeMillis(); while ((msg = mq.receiveMessage()) == null) { log.debug("."); try { Thread.sleep(1000); } catch (InterruptedException ex) {} i++; } end = System.currentTimeMillis(); log.debug("Message was invisible for "+(end-start)/1000.0+" seconds"); mq.deleteMessage(msg.getMessageId()); // reset queue timeout mq.setVisibilityTimeout(timeout); } }
true
true
public static void main(String [] args) throws Exception { final String AWSAccessKeyId = "[AWS Access Id]"; final String SecretAccessKey = "[AWS Access Id]"; QueueService qs = new QueueService(AWSAccessKeyId, SecretAccessKey); MessageQueue mq = qs.getOrCreateMessageQueue(args[0]); int timeout = mq.getVisibilityTimeout(); log.debug("Queue timeout = "+timeout); mq.sendMessage("Testing 1, 2, 3"); try { Thread.sleep(5000); } catch (InterruptedException ex) {} Message msg = mq.receiveMessage(); log.debug("Message = "+msg.getMessageBody()); int i=0; long start = System.currentTimeMillis(); while ((msg = mq.receiveMessage()) == null) { log.debug("."); try { Thread.sleep(1000); } catch (InterruptedException ex) {} i++; } long end = System.currentTimeMillis(); log.debug("Message was invisible for "+(end-start)/1000.0+" seconds"); mq.deleteMessage(msg.getMessageId()); // test queue visibility log.debug("setting timeout to 10 seconds."); mq.setVisibilityTimeout(10); mq.sendMessage("Testing 1, 2, 3"); try { Thread.sleep(5000); } catch (InterruptedException ex) {} msg = mq.receiveMessage(); log.debug("Message = "+msg.getMessageBody()); i=0; start = System.currentTimeMillis(); while ((msg = mq.receiveMessage()) == null) { log.debug("."); try { Thread.sleep(1000); } catch (InterruptedException ex) {} i++; } end = System.currentTimeMillis(); log.debug("Message was invisible for "+(end-start)/1000.0+" seconds"); mq.deleteMessage(msg.getMessageId()); // test change message visibility log.debug("setting timeout to 10 seconds."); mq.setVisibilityTimeout(10); String msgId = mq.sendMessage("Testing 1, 2, 3"); try { Thread.sleep(5000); } catch (InterruptedException ex) {} msg = mq.receiveMessage(); log.debug("Message = "+msg.getMessageBody()); i=0; start = System.currentTimeMillis(); while ((msg = mq.receiveMessage()) == null) { log.debug("."); if (i == 4) { log.debug("change timeout to 60 seconds."); mq.setMessageVisibilityTimeout(msgId, 60); } try { Thread.sleep(1000); } catch (InterruptedException ex) {} i++; } end = System.currentTimeMillis(); log.debug("Message was invisible for "+(end-start)/1000.0+" seconds"); mq.deleteMessage(msg.getMessageId()); // test receive visibility mq.sendMessage("Testing 1, 2, 3"); try { Thread.sleep(5000); } catch (InterruptedException ex) {} msg = mq.receiveMessage(30); log.debug("Message = "+msg.getMessageBody()); i=0; start = System.currentTimeMillis(); while ((msg = mq.receiveMessage()) == null) { log.debug("."); try { Thread.sleep(1000); } catch (InterruptedException ex) {} i++; } end = System.currentTimeMillis(); log.debug("Message was invisible for "+(end-start)/1000.0+" seconds"); mq.deleteMessage(msg.getMessageId()); // reset queue timeout mq.setVisibilityTimeout(timeout); }
public static void main(String [] args) throws Exception { final String AWSAccessKeyId = "[AWS Access Id]"; final String SecretAccessKey = "[AWS Access Id]"; QueueService qs = new QueueService(AWSAccessKeyId, SecretAccessKey); MessageQueue mq = qs.getOrCreateMessageQueue(args[0]); int timeout = mq.getVisibilityTimeout(); log.debug("Queue timeout = "+timeout); mq.sendMessage("Testing 1, 2, 3"); try { Thread.sleep(5000); } catch (InterruptedException ex) {} Message msg = mq.receiveMessage(); log.debug("Message = "+msg.getMessageBody()); int i=0; long start = System.currentTimeMillis(); while ((msg = mq.receiveMessage()) == null) { log.debug("."); try { Thread.sleep(1000); } catch (InterruptedException ex) {} i++; } long end = System.currentTimeMillis(); log.debug("Message was invisible for "+(end-start)/1000.0+" seconds"); mq.deleteMessage(msg.getMessageId()); // test queue visibility log.debug("setting timeout to 10 seconds."); mq.setVisibilityTimeout(10); mq.sendMessage("Testing 1, 2, 3"); try { Thread.sleep(5000); } catch (InterruptedException ex) {} msg = mq.receiveMessage(); log.debug("Message = "+msg.getMessageBody()); i=0; start = System.currentTimeMillis(); while ((msg = mq.receiveMessage()) == null) { log.debug("."); try { Thread.sleep(1000); } catch (InterruptedException ex) {} i++; } end = System.currentTimeMillis(); log.debug("Message was invisible for "+(end-start)/1000.0+" seconds"); mq.deleteMessage(msg.getMessageId()); // test change message visibility log.debug("setting timeout to 10 seconds."); mq.setVisibilityTimeout(10); String msgId = mq.sendMessage("Testing 1, 2, 3"); try { Thread.sleep(5000); } catch (InterruptedException ex) {} msg = mq.receiveMessage(); log.debug("Message = "+msg.getMessageBody()); i=0; start = System.currentTimeMillis(); while ((msg = mq.receiveMessage()) == null) { log.debug("."); if (i == 4) { log.debug("change timeout to 60 seconds."); mq.setVisibilityTimeout(msgId, 60); } try { Thread.sleep(1000); } catch (InterruptedException ex) {} i++; } end = System.currentTimeMillis(); log.debug("Message was invisible for "+(end-start)/1000.0+" seconds"); mq.deleteMessage(msg.getMessageId()); // test receive visibility mq.sendMessage("Testing 1, 2, 3"); try { Thread.sleep(5000); } catch (InterruptedException ex) {} msg = mq.receiveMessage(30); log.debug("Message = "+msg.getMessageBody()); i=0; start = System.currentTimeMillis(); while ((msg = mq.receiveMessage()) == null) { log.debug("."); try { Thread.sleep(1000); } catch (InterruptedException ex) {} i++; } end = System.currentTimeMillis(); log.debug("Message was invisible for "+(end-start)/1000.0+" seconds"); mq.deleteMessage(msg.getMessageId()); // reset queue timeout mq.setVisibilityTimeout(timeout); }
diff --git a/tests/org.jboss.tools.esb.ui.bot.test/src/org/jboss/tools/esb/ui/bot/tests/editor/action/Notifier.java b/tests/org.jboss.tools.esb.ui.bot.test/src/org/jboss/tools/esb/ui/bot/tests/editor/action/Notifier.java index c37a53f..6f6053c 100644 --- a/tests/org.jboss.tools.esb.ui.bot.test/src/org/jboss/tools/esb/ui/bot/tests/editor/action/Notifier.java +++ b/tests/org.jboss.tools.esb.ui.bot.test/src/org/jboss/tools/esb/ui/bot/tests/editor/action/Notifier.java @@ -1,97 +1,98 @@ package org.jboss.tools.esb.ui.bot.tests.editor.action; import static org.junit.Assert.fail; import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotEditor; import org.eclipse.swtbot.swt.finder.SWTBot; import org.eclipse.swtbot.swt.finder.widgets.SWTBotShell; import org.eclipse.swtbot.swt.finder.widgets.SWTBotTreeItem; import org.jboss.tools.esb.ui.bot.tests.editor.Assertions; import org.jboss.tools.esb.ui.bot.tests.editor.ESBAction; import org.jboss.tools.esb.ui.bot.tests.editor.ESBObject; import org.jboss.tools.esb.ui.bot.tests.editor.ESBObjectDummy; import org.jboss.tools.ui.bot.ext.SWTEclipseExt; import org.jboss.tools.ui.bot.ext.helper.ContextMenuHelper; import org.jboss.tools.ui.bot.ext.types.IDELabel; import org.jboss.tools.ui.bot.ext.widgets.SWTBotSection; public class Notifier extends ESBAction { public Notifier() { super("Notifier","Routers","org.jboss.soa.esb.actions.Notifier"); } protected void doEditing(SWTBotEditor editor, String... path) { SWTBotSection section = bot.section(editor.bot(),getSectionTitle()); editTextProperty(editor, section.bot(), "Ok Method:", "okMethod", "method"); editTextProperty(editor, section.bot(), "Exception Method:", "exceptionMethod", "method"); section = bot.section(editor.bot(),"Notification Lists"); section.bot().button(IDELabel.Button.ADD).click(); SWTBotShell shell = bot.shell("Add Notification List...").activate(); shell.bot().text().setText("list"); shell.bot().button(IDELabel.Button.FINISH).click(); String xpath = getBaseXPath()+getXpath()+"/property[@name='destinations']/NotificationList[@type='list']"; Assertions.assertXmlContentExists(editor.toTextEditor().getText(), xpath); section = bot.section(editor.bot(),"Targets"); editor.save(); String[] notifiersPath = arrayAppend(path, "Notifier","list"); addTarget(editor, xpath, notifiersPath); addNotifier(editor, new ESBObjectDummy("Notify Console", "NotifyConsole"), xpath, notifiersPath); addEmail(editor, xpath, notifiersPath); addNotifier(editor, new ESBObjectDummy("Notify Files", "NotifyFiles"), xpath, notifiersPath); addNotifier(editor, new ESBObjectDummy("Notify FTP", "NotifyFTP"), xpath, notifiersPath); addNotifier(editor, new ESBObjectDummy("Notify FTP List", "NotifyFTPList"), xpath, notifiersPath); addNotifier(editor, new ESBObjectDummy("Notify Queues", "NotifyQueues"), xpath, notifiersPath); addSQL(editor, xpath, notifiersPath); addNotifier(editor, new ESBObjectDummy("Notify TCP", "NotifyTCP"), xpath, notifiersPath); addNotifier(editor, new ESBObjectDummy("Notify Topics", "NotifyTopics"), xpath, notifiersPath); - fail("OK"); + // FIXME full coverage of notifiers + //fail("OK"); } private void addTarget(SWTBotEditor editor,String xpath,String... path) { SWTBotTreeItem item = SWTEclipseExt.selectTreeLocation(editor.bot(), path); ContextMenuHelper.prepareTreeItemForContextMenu(editor.bot().tree(),item); ContextMenuHelper.clickContextMenu(editor.bot().tree(), IDELabel.Menu.NEW,"Target..."); SWTBot shellBot = bot.shell("Add Target").bot(); shellBot.text().setText("java.lang.Object"); shellBot.button(IDELabel.Button.FINISH).click(); editor.save(); xpath+="/target[@class='java.lang.Object']"; Assertions.assertXmlContentExists(editor.toTextEditor().getText(), xpath); } private void addNotifier(SWTBotEditor editor, ESBObject obj,String xpath,String... path) { SWTBotTreeItem item = SWTEclipseExt.selectTreeLocation(editor.bot(), path); ContextMenuHelper.prepareTreeItemForContextMenu(editor.bot().tree(),item); ContextMenuHelper.clickContextMenu(editor.bot().tree(), IDELabel.Menu.NEW,obj.getMenuLabel()); editor.save(); xpath+="/target[@class='"+obj.xmlName+"']"; Assertions.assertXmlContentExists(editor.toTextEditor().getText(), xpath); } private void addEmail(SWTBotEditor editor,String xpath,String... path) { SWTBotTreeItem item = SWTEclipseExt.selectTreeLocation(editor.bot(), path); ContextMenuHelper.prepareTreeItemForContextMenu(editor.bot().tree(),item); ContextMenuHelper.clickContextMenu(editor.bot().tree(), IDELabel.Menu.NEW,"Notify Email..."); SWTBot shellBot = bot.shell("Notify Email...").bot(); shellBot.text(0).setText("a"); shellBot.text(1).setText("b"); shellBot.text(2).setText("c"); shellBot.button(IDELabel.Button.FINISH).click(); editor.save(); xpath+="/target[@class='NotifyEmail' and @from='a' and @sendTo='b' and @subject='c']"; Assertions.assertXmlContentExists(editor.toTextEditor().getText(), xpath); } private void addSQL(SWTBotEditor editor,String xpath,String... path) { SWTBotTreeItem item = SWTEclipseExt.selectTreeLocation(editor.bot(), path); ContextMenuHelper.prepareTreeItemForContextMenu(editor.bot().tree(),item); ContextMenuHelper.clickContextMenu(editor.bot().tree(), IDELabel.Menu.NEW,"Notify SQL Table..."); SWTBot shellBot = bot.shell("Notify SQL Table...").bot(); shellBot.text(1).setText("a"); shellBot.text(2).setText("b"); shellBot.text(3).setText("c"); shellBot.button(IDELabel.Button.FINISH).click(); editor.save(); xpath+="/target[@class='NotifySQLTable' and @driver-class='a' and @connection-url='b' and @user-name='c']"; Assertions.assertXmlContentExists(editor.toTextEditor().getText(), xpath); } }
true
true
protected void doEditing(SWTBotEditor editor, String... path) { SWTBotSection section = bot.section(editor.bot(),getSectionTitle()); editTextProperty(editor, section.bot(), "Ok Method:", "okMethod", "method"); editTextProperty(editor, section.bot(), "Exception Method:", "exceptionMethod", "method"); section = bot.section(editor.bot(),"Notification Lists"); section.bot().button(IDELabel.Button.ADD).click(); SWTBotShell shell = bot.shell("Add Notification List...").activate(); shell.bot().text().setText("list"); shell.bot().button(IDELabel.Button.FINISH).click(); String xpath = getBaseXPath()+getXpath()+"/property[@name='destinations']/NotificationList[@type='list']"; Assertions.assertXmlContentExists(editor.toTextEditor().getText(), xpath); section = bot.section(editor.bot(),"Targets"); editor.save(); String[] notifiersPath = arrayAppend(path, "Notifier","list"); addTarget(editor, xpath, notifiersPath); addNotifier(editor, new ESBObjectDummy("Notify Console", "NotifyConsole"), xpath, notifiersPath); addEmail(editor, xpath, notifiersPath); addNotifier(editor, new ESBObjectDummy("Notify Files", "NotifyFiles"), xpath, notifiersPath); addNotifier(editor, new ESBObjectDummy("Notify FTP", "NotifyFTP"), xpath, notifiersPath); addNotifier(editor, new ESBObjectDummy("Notify FTP List", "NotifyFTPList"), xpath, notifiersPath); addNotifier(editor, new ESBObjectDummy("Notify Queues", "NotifyQueues"), xpath, notifiersPath); addSQL(editor, xpath, notifiersPath); addNotifier(editor, new ESBObjectDummy("Notify TCP", "NotifyTCP"), xpath, notifiersPath); addNotifier(editor, new ESBObjectDummy("Notify Topics", "NotifyTopics"), xpath, notifiersPath); fail("OK"); }
protected void doEditing(SWTBotEditor editor, String... path) { SWTBotSection section = bot.section(editor.bot(),getSectionTitle()); editTextProperty(editor, section.bot(), "Ok Method:", "okMethod", "method"); editTextProperty(editor, section.bot(), "Exception Method:", "exceptionMethod", "method"); section = bot.section(editor.bot(),"Notification Lists"); section.bot().button(IDELabel.Button.ADD).click(); SWTBotShell shell = bot.shell("Add Notification List...").activate(); shell.bot().text().setText("list"); shell.bot().button(IDELabel.Button.FINISH).click(); String xpath = getBaseXPath()+getXpath()+"/property[@name='destinations']/NotificationList[@type='list']"; Assertions.assertXmlContentExists(editor.toTextEditor().getText(), xpath); section = bot.section(editor.bot(),"Targets"); editor.save(); String[] notifiersPath = arrayAppend(path, "Notifier","list"); addTarget(editor, xpath, notifiersPath); addNotifier(editor, new ESBObjectDummy("Notify Console", "NotifyConsole"), xpath, notifiersPath); addEmail(editor, xpath, notifiersPath); addNotifier(editor, new ESBObjectDummy("Notify Files", "NotifyFiles"), xpath, notifiersPath); addNotifier(editor, new ESBObjectDummy("Notify FTP", "NotifyFTP"), xpath, notifiersPath); addNotifier(editor, new ESBObjectDummy("Notify FTP List", "NotifyFTPList"), xpath, notifiersPath); addNotifier(editor, new ESBObjectDummy("Notify Queues", "NotifyQueues"), xpath, notifiersPath); addSQL(editor, xpath, notifiersPath); addNotifier(editor, new ESBObjectDummy("Notify TCP", "NotifyTCP"), xpath, notifiersPath); addNotifier(editor, new ESBObjectDummy("Notify Topics", "NotifyTopics"), xpath, notifiersPath); // FIXME full coverage of notifiers //fail("OK"); }
diff --git a/test/badm/models/BudgetTest.java b/test/badm/models/BudgetTest.java index 17463b7..316ed07 100644 --- a/test/badm/models/BudgetTest.java +++ b/test/badm/models/BudgetTest.java @@ -1,355 +1,355 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package badm.models; import badm.BridgeHelper; import badm.Budget; import badm.Note; import cc.test.bridge.BridgeConstants.Side; import cc.test.bridge.BudgetInterface; import cc.test.bridge.LineInterface; import cc.test.bridge.NoteInterface; import java.util.ArrayList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import org.junit.*; import org.workplicity.task.NetTask; import org.workplicity.util.Helper; import org.workplicity.util.WorkDate; import org.workplicity.worklet.WorkletContext; /** * * @author idontknow5691 */ public class BudgetTest { /** * The store or mongo db name */ public final static String STORE_NAME = "badm"; /** * The scratch pad for Helper */ private static WorkletContext context = WorkletContext.getInstance(); private static Budget budget; public BudgetTest() { } @BeforeClass public static void setUpClass() throws Exception { try { // Set the store name since the default may be be not ours NetTask.setStoreName(STORE_NAME); NetTask.setUrlBase("http://localhost:8080/netprevayle/task"); // Attempt the login if(!Helper.login("admin", "gazelle", context)) fail("login failed"); } catch (Exception e) { fail("failed with exception: " + e); } budget = (Budget) BridgeHelper.getBudgetFactory().create(); budget.setDescription("My Budget"); } @AfterClass public static void tearDownClass() throws Exception { Helper.logout(Helper.whoAmI(context), context); } @Before public void setUp() { } @After public void tearDown() { } @Test public void insert() { System.out.println("insert"); //boolean successful = Helper.insert(budget, budget.getRepositoryName(), context); try{ Boolean insert = budget.commit(); }catch(Exception e){ fail("Hey inserting a budget didn't work"+e); } System.out.println("after failed insert"); System.out.println(Helper.getTicket(context)); } @Test public void fetch() { try { System.out.println("fetch"); System.out.println(Helper.getTicket(context)); String repos = budget.getRepositoryName(); System.out.println(Helper.getTicket(context)); - BudgetInterface fetched_budget = - (Budget) Helper.fetch(repos, budget.getId(), WorkletContext.getInstance()); + Budget fetched_budget = + Budget.find(budget.getId()); if(fetched_budget == null) { fail("budget not found"); } System.out.println("fetched budget description = '"+fetched_budget.getDescription()+"'"); // Verify that the name is what we expect assertEquals(fetched_budget.getDescription(), budget.getDescription()); } catch (Exception e) { fail("failed with exception: " + e); } } /** * Test of getDescription method, of class Budget. */ @Test public void testGetDescription() { System.out.println("getDescription"); Budget instance = new Budget(); String expResult = "this is a description"; instance.setDescription(expResult); String result = instance.getDescription(); assertEquals(expResult, result); } /** * Test of setDescription method, of class Budget. */ @Test public void testSetDescription() { System.out.println("setDescription"); String d = "herpidy derp"; Budget instance = new Budget(); instance.setDescription(d); assertEquals(d, instance.getDescription()); } /** * Test of fetchLines method, of class Budget. */ @Test public void testFetchLines() { System.out.println("fetchLines"); Side side = null; Budget instance = new Budget(); ArrayList expResult = null; ArrayList result = instance.fetchLines(side); assertEquals(expResult, result); // TODO better test } /** * Test of fetchNotes method, of class Budget. */ @Test public void testFetchNotes() { System.out.println("fetchNotes"); Budget instance = new Budget(); ArrayList expResult = null; ArrayList result = instance.fetchNotes(); assertEquals(expResult, result); // TODO better test } /** * Test of createLine method, of class Budget. */ @Test public void testCreateLine() { System.out.println("createLine"); Budget instance = new Budget(); LineInterface expResult = null; LineInterface result = instance.createLine(); assertEquals(expResult, result); // TODO better test } /** * Test of createNote method, of class Budget. */ @Test public void testCreateNote() { System.out.println("createNote"); Budget instance = new Budget(); NoteInterface expResult = null; NoteInterface result = instance.createNote(); assertEquals(expResult, result); // TODO better test } /** * Test of add method, of class Budget. */ @Test public void testAdd_NoteInterface() { System.out.println("add"); NoteInterface ni = new Note(); Budget instance = new Budget(); instance.setId(34); instance.add(ni); Note note = (Note)ni; System.out.println("The notes id is:(drumroll)"+note.getBudgetId()); try { assertEquals(true, note.commit()); } catch (Exception e) { fail("failed with exception: " + e); } } /** * Test of delete method, of class Budget. */ @Test public void testDelete_NoteInterface() { System.out.println("delete"); NoteInterface ni = null; Budget instance = new Budget(); instance.delete(ni); // TODO better test } /** * Test of add method, of class Budget. */ @Test public void testAdd_LineInterface() { System.out.println("add"); LineInterface li = null; Budget instance = new Budget(); instance.add(li); // TODO better test } /** * Test of delete method, of class Budget. */ @Test public void testDelete_LineInterface() { System.out.println("delete"); LineInterface li = null; Budget instance = new Budget(); instance.delete(li); // TODO better test } /** * Test of update method, of class Budget. */ @Test public void testUpdate_LineInterface() { System.out.println("update"); LineInterface li = null; Budget instance = new Budget(); instance.update(li); // TODO better test } /** * Test of update method, of class Budget. */ @Test public void testUpdate_NoteInterface() { System.out.println("update"); NoteInterface ni = null; Budget instance = new Budget(); instance.update(ni); // TODO better test } /** * Test of getId method, of class Budget. */ @Test public void testGetId() { System.out.println("getId"); Budget instance = new Budget(); Integer expResult = -1; Integer result = instance.getId(); assertEquals(expResult, result); } /** * Test of setName method, of class Budget. */ @Test public void testSetName() { System.out.println("setName"); String string = "Testing"; Budget instance = new Budget(); instance.setName(string); assertEquals(instance.getName(), string); } /** * Test of getName method, of class Budget. */ @Test public void testGetName() { System.out.println("getName"); Budget instance = new Budget(); String expResult = "Name"; instance.setName(expResult); String result = instance.getName(); assertEquals(expResult, result); } /** * Test of getUpdateDate method, of class Budget. */ @Test public void testGetUpdateDate() { System.out.println("getUpdateDate"); Budget instance = new Budget(); WorkDate expResult = null; WorkDate result = instance.getUpdateDate(); assertEquals(expResult, result); // TODO better test } /** * Test of commit method, of class Budget. */ @Test public void testCommit() { System.out.println("commit"); Budget instance = new Budget(); Boolean expResult = false; try{ Boolean result = instance.commit(); }catch(Exception e){ fail("Commit failed"+e); } // TODO better test } /** * Test of getRepositoryName method, of class Budget. */ @Test public void testGetRepositoryName() { System.out.println("getRepositoryName"); Budget instance = new Budget(); String expResult = "Budgets"; String result = instance.getRepositoryName(); assertEquals(expResult, result); } }
true
true
public void fetch() { try { System.out.println("fetch"); System.out.println(Helper.getTicket(context)); String repos = budget.getRepositoryName(); System.out.println(Helper.getTicket(context)); BudgetInterface fetched_budget = (Budget) Helper.fetch(repos, budget.getId(), WorkletContext.getInstance()); if(fetched_budget == null) { fail("budget not found"); } System.out.println("fetched budget description = '"+fetched_budget.getDescription()+"'"); // Verify that the name is what we expect assertEquals(fetched_budget.getDescription(), budget.getDescription()); } catch (Exception e) { fail("failed with exception: " + e); } }
public void fetch() { try { System.out.println("fetch"); System.out.println(Helper.getTicket(context)); String repos = budget.getRepositoryName(); System.out.println(Helper.getTicket(context)); Budget fetched_budget = Budget.find(budget.getId()); if(fetched_budget == null) { fail("budget not found"); } System.out.println("fetched budget description = '"+fetched_budget.getDescription()+"'"); // Verify that the name is what we expect assertEquals(fetched_budget.getDescription(), budget.getDescription()); } catch (Exception e) { fail("failed with exception: " + e); } }
diff --git a/bundles/org.eclipse.rap.jface/src/org/eclipse/jface/resource/URLImageDescriptor.java b/bundles/org.eclipse.rap.jface/src/org/eclipse/jface/resource/URLImageDescriptor.java index aa2a437dd..2a44d7c96 100755 --- a/bundles/org.eclipse.rap.jface/src/org/eclipse/jface/resource/URLImageDescriptor.java +++ b/bundles/org.eclipse.rap.jface/src/org/eclipse/jface/resource/URLImageDescriptor.java @@ -1,152 +1,158 @@ /******************************************************************************* * Copyright (c) 2000, 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jface.resource; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jface.util.Policy; import org.eclipse.rwt.graphics.Graphics; import org.eclipse.swt.SWT; import org.eclipse.swt.SWTException; import org.eclipse.swt.graphics.Device; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; /** * An ImageDescriptor that gets its information from a URL. This class is not * public API. Use ImageDescriptor#createFromURL to create a descriptor that * uses a URL. */ class URLImageDescriptor extends ImageDescriptor { /** * Constant for the file protocol for optimized loading */ private static final String FILE_PROTOCOL = "file"; //$NON-NLS-1$ private URL url; /** * Creates a new URLImageDescriptor. * * @param url * The URL to load the image from. Must be non-null. */ URLImageDescriptor(URL url) { this.url = url; } /* * (non-Javadoc) Method declared on Object. */ public boolean equals(Object o) { if (!(o instanceof URLImageDescriptor)) { return false; } return ((URLImageDescriptor) o).url.toExternalForm().equals(this.url.toExternalForm()); } /* * (non-Javadoc) Method declared on ImageDesciptor. Returns null if the * image data cannot be read. */ public ImageData getImageData() { ImageData result = null; InputStream in = getStream(); if (in != null) { try { result = new ImageData(in); } catch (SWTException e) { if (e.code != SWT.ERROR_INVALID_IMAGE) { throw e; // fall through otherwise } } finally { try { in.close(); } catch (IOException e) { Policy.getLog().log( new Status(IStatus.ERROR, Policy.JFACE, e .getLocalizedMessage(), e)); } } } return result; } /** * Returns a stream on the image contents. Returns null if a stream could * not be opened. * * @return the stream for loading the data */ protected InputStream getStream() { try { return new BufferedInputStream(url.openStream()); } catch (IOException e) { return null; } } /* * (non-Javadoc) Method declared on Object. */ public int hashCode() { return url.toExternalForm().hashCode(); } /* * (non-Javadoc) Method declared on Object. */ /** * The <code>URLImageDescriptor</code> implementation of this * <code>Object</code> method returns a string representation of this * object which is suitable only for debugging. */ public String toString() { return "URLImageDescriptor(" + url + ")"; //$NON-NLS-1$ //$NON-NLS-2$ } // RAP [bm] alternative to ImageData for performance reasons public Image createImage( boolean returnMissingImageOnError, Device device ) { String path = url.toString(); String schema = "bundleentry://"; //$NON-NLS-1$ int pos = path.indexOf( schema ); if( pos != -1 ) { path = path.substring( pos + schema.length() ); } schema = "bundleresource://"; //$NON-NLS-1$ pos = path.indexOf( schema ); if( pos != -1 ) { path = path.substring( pos + schema.length() ); } schema = "platform:/"; //$NON-NLS-1$ pos = path.indexOf( schema ); if( pos != -1 ) { path = path.substring( pos + schema.length() ); } - Image image; + Image image = null; InputStream stream = getStream(); - try { - image = Graphics.getImage( path, stream ); - } finally { + if( stream != null ) { try { - stream.close(); - } catch( IOException e ) { - // do nothing + image = Graphics.getImage( path, stream ); + } finally { + try { + stream.close(); + } catch( IOException e ) { + // do nothing + } } + } else if( returnMissingImageOnError ) { + path = "org/eclipse/jface/resource/images/missing_image.png"; //$NON-NLS-1$ + ClassLoader loader = getClass().getClassLoader(); + image = Graphics.getImage( path, loader.getResourceAsStream( path ) ); } return image; } }
false
true
public Image createImage( boolean returnMissingImageOnError, Device device ) { String path = url.toString(); String schema = "bundleentry://"; //$NON-NLS-1$ int pos = path.indexOf( schema ); if( pos != -1 ) { path = path.substring( pos + schema.length() ); } schema = "bundleresource://"; //$NON-NLS-1$ pos = path.indexOf( schema ); if( pos != -1 ) { path = path.substring( pos + schema.length() ); } schema = "platform:/"; //$NON-NLS-1$ pos = path.indexOf( schema ); if( pos != -1 ) { path = path.substring( pos + schema.length() ); } Image image; InputStream stream = getStream(); try { image = Graphics.getImage( path, stream ); } finally { try { stream.close(); } catch( IOException e ) { // do nothing } } return image; }
public Image createImage( boolean returnMissingImageOnError, Device device ) { String path = url.toString(); String schema = "bundleentry://"; //$NON-NLS-1$ int pos = path.indexOf( schema ); if( pos != -1 ) { path = path.substring( pos + schema.length() ); } schema = "bundleresource://"; //$NON-NLS-1$ pos = path.indexOf( schema ); if( pos != -1 ) { path = path.substring( pos + schema.length() ); } schema = "platform:/"; //$NON-NLS-1$ pos = path.indexOf( schema ); if( pos != -1 ) { path = path.substring( pos + schema.length() ); } Image image = null; InputStream stream = getStream(); if( stream != null ) { try { image = Graphics.getImage( path, stream ); } finally { try { stream.close(); } catch( IOException e ) { // do nothing } } } else if( returnMissingImageOnError ) { path = "org/eclipse/jface/resource/images/missing_image.png"; //$NON-NLS-1$ ClassLoader loader = getClass().getClassLoader(); image = Graphics.getImage( path, loader.getResourceAsStream( path ) ); } return image; }
diff --git a/src/main/java/me/cmastudios/plugins/WarhubModChat/WarhubModChat.java b/src/main/java/me/cmastudios/plugins/WarhubModChat/WarhubModChat.java index 9d8e5bc..e0385d1 100644 --- a/src/main/java/me/cmastudios/plugins/WarhubModChat/WarhubModChat.java +++ b/src/main/java/me/cmastudios/plugins/WarhubModChat/WarhubModChat.java @@ -1,419 +1,419 @@ package me.cmastudios.plugins.WarhubModChat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.logging.Logger; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import me.cmastudios.plugins.WarhubModChat.util.*; import me.cmastudios.plugins.WarhubModChat.SLAPI; public class WarhubModChat extends JavaPlugin { Permission permissions = new Permission(); Message messageUtil = new Message(); String version; Logger log = Logger.getLogger("Minecraft"); private final plrLstnr playerListener = new plrLstnr(this); public HashMap<Player, String> channels = new HashMap<Player, String>(); public HashMap<Player, String> ignores = new HashMap<Player, String>(); public HashMap<String, Integer> mutedplrs = new HashMap<String, Integer>(); public HashMap<String, Integer> warnings = new HashMap<String, Integer>(); @Override public void onDisable() { channels.clear(); try { SLAPI.save(warnings, "warnings.bin"); warnings.clear(); SLAPI.save(mutedplrs, "mutedplrs.bin"); mutedplrs.clear(); } catch (Exception e) { log.severe("[WarhubModChat] Failed to save data!"); e.printStackTrace(); } log.info("[WarhubModChat] Disabled!"); } @SuppressWarnings("unchecked") @Override public void onEnable() { permissions.setupPermissions(); Config.setup(); try { warnings = (HashMap<String, Integer>) SLAPI.load("warnings.bin"); mutedplrs = (HashMap<String, Integer>) SLAPI.load("mutedplrs.bin"); } catch (Exception e) { log.severe("[WarhubModChat] Failed to load data!"); e.printStackTrace(); } PluginManager pm = this.getServer().getPluginManager(); pm.registerEvents(playerListener, this); PluginDescriptionFile pdffile = this.getDescription(); version = pdffile.getVersion(); log.info("[WarhubModChat] Version " + version + " by cmastudios enabled!"); } @SuppressWarnings("static-access") public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { Player player = null; if (sender instanceof Player) { player = (Player) sender; } if (cmd.getName().equalsIgnoreCase("modchat")) { if (!permissions.has(player, "warhub.moderator")) { player.sendMessage(ChatColor.RED + "You don't have the permissions to do that!"); return true; } if (args.length < 1) { if (player == null) { log.info("You can't use channels from the console, use '/modchat <message>' to chat."); return true; } channels.put(player, "mod"); player.sendMessage(ChatColor.YELLOW + "Chat switched to mod."); } else { String message = ""; for (String arg : args) { message = message + arg + " "; } if (message.equals("")) return false; if (player == null) { List<Player> sendto = new ArrayList<Player>(); for (Player p : Bukkit.getServer().getOnlinePlayers()) { if (permissions.has(p, "warhub.moderator")) { sendto.add(p); } } for (Player p : sendto) { p.sendMessage(messageUtil.colorizeText(Config .read("modchat-format") .replace("%player", "tommytony") .replace("%message", message))); } log.info("[MODCHAT] tommytony: " + message); sendto.clear(); return true; } if (channels.containsKey(player)) { String channel = channels.remove(player); player.chat(message); channels.put(player, channel); channel = null; } else { channels.put(player, "mod"); player.chat(message); channels.remove(player); } } return true; } if (cmd.getName().equalsIgnoreCase("alert")) { if (player == null) { log.info("You can't use alert from the console, use '/say <message>' to chat."); return true; } if (!permissions.has(player, "warhub.moderator")) { player.sendMessage(ChatColor.RED + "You don't have the permissions to do that!"); return true; } if (args.length < 1) { channels.put(player, "alert"); player.sendMessage(ChatColor.YELLOW + "Chat switched to alert."); } else { String message = ""; for (String arg : args) { message = message + arg + " "; } if (message.equals("")) return false; if (channels.containsKey(player)) { String channel = channels.remove(player); player.chat(message); channels.put(player, channel); channel = null; } else { channels.put(player, "alert"); player.chat(message); channels.remove(player); } } return true; } if (cmd.getName().equalsIgnoreCase("global")) { if (player == null) { log.info("You can't use global from the console, use '/say <message>' to chat."); return true; } if (args.length < 1) { channels.remove(player); player.sendMessage(ChatColor.YELLOW + "Chat switched to global."); } else { String message = ""; for (String arg : args) { message = message + arg + " "; } if (message.equals("")) return false; if (channels.containsKey(player)) { String channel = channels.remove(player); player.chat(message); channels.put(player, channel); channel = null; } else { player.chat(message); } } return true; } if (cmd.getName().equalsIgnoreCase("channel")) { if (player == null) { log.info("You can't use channels from the console, use '/<say/modchat> <message>' to chat."); return true; } if (args.length < 1) { if (!permissions.has(player, "warhub.moderator")) { player.sendMessage(ChatColor.RED + "You're not a mod, and cannot change channels."); return true; } else { player.sendMessage(ChatColor.RED + "Use '/ch <mod/alert/global>' to change your channel."); } return true; } if (args[0].equalsIgnoreCase("mod") || args[0].equalsIgnoreCase("modchat") || args[0].equalsIgnoreCase("m")) { if (!permissions.has(player, "warhub.moderator")) { player.sendMessage(ChatColor.RED + "You don't have the permissions to do that!"); return true; } channels.put(player, "mod"); player.sendMessage(ChatColor.YELLOW + "Chat switched to mod."); return true; } if (args[0].equalsIgnoreCase("a") || args[0].equalsIgnoreCase("alert")) { if (!permissions.has(player, "warhub.moderator")) { player.sendMessage(ChatColor.RED + "You don't have the permissions to do that!"); return true; } channels.put(player, "alert"); player.sendMessage(ChatColor.YELLOW + "Chat switched to alert."); return true; } if (args[0].equalsIgnoreCase("g") || args[0].equalsIgnoreCase("global")) { channels.remove(player); player.sendMessage(ChatColor.YELLOW + "Chat switched to global."); return true; } if (!permissions.has(player, "warhub.moderator")) { player.sendMessage(ChatColor.RED + "You're not a mod, and cannot change channels."); return true; } else { player.sendMessage(ChatColor.RED + "Use '/ch <mod/alert/global>' to change your channel."); } return true; } if (cmd.getName().equalsIgnoreCase("say")) { if (player != null) if (!player.isOp()) { player.sendMessage(ChatColor.RED + "You don't have the permissions to do that!"); return true; } if (args.length == 0) return false; String message = ""; for (String arg : args) { message = message + arg + " "; } if (message.equals("")) return false; this.getServer().broadcastMessage( messageUtil.colorizeText(Config.read("say-format")) .replace("%message", message)); return true; } if (cmd.getName().equalsIgnoreCase("deaf")) { if (args.length < 1) { player.sendMessage(ChatColor.YELLOW + "Deafened players:"); String plrs = ""; for (Player plr : ignores.keySet()) { plrs += plr.getDisplayName() + ", "; } player.sendMessage(ChatColor.YELLOW + plrs); player.sendMessage(ChatColor.YELLOW + "Use /deaf <player> to deafen someone."); return true; } else if (args.length == 1) { Player todeafen = PlayerInfo.toPlayer(args[0]); if (todeafen == player) { if (ignores.containsKey(player)) { ignores.remove(player); todeafen.sendMessage(ChatColor.YELLOW + "You have been undeafened."); } else { ignores.put(player, ""); todeafen.sendMessage(ChatColor.YELLOW + "You have been deafened."); } } else if (player.hasPermission("warhub.moderator")) { if (ignores.containsKey(todeafen)) { ignores.remove(todeafen); player.sendMessage(ChatColor.YELLOW + todeafen.getName() + " has been undeafened."); todeafen.sendMessage(ChatColor.YELLOW + "You have been undeafened."); } else { ignores.put(todeafen, ""); player.sendMessage(ChatColor.YELLOW + todeafen.getName() + " has been deafened."); todeafen.sendMessage(ChatColor.YELLOW + "You have been deafened."); } } else { player.sendMessage(ChatColor.RED + "You do not have permissions to deafen others."); } - return false; + return true; } return false; } if (cmd.getName().equalsIgnoreCase("me")) { if (mutedplrs.containsKey(player.getName())) { player.sendMessage(ChatColor.RED + "You are muted."); return true; } String message = ""; for (String arg : args) { message = message + arg + " "; } if (message == "") return false; if (message == " ") return false; if (message.contains("\u00A7") && !player.hasPermission("warhub.moderator")) { message = message.replaceAll("\u00A7[0-9a-fA-FkK]", ""); } for (Player p : Bukkit.getServer().getOnlinePlayers()) { if (!ignores.containsKey(p)) p.sendMessage("* " + ChatColor.WHITE + player.getDisplayName() + ChatColor.WHITE + " " + message); } return true; } if (cmd.getName().equalsIgnoreCase("mute")) { if (args.length < 1) { player.sendMessage(ChatColor.YELLOW + "Muted players:"); String plrs = ""; for (String plr : mutedplrs.keySet()) { plrs += plr + ", "; } player.sendMessage(ChatColor.YELLOW + plrs); player.sendMessage(ChatColor.YELLOW + "Use /mute <player> to mute someone."); return true; } else if (args.length == 1) { Player todeafen = PlayerInfo.toPlayer(args[0]); if (todeafen == player && player.hasPermission("warhub.moderator")) { if (mutedplrs.containsKey(player.getName())) { mutedplrs.remove(player.getName()); todeafen.sendMessage(ChatColor.YELLOW + "You have been unmuted."); } else { mutedplrs.put(player.getName(), 1); todeafen.sendMessage(ChatColor.YELLOW + "You have been muted."); } } else if (player.hasPermission("warhub.moderator")) { if (mutedplrs.containsKey(todeafen.getName())) { mutedplrs.remove(todeafen.getName()); player.sendMessage(ChatColor.YELLOW + todeafen.getName() + " has been unmuted."); todeafen.sendMessage(ChatColor.YELLOW + "You have been unmuted."); } else { mutedplrs.put(todeafen.getName(), 1); player.sendMessage(ChatColor.YELLOW + todeafen.getName() + " has been muted."); todeafen.sendMessage(ChatColor.YELLOW + "You have been muted."); } } else { player.sendMessage(ChatColor.RED + "You do not have permissions to mute players."); } - return false; + return true; } return false; } return false; } public int parseTimeString(String time) { if (!time.matches("[0-9]*h?[0-9]*m?")) return -1; if (time.matches("[0-9]+")) return Integer.parseInt(time); if (time.matches("[0-9]+m")) return Integer.parseInt(time.split("m")[0]); if (time.matches("[0-9]+h")) return Integer.parseInt(time.split("h")[0]) * 60; if (time.matches("[0-9]+h[0-9]+m")) { String[] split = time.split("[mh]"); return (Integer.parseInt(split[0]) * 60) + Integer.parseInt(split[1]); } return -1; } public String parseMinutes(int minutes) { if (minutes == 1) return "one minute"; if (minutes < 60) return minutes + " minutes"; if (minutes % 60 == 0) { if (minutes / 60 == 1) return "one hour"; else return (minutes / 60) + " hours"; } if (minutes == -1) return "indefinitely"; int m = minutes % 60; int h = (minutes - m) / 60; return h + "h" + m + "m"; } }
false
true
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { Player player = null; if (sender instanceof Player) { player = (Player) sender; } if (cmd.getName().equalsIgnoreCase("modchat")) { if (!permissions.has(player, "warhub.moderator")) { player.sendMessage(ChatColor.RED + "You don't have the permissions to do that!"); return true; } if (args.length < 1) { if (player == null) { log.info("You can't use channels from the console, use '/modchat <message>' to chat."); return true; } channels.put(player, "mod"); player.sendMessage(ChatColor.YELLOW + "Chat switched to mod."); } else { String message = ""; for (String arg : args) { message = message + arg + " "; } if (message.equals("")) return false; if (player == null) { List<Player> sendto = new ArrayList<Player>(); for (Player p : Bukkit.getServer().getOnlinePlayers()) { if (permissions.has(p, "warhub.moderator")) { sendto.add(p); } } for (Player p : sendto) { p.sendMessage(messageUtil.colorizeText(Config .read("modchat-format") .replace("%player", "tommytony") .replace("%message", message))); } log.info("[MODCHAT] tommytony: " + message); sendto.clear(); return true; } if (channels.containsKey(player)) { String channel = channels.remove(player); player.chat(message); channels.put(player, channel); channel = null; } else { channels.put(player, "mod"); player.chat(message); channels.remove(player); } } return true; } if (cmd.getName().equalsIgnoreCase("alert")) { if (player == null) { log.info("You can't use alert from the console, use '/say <message>' to chat."); return true; } if (!permissions.has(player, "warhub.moderator")) { player.sendMessage(ChatColor.RED + "You don't have the permissions to do that!"); return true; } if (args.length < 1) { channels.put(player, "alert"); player.sendMessage(ChatColor.YELLOW + "Chat switched to alert."); } else { String message = ""; for (String arg : args) { message = message + arg + " "; } if (message.equals("")) return false; if (channels.containsKey(player)) { String channel = channels.remove(player); player.chat(message); channels.put(player, channel); channel = null; } else { channels.put(player, "alert"); player.chat(message); channels.remove(player); } } return true; } if (cmd.getName().equalsIgnoreCase("global")) { if (player == null) { log.info("You can't use global from the console, use '/say <message>' to chat."); return true; } if (args.length < 1) { channels.remove(player); player.sendMessage(ChatColor.YELLOW + "Chat switched to global."); } else { String message = ""; for (String arg : args) { message = message + arg + " "; } if (message.equals("")) return false; if (channels.containsKey(player)) { String channel = channels.remove(player); player.chat(message); channels.put(player, channel); channel = null; } else { player.chat(message); } } return true; } if (cmd.getName().equalsIgnoreCase("channel")) { if (player == null) { log.info("You can't use channels from the console, use '/<say/modchat> <message>' to chat."); return true; } if (args.length < 1) { if (!permissions.has(player, "warhub.moderator")) { player.sendMessage(ChatColor.RED + "You're not a mod, and cannot change channels."); return true; } else { player.sendMessage(ChatColor.RED + "Use '/ch <mod/alert/global>' to change your channel."); } return true; } if (args[0].equalsIgnoreCase("mod") || args[0].equalsIgnoreCase("modchat") || args[0].equalsIgnoreCase("m")) { if (!permissions.has(player, "warhub.moderator")) { player.sendMessage(ChatColor.RED + "You don't have the permissions to do that!"); return true; } channels.put(player, "mod"); player.sendMessage(ChatColor.YELLOW + "Chat switched to mod."); return true; } if (args[0].equalsIgnoreCase("a") || args[0].equalsIgnoreCase("alert")) { if (!permissions.has(player, "warhub.moderator")) { player.sendMessage(ChatColor.RED + "You don't have the permissions to do that!"); return true; } channels.put(player, "alert"); player.sendMessage(ChatColor.YELLOW + "Chat switched to alert."); return true; } if (args[0].equalsIgnoreCase("g") || args[0].equalsIgnoreCase("global")) { channels.remove(player); player.sendMessage(ChatColor.YELLOW + "Chat switched to global."); return true; } if (!permissions.has(player, "warhub.moderator")) { player.sendMessage(ChatColor.RED + "You're not a mod, and cannot change channels."); return true; } else { player.sendMessage(ChatColor.RED + "Use '/ch <mod/alert/global>' to change your channel."); } return true; } if (cmd.getName().equalsIgnoreCase("say")) { if (player != null) if (!player.isOp()) { player.sendMessage(ChatColor.RED + "You don't have the permissions to do that!"); return true; } if (args.length == 0) return false; String message = ""; for (String arg : args) { message = message + arg + " "; } if (message.equals("")) return false; this.getServer().broadcastMessage( messageUtil.colorizeText(Config.read("say-format")) .replace("%message", message)); return true; } if (cmd.getName().equalsIgnoreCase("deaf")) { if (args.length < 1) { player.sendMessage(ChatColor.YELLOW + "Deafened players:"); String plrs = ""; for (Player plr : ignores.keySet()) { plrs += plr.getDisplayName() + ", "; } player.sendMessage(ChatColor.YELLOW + plrs); player.sendMessage(ChatColor.YELLOW + "Use /deaf <player> to deafen someone."); return true; } else if (args.length == 1) { Player todeafen = PlayerInfo.toPlayer(args[0]); if (todeafen == player) { if (ignores.containsKey(player)) { ignores.remove(player); todeafen.sendMessage(ChatColor.YELLOW + "You have been undeafened."); } else { ignores.put(player, ""); todeafen.sendMessage(ChatColor.YELLOW + "You have been deafened."); } } else if (player.hasPermission("warhub.moderator")) { if (ignores.containsKey(todeafen)) { ignores.remove(todeafen); player.sendMessage(ChatColor.YELLOW + todeafen.getName() + " has been undeafened."); todeafen.sendMessage(ChatColor.YELLOW + "You have been undeafened."); } else { ignores.put(todeafen, ""); player.sendMessage(ChatColor.YELLOW + todeafen.getName() + " has been deafened."); todeafen.sendMessage(ChatColor.YELLOW + "You have been deafened."); } } else { player.sendMessage(ChatColor.RED + "You do not have permissions to deafen others."); } return false; } return false; } if (cmd.getName().equalsIgnoreCase("me")) { if (mutedplrs.containsKey(player.getName())) { player.sendMessage(ChatColor.RED + "You are muted."); return true; } String message = ""; for (String arg : args) { message = message + arg + " "; } if (message == "") return false; if (message == " ") return false; if (message.contains("\u00A7") && !player.hasPermission("warhub.moderator")) { message = message.replaceAll("\u00A7[0-9a-fA-FkK]", ""); } for (Player p : Bukkit.getServer().getOnlinePlayers()) { if (!ignores.containsKey(p)) p.sendMessage("* " + ChatColor.WHITE + player.getDisplayName() + ChatColor.WHITE + " " + message); } return true; } if (cmd.getName().equalsIgnoreCase("mute")) { if (args.length < 1) { player.sendMessage(ChatColor.YELLOW + "Muted players:"); String plrs = ""; for (String plr : mutedplrs.keySet()) { plrs += plr + ", "; } player.sendMessage(ChatColor.YELLOW + plrs); player.sendMessage(ChatColor.YELLOW + "Use /mute <player> to mute someone."); return true; } else if (args.length == 1) { Player todeafen = PlayerInfo.toPlayer(args[0]); if (todeafen == player && player.hasPermission("warhub.moderator")) { if (mutedplrs.containsKey(player.getName())) { mutedplrs.remove(player.getName()); todeafen.sendMessage(ChatColor.YELLOW + "You have been unmuted."); } else { mutedplrs.put(player.getName(), 1); todeafen.sendMessage(ChatColor.YELLOW + "You have been muted."); } } else if (player.hasPermission("warhub.moderator")) { if (mutedplrs.containsKey(todeafen.getName())) { mutedplrs.remove(todeafen.getName()); player.sendMessage(ChatColor.YELLOW + todeafen.getName() + " has been unmuted."); todeafen.sendMessage(ChatColor.YELLOW + "You have been unmuted."); } else { mutedplrs.put(todeafen.getName(), 1); player.sendMessage(ChatColor.YELLOW + todeafen.getName() + " has been muted."); todeafen.sendMessage(ChatColor.YELLOW + "You have been muted."); } } else { player.sendMessage(ChatColor.RED + "You do not have permissions to mute players."); } return false; } return false; } return false; }
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { Player player = null; if (sender instanceof Player) { player = (Player) sender; } if (cmd.getName().equalsIgnoreCase("modchat")) { if (!permissions.has(player, "warhub.moderator")) { player.sendMessage(ChatColor.RED + "You don't have the permissions to do that!"); return true; } if (args.length < 1) { if (player == null) { log.info("You can't use channels from the console, use '/modchat <message>' to chat."); return true; } channels.put(player, "mod"); player.sendMessage(ChatColor.YELLOW + "Chat switched to mod."); } else { String message = ""; for (String arg : args) { message = message + arg + " "; } if (message.equals("")) return false; if (player == null) { List<Player> sendto = new ArrayList<Player>(); for (Player p : Bukkit.getServer().getOnlinePlayers()) { if (permissions.has(p, "warhub.moderator")) { sendto.add(p); } } for (Player p : sendto) { p.sendMessage(messageUtil.colorizeText(Config .read("modchat-format") .replace("%player", "tommytony") .replace("%message", message))); } log.info("[MODCHAT] tommytony: " + message); sendto.clear(); return true; } if (channels.containsKey(player)) { String channel = channels.remove(player); player.chat(message); channels.put(player, channel); channel = null; } else { channels.put(player, "mod"); player.chat(message); channels.remove(player); } } return true; } if (cmd.getName().equalsIgnoreCase("alert")) { if (player == null) { log.info("You can't use alert from the console, use '/say <message>' to chat."); return true; } if (!permissions.has(player, "warhub.moderator")) { player.sendMessage(ChatColor.RED + "You don't have the permissions to do that!"); return true; } if (args.length < 1) { channels.put(player, "alert"); player.sendMessage(ChatColor.YELLOW + "Chat switched to alert."); } else { String message = ""; for (String arg : args) { message = message + arg + " "; } if (message.equals("")) return false; if (channels.containsKey(player)) { String channel = channels.remove(player); player.chat(message); channels.put(player, channel); channel = null; } else { channels.put(player, "alert"); player.chat(message); channels.remove(player); } } return true; } if (cmd.getName().equalsIgnoreCase("global")) { if (player == null) { log.info("You can't use global from the console, use '/say <message>' to chat."); return true; } if (args.length < 1) { channels.remove(player); player.sendMessage(ChatColor.YELLOW + "Chat switched to global."); } else { String message = ""; for (String arg : args) { message = message + arg + " "; } if (message.equals("")) return false; if (channels.containsKey(player)) { String channel = channels.remove(player); player.chat(message); channels.put(player, channel); channel = null; } else { player.chat(message); } } return true; } if (cmd.getName().equalsIgnoreCase("channel")) { if (player == null) { log.info("You can't use channels from the console, use '/<say/modchat> <message>' to chat."); return true; } if (args.length < 1) { if (!permissions.has(player, "warhub.moderator")) { player.sendMessage(ChatColor.RED + "You're not a mod, and cannot change channels."); return true; } else { player.sendMessage(ChatColor.RED + "Use '/ch <mod/alert/global>' to change your channel."); } return true; } if (args[0].equalsIgnoreCase("mod") || args[0].equalsIgnoreCase("modchat") || args[0].equalsIgnoreCase("m")) { if (!permissions.has(player, "warhub.moderator")) { player.sendMessage(ChatColor.RED + "You don't have the permissions to do that!"); return true; } channels.put(player, "mod"); player.sendMessage(ChatColor.YELLOW + "Chat switched to mod."); return true; } if (args[0].equalsIgnoreCase("a") || args[0].equalsIgnoreCase("alert")) { if (!permissions.has(player, "warhub.moderator")) { player.sendMessage(ChatColor.RED + "You don't have the permissions to do that!"); return true; } channels.put(player, "alert"); player.sendMessage(ChatColor.YELLOW + "Chat switched to alert."); return true; } if (args[0].equalsIgnoreCase("g") || args[0].equalsIgnoreCase("global")) { channels.remove(player); player.sendMessage(ChatColor.YELLOW + "Chat switched to global."); return true; } if (!permissions.has(player, "warhub.moderator")) { player.sendMessage(ChatColor.RED + "You're not a mod, and cannot change channels."); return true; } else { player.sendMessage(ChatColor.RED + "Use '/ch <mod/alert/global>' to change your channel."); } return true; } if (cmd.getName().equalsIgnoreCase("say")) { if (player != null) if (!player.isOp()) { player.sendMessage(ChatColor.RED + "You don't have the permissions to do that!"); return true; } if (args.length == 0) return false; String message = ""; for (String arg : args) { message = message + arg + " "; } if (message.equals("")) return false; this.getServer().broadcastMessage( messageUtil.colorizeText(Config.read("say-format")) .replace("%message", message)); return true; } if (cmd.getName().equalsIgnoreCase("deaf")) { if (args.length < 1) { player.sendMessage(ChatColor.YELLOW + "Deafened players:"); String plrs = ""; for (Player plr : ignores.keySet()) { plrs += plr.getDisplayName() + ", "; } player.sendMessage(ChatColor.YELLOW + plrs); player.sendMessage(ChatColor.YELLOW + "Use /deaf <player> to deafen someone."); return true; } else if (args.length == 1) { Player todeafen = PlayerInfo.toPlayer(args[0]); if (todeafen == player) { if (ignores.containsKey(player)) { ignores.remove(player); todeafen.sendMessage(ChatColor.YELLOW + "You have been undeafened."); } else { ignores.put(player, ""); todeafen.sendMessage(ChatColor.YELLOW + "You have been deafened."); } } else if (player.hasPermission("warhub.moderator")) { if (ignores.containsKey(todeafen)) { ignores.remove(todeafen); player.sendMessage(ChatColor.YELLOW + todeafen.getName() + " has been undeafened."); todeafen.sendMessage(ChatColor.YELLOW + "You have been undeafened."); } else { ignores.put(todeafen, ""); player.sendMessage(ChatColor.YELLOW + todeafen.getName() + " has been deafened."); todeafen.sendMessage(ChatColor.YELLOW + "You have been deafened."); } } else { player.sendMessage(ChatColor.RED + "You do not have permissions to deafen others."); } return true; } return false; } if (cmd.getName().equalsIgnoreCase("me")) { if (mutedplrs.containsKey(player.getName())) { player.sendMessage(ChatColor.RED + "You are muted."); return true; } String message = ""; for (String arg : args) { message = message + arg + " "; } if (message == "") return false; if (message == " ") return false; if (message.contains("\u00A7") && !player.hasPermission("warhub.moderator")) { message = message.replaceAll("\u00A7[0-9a-fA-FkK]", ""); } for (Player p : Bukkit.getServer().getOnlinePlayers()) { if (!ignores.containsKey(p)) p.sendMessage("* " + ChatColor.WHITE + player.getDisplayName() + ChatColor.WHITE + " " + message); } return true; } if (cmd.getName().equalsIgnoreCase("mute")) { if (args.length < 1) { player.sendMessage(ChatColor.YELLOW + "Muted players:"); String plrs = ""; for (String plr : mutedplrs.keySet()) { plrs += plr + ", "; } player.sendMessage(ChatColor.YELLOW + plrs); player.sendMessage(ChatColor.YELLOW + "Use /mute <player> to mute someone."); return true; } else if (args.length == 1) { Player todeafen = PlayerInfo.toPlayer(args[0]); if (todeafen == player && player.hasPermission("warhub.moderator")) { if (mutedplrs.containsKey(player.getName())) { mutedplrs.remove(player.getName()); todeafen.sendMessage(ChatColor.YELLOW + "You have been unmuted."); } else { mutedplrs.put(player.getName(), 1); todeafen.sendMessage(ChatColor.YELLOW + "You have been muted."); } } else if (player.hasPermission("warhub.moderator")) { if (mutedplrs.containsKey(todeafen.getName())) { mutedplrs.remove(todeafen.getName()); player.sendMessage(ChatColor.YELLOW + todeafen.getName() + " has been unmuted."); todeafen.sendMessage(ChatColor.YELLOW + "You have been unmuted."); } else { mutedplrs.put(todeafen.getName(), 1); player.sendMessage(ChatColor.YELLOW + todeafen.getName() + " has been muted."); todeafen.sendMessage(ChatColor.YELLOW + "You have been muted."); } } else { player.sendMessage(ChatColor.RED + "You do not have permissions to mute players."); } return true; } return false; } return false; }
diff --git a/plugins/org.eclipse.dltk.javascript.core/src/org/eclipse/dltk/internal/javascript/typeinference/HostCollection.java b/plugins/org.eclipse.dltk.javascript.core/src/org/eclipse/dltk/internal/javascript/typeinference/HostCollection.java index 8d8970a0..ba371c3b 100644 --- a/plugins/org.eclipse.dltk.javascript.core/src/org/eclipse/dltk/internal/javascript/typeinference/HostCollection.java +++ b/plugins/org.eclipse.dltk.javascript.core/src/org/eclipse/dltk/internal/javascript/typeinference/HostCollection.java @@ -1,317 +1,329 @@ /******************************************************************************* * Copyright (c) 2005, 2007 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * *******************************************************************************/ package org.eclipse.dltk.internal.javascript.typeinference; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.Stack; public class HostCollection { public static final int FUNCTION = 1; public static final int NORMAL = 0; private final HostCollection parent; private final HashMap reference = new HashMap(); private int type; public IReference getReference(String key) { IReference reference2 = (IReference) reference.get(key); if (reference2 == null) if (parent != null) return parent.getReference(key); return reference2; } public static String parseCompletionString(String id, boolean dotBeforeBrackets) { StringBuffer sb = new StringBuffer(); int start = 0; int current = id.length(); Stack inBrackStack = new Stack(); - boolean inString = false; + boolean inStringSingle = false; + boolean inStringDouble = false; for (int i = id.length(); --i >= 0;) { char c = id.charAt(i); - if (c == '\"' || c == '\'') { - if (inString) { - inString = false; + if (c == '\'') { + if (inStringSingle) { + inStringSingle = false; continue; } // end of a string try to skip this. - inString = true; + if (!inStringDouble) + inStringSingle = true; } - if (inString) + if (c == '\"') { + if (inStringDouble) { + inStringDouble = false; + continue; + } + // end of a string try to skip this. + if (!inStringSingle) + inStringDouble = true; + } + if (inStringSingle || inStringDouble) continue; if (c == ']') { if (inBrackStack.isEmpty()) { String brackets = "[]"; if (dotBeforeBrackets && i > 0 && id.charAt(i - 2) != '.') { brackets = ".[]"; } sb.insert(0, brackets + id.substring(i + 1, current)); } inBrackStack.push(new Integer(i)); continue; } if (c == ')') { if (inBrackStack.isEmpty()) { sb.insert(0, id.substring(i + 1, current)); } inBrackStack.push(new Long(i)); continue; } if (c == '[' || c == '(') { if (inBrackStack.isEmpty()) { if (i + 1 < id.length() && id.charAt(i + 1) == c) { // illegal code like [[xx]. try best guess id = id.substring(0, i) + id.substring(i + 1); return parseCompletionString(id, dotBeforeBrackets); } return id.substring(i + 1, current) + sb.toString(); } Object pop = inBrackStack.pop(); if (c == '[' && !(pop instanceof Integer)) { inBrackStack.push(pop); } else if (c == '(' && !(pop instanceof Long)) { inBrackStack.push(pop); } else { current = i; } continue; } if (c != '.' + && inBrackStack.isEmpty() && (Character.isWhitespace(c) || !Character .isJavaIdentifierPart(c))) { start = i + 1; break; } } if (start == 0 && current == id.length() && inBrackStack.isEmpty()) return id; if (!inBrackStack.isEmpty()) { // illegal code like []] Number last = (Number) inBrackStack.pop(); id = id.substring(start, last.intValue()) + id.substring(last.intValue() + 1, id.length()); return parseCompletionString(id, dotBeforeBrackets); } sb.insert(0, id.substring(start, current)); return sb.toString(); } public Set queryElements(String completion, boolean useGlobal) { completion = parseCompletionString(completion, false); IReference r = getReference(completion); HashSet res = new HashSet(); if (r != null) { res.add(r); return res; } int pos = completion.indexOf('.'); if (pos == -1) return res; String rootName = completion.substring(0, pos); r = (IReference) getReference(rootName); pos += 1; String field; while (pos != 0) { if (r == null) return new HashSet(); int k = completion.indexOf('.', pos); if (k == -1) field = completion.substring(pos); else field = completion.substring(pos, k); r = r.getChild(field, useGlobal); pos = k + 1; } if (r == null) return res; res.add(r); return res; } public HostCollection(HostCollection parent) { super(); this.parent = parent; } public Map getReferences() { return reference; } public void write(String key, IReference ref) { if (ref == null) throw new IllegalArgumentException(); reference.put(key, ref); } public void add(String key, IReference ref) { if (ref == null) throw new IllegalArgumentException(); Object object = reference.get(key); if (object == null) { reference.put(key, ref); } else if (object != ref) { if (object instanceof CombinedOrReference) { ((CombinedOrReference) object).addReference(ref); return; } else if (ref instanceof TransparentRef) { if (((TransparentRef) ref).evaluateReference == object) { reference.put(key, ref); return; } } if (object instanceof TransparentRef && ((TransparentRef) object).evaluateReference instanceof CombinedOrReference) { ((CombinedOrReference) ((TransparentRef) object).evaluateReference) .addReference(ref); return; } else if (ref instanceof CombinedOrReference) { ((CombinedOrReference) ref).addReference((IReference) object); } else { CombinedOrReference cor = new CombinedOrReference(); cor.addReference(ref); cor.addReference((IReference) object); ref = cor; } reference.put(key, ref); } } public void oneOf(String key, IReference ref, IReference other) { if (ref == null) throw new IllegalArgumentException(); if (other == null) throw new IllegalArgumentException(); if (ref.isChildishReference() || other.isChildishReference()) { add(key, ref); add(key, other); } else { if (ref instanceof CombinedOrReference) { CombinedOrReference orReference = ((CombinedOrReference) ref); orReference.addReference(other); reference.put(key, ref); } else if (other instanceof CombinedOrReference) { CombinedOrReference orReference = ((CombinedOrReference) other); orReference.addReference(ref); reference.put(key, other); } else { CombinedOrReference cor = new CombinedOrReference(); cor.addReference(ref); cor.addReference(other); reference.put(key, cor); } } } public HostCollection getParent() { return parent; } public void mergeIf(HostCollection cl) { Iterator i = cl.reference.keySet().iterator(); while (i.hasNext()) { Object next = i.next(); if (next instanceof String) { String s = (String) next; IReference rm = (IReference) cl.reference.get(s); add(s, rm); } } cl.pach(this); } public void mergeElseIf(HostCollection cl, HostCollection cl1) { HashSet sm = new HashSet(cl.reference.keySet()); sm.retainAll(cl1.reference.keySet()); Iterator i = sm.iterator(); while (i.hasNext()) { String s = (String) i.next(); IReference rm = (IReference) cl.reference.get(s); IReference rm1 = (IReference) cl1.reference.get(s); oneOf(s, rm, rm1); } cl1.pach(this); cl.pach(this); } public void override(HostCollection other) { reference.putAll(other.reference); } public void setReference(String objId, IReference root) { this.reference.put(objId, root); } public IReference getReferenceNoParentContext(String rootName) { return (IReference) this.reference.get(rootName); } public IReference queryElement(String key1, boolean useGlobal) { Set queryElement = this.queryElements(key1, useGlobal); if (queryElement.isEmpty()) return null; return (IReference) queryElement.iterator().next(); } HashSet transparent = new HashSet(); public void addTransparent(TransparentRef transparentRef) { transparent.add(transparentRef); } private void pach(HostCollection col) { Iterator iterator = transparent.iterator(); while (iterator.hasNext()) { TransparentRef next = (TransparentRef) iterator.next(); next.patchRef(col); } } public void recordDelete(String objId) { reference.remove(objId); } private String name; public void setName(String functionName) { this.name = functionName; } public String getName() { return name; } public int getType() { return type; } public void setType(int type) { this.type = type; } public void recordFunction(Object function, HostCollection collection) { reference.put(function, collection); } public HostCollection getFunction(Object funObject) { return (HostCollection) reference.get(funObject); } }
false
true
public static String parseCompletionString(String id, boolean dotBeforeBrackets) { StringBuffer sb = new StringBuffer(); int start = 0; int current = id.length(); Stack inBrackStack = new Stack(); boolean inString = false; for (int i = id.length(); --i >= 0;) { char c = id.charAt(i); if (c == '\"' || c == '\'') { if (inString) { inString = false; continue; } // end of a string try to skip this. inString = true; } if (inString) continue; if (c == ']') { if (inBrackStack.isEmpty()) { String brackets = "[]"; if (dotBeforeBrackets && i > 0 && id.charAt(i - 2) != '.') { brackets = ".[]"; } sb.insert(0, brackets + id.substring(i + 1, current)); } inBrackStack.push(new Integer(i)); continue; } if (c == ')') { if (inBrackStack.isEmpty()) { sb.insert(0, id.substring(i + 1, current)); } inBrackStack.push(new Long(i)); continue; } if (c == '[' || c == '(') { if (inBrackStack.isEmpty()) { if (i + 1 < id.length() && id.charAt(i + 1) == c) { // illegal code like [[xx]. try best guess id = id.substring(0, i) + id.substring(i + 1); return parseCompletionString(id, dotBeforeBrackets); } return id.substring(i + 1, current) + sb.toString(); } Object pop = inBrackStack.pop(); if (c == '[' && !(pop instanceof Integer)) { inBrackStack.push(pop); } else if (c == '(' && !(pop instanceof Long)) { inBrackStack.push(pop); } else { current = i; } continue; } if (c != '.' && (Character.isWhitespace(c) || !Character .isJavaIdentifierPart(c))) { start = i + 1; break; } } if (start == 0 && current == id.length() && inBrackStack.isEmpty()) return id; if (!inBrackStack.isEmpty()) { // illegal code like []] Number last = (Number) inBrackStack.pop(); id = id.substring(start, last.intValue()) + id.substring(last.intValue() + 1, id.length()); return parseCompletionString(id, dotBeforeBrackets); } sb.insert(0, id.substring(start, current)); return sb.toString(); }
public static String parseCompletionString(String id, boolean dotBeforeBrackets) { StringBuffer sb = new StringBuffer(); int start = 0; int current = id.length(); Stack inBrackStack = new Stack(); boolean inStringSingle = false; boolean inStringDouble = false; for (int i = id.length(); --i >= 0;) { char c = id.charAt(i); if (c == '\'') { if (inStringSingle) { inStringSingle = false; continue; } // end of a string try to skip this. if (!inStringDouble) inStringSingle = true; } if (c == '\"') { if (inStringDouble) { inStringDouble = false; continue; } // end of a string try to skip this. if (!inStringSingle) inStringDouble = true; } if (inStringSingle || inStringDouble) continue; if (c == ']') { if (inBrackStack.isEmpty()) { String brackets = "[]"; if (dotBeforeBrackets && i > 0 && id.charAt(i - 2) != '.') { brackets = ".[]"; } sb.insert(0, brackets + id.substring(i + 1, current)); } inBrackStack.push(new Integer(i)); continue; } if (c == ')') { if (inBrackStack.isEmpty()) { sb.insert(0, id.substring(i + 1, current)); } inBrackStack.push(new Long(i)); continue; } if (c == '[' || c == '(') { if (inBrackStack.isEmpty()) { if (i + 1 < id.length() && id.charAt(i + 1) == c) { // illegal code like [[xx]. try best guess id = id.substring(0, i) + id.substring(i + 1); return parseCompletionString(id, dotBeforeBrackets); } return id.substring(i + 1, current) + sb.toString(); } Object pop = inBrackStack.pop(); if (c == '[' && !(pop instanceof Integer)) { inBrackStack.push(pop); } else if (c == '(' && !(pop instanceof Long)) { inBrackStack.push(pop); } else { current = i; } continue; } if (c != '.' && inBrackStack.isEmpty() && (Character.isWhitespace(c) || !Character .isJavaIdentifierPart(c))) { start = i + 1; break; } } if (start == 0 && current == id.length() && inBrackStack.isEmpty()) return id; if (!inBrackStack.isEmpty()) { // illegal code like []] Number last = (Number) inBrackStack.pop(); id = id.substring(start, last.intValue()) + id.substring(last.intValue() + 1, id.length()); return parseCompletionString(id, dotBeforeBrackets); } sb.insert(0, id.substring(start, current)); return sb.toString(); }
diff --git a/src/test/java/org/agilos/zendesk_jira_plugin/integrationtest/fixtures/JIRAFixture.java b/src/test/java/org/agilos/zendesk_jira_plugin/integrationtest/fixtures/JIRAFixture.java index 0276139..8ff260b 100644 --- a/src/test/java/org/agilos/zendesk_jira_plugin/integrationtest/fixtures/JIRAFixture.java +++ b/src/test/java/org/agilos/zendesk_jira_plugin/integrationtest/fixtures/JIRAFixture.java @@ -1,166 +1,166 @@ package org.agilos.zendesk_jira_plugin.integrationtest.fixtures; import it.org.agilos.zendesk_jira_plugin.integrationtest.JIRAClient; import java.io.File; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import junit.framework.AssertionFailedError; import net.sourceforge.jwebunit.WebTester; import org.agilos.jira.soapclient.RemoteException; import org.agilos.jira.soapclient.RemoteGroup; import org.agilos.jira.soapclient.RemotePermissionScheme; import org.agilos.jira.soapclient.RemoteProject; import org.agilos.jira.soapclient.RemoteUser; import org.apache.log4j.Logger; /** * Parent fixture for access to a JIRA instance. */ public class JIRAFixture { protected RemoteProject project; Map<String, RemoteUser> userMap = new HashMap<String, RemoteUser>(); Map<String, RemoteProject> projectMap = new HashMap<String, RemoteProject>(); protected JIRAClient jiraClient; private Logger log = Logger.getLogger(JIRAFixture.class.getName()); public static final String JIRA_ADMINISTRATORS = "jira-administrators"; public static final String JIRA_DEVELOPERS = "jira-developers"; public static final String JIRA_USERS = "jira-users"; private static final char FS = File.separatorChar; protected WebTester tester; public JIRAFixture() { jiraClient = JIRAClient.instance(); tester = jiraClient.getFuncTestHelperFactory().getTester(); } /** * Connects to JIRA */ public void connect() { jiraClient.login(); } public RemoteProject createProjectWithKeyAndNameAndLead(String key, String projectName, String ProjectLead) throws Exception { log.info("Creating project: "+key+" "+projectName); try { project = jiraClient.getService().createProject(jiraClient.getToken(), key, projectName, "", null, ProjectLead, new RemotePermissionScheme(null, new Long(0), null, null, null), null, null); } catch (RemoteException re) { // Let's add the user to the user map in case he already exists. This will cause the teardown to delete the user. log.error("Failed to create project "+key, re); if( re.getFaultReason().equals("com.atlassian.jira.rpc.exception.RemoteValidationException: A project with that project key already exists.")) { projectMap.put(key, null); } throw re; } projectMap.put(project.getKey(), project); return project; } public void removeProject(String key) throws Exception { log.info("Deleting project: "+key+" "+projectMap.get(key)); jiraClient.getService().deleteProject(jiraClient.getToken(), key); } /** * Creates user and adds the user to the developers role (to enable editing permission) * @param name * @throws Exception */ public void createUserWithUsername(String name) throws Exception { log.info("Creating user: "+name); RemoteUser user = null; try { user = jiraClient.getService().createUser(jiraClient.getToken(), name, name+"-pw", "Test User "+name, name+"@nowhere.test"); } catch (RemoteException re) { // Let's add the user to the user map in case he already exists. This will cause the teardown to delete the user. log.error("Failed to create user "+name, re); if( re.getFaultReason().equals("com.atlassian.jira.rpc.exception.RemoteValidationException: user for this name already exists, please choose a different user name")) { userMap.put(name, null); } throw re; } userMap.put(name, user); log.debug("Adding "+name+" to "+JIRA_DEVELOPERS); addUserToGroup(name, JIRA_DEVELOPERS); } public void removeUser(String name) throws Exception { log.info("Removing user: "+name); jiraClient.getService().deleteUser(jiraClient.getToken(), name); } public void addUserToGroup(String userName, String groupName) throws Exception { log.info("Adding user: "+userName+" to group: "+groupName); RemoteGroup group = jiraClient.getService().getGroup(jiraClient.getToken(), groupName); RemoteUser user = jiraClient.getService().getUser(jiraClient.getToken(), userName); jiraClient.getService().addUserToGroup(jiraClient.getToken(), group, user); } public void removeUserFromGroup(String userName, String groupName) throws Exception { log.info("Removing user: "+userName+" from group: "+groupName); RemoteGroup group = jiraClient.getService().getGroup(jiraClient.getToken(), groupName); RemoteUser user = jiraClient.getService().getUser(jiraClient.getToken(), userName); jiraClient.getService().removeUserFromGroup(jiraClient.getToken(), group, user); } //Needs to exterminate all data before each test to ensure a stable test environment public void cleanData() { Iterator<String> projectKeyIterator = projectMap.keySet().iterator(); while (projectKeyIterator.hasNext()) { String projectKey = projectKeyIterator.next(); try { removeProject(projectKey); } catch (Exception e) { log.error("Failed to clean project: "+projectKey); } } Iterator<String> userIDIterator = userMap.keySet().iterator(); while (userIDIterator.hasNext()) { String userID = userIDIterator.next(); try { removeUser(userID); } catch (Exception e) { log.error("Failed to clean user: "+userID); } } } /** * Loads data from the indicated backup file into JIRA. The file should be located in the <code>jira.xml.data.location</code> directory indicated in the * localtest.properties file (Generated during the pre-integration-test phase and located in the test-classes folder ). * * Handles two cases, either a initial setup of JIRA, or a XML restore in a already configured JIRA. */ public void loadData (String fileName) { String filePath = jiraClient.getFuncTestHelperFactory().getEnvironmentData().getXMLDataLocation().getAbsolutePath() + FS + fileName; String JIRAHomeDir = jiraClient.getFuncTestHelperFactory().getEnvironmentData().getJIRAHomeLocation().getAbsolutePath(); try { if (tester.getDialog().getResponsePageTitle().indexOf("JIRA installation") != -1) { tester.gotoPage("secure/SetupImport!default.jspa"); tester.setWorkingForm("jiraform"); tester.setFormElement("filename", filePath); tester.setFormElement("indexPath", JIRAHomeDir + FS + "indexes"); tester.submit(); tester.assertTextPresent("Setup is now complete."); } else { jiraClient.getFuncTestHelperFactory().getNavigation().login("admin", "admin");// GUI login with default user tester.gotoPage("secure/admin/XmlRestore!default.jspa"); tester.setWorkingForm("jiraform"); tester.setFormElement("filename", filePath); tester.submit(); tester.assertTextPresent("Your project has been successfully imported"); } log.info("Restored data from '" + filePath + "'"); } catch(AssertionFailedError e) { - throw new AssertionError("Your project failed to import successfully. See logs for details"); + throw new RuntimeException("Your project failed to import successfully. See logs for details", e); } } }
true
true
public void loadData (String fileName) { String filePath = jiraClient.getFuncTestHelperFactory().getEnvironmentData().getXMLDataLocation().getAbsolutePath() + FS + fileName; String JIRAHomeDir = jiraClient.getFuncTestHelperFactory().getEnvironmentData().getJIRAHomeLocation().getAbsolutePath(); try { if (tester.getDialog().getResponsePageTitle().indexOf("JIRA installation") != -1) { tester.gotoPage("secure/SetupImport!default.jspa"); tester.setWorkingForm("jiraform"); tester.setFormElement("filename", filePath); tester.setFormElement("indexPath", JIRAHomeDir + FS + "indexes"); tester.submit(); tester.assertTextPresent("Setup is now complete."); } else { jiraClient.getFuncTestHelperFactory().getNavigation().login("admin", "admin");// GUI login with default user tester.gotoPage("secure/admin/XmlRestore!default.jspa"); tester.setWorkingForm("jiraform"); tester.setFormElement("filename", filePath); tester.submit(); tester.assertTextPresent("Your project has been successfully imported"); } log.info("Restored data from '" + filePath + "'"); } catch(AssertionFailedError e) { throw new AssertionError("Your project failed to import successfully. See logs for details"); } }
public void loadData (String fileName) { String filePath = jiraClient.getFuncTestHelperFactory().getEnvironmentData().getXMLDataLocation().getAbsolutePath() + FS + fileName; String JIRAHomeDir = jiraClient.getFuncTestHelperFactory().getEnvironmentData().getJIRAHomeLocation().getAbsolutePath(); try { if (tester.getDialog().getResponsePageTitle().indexOf("JIRA installation") != -1) { tester.gotoPage("secure/SetupImport!default.jspa"); tester.setWorkingForm("jiraform"); tester.setFormElement("filename", filePath); tester.setFormElement("indexPath", JIRAHomeDir + FS + "indexes"); tester.submit(); tester.assertTextPresent("Setup is now complete."); } else { jiraClient.getFuncTestHelperFactory().getNavigation().login("admin", "admin");// GUI login with default user tester.gotoPage("secure/admin/XmlRestore!default.jspa"); tester.setWorkingForm("jiraform"); tester.setFormElement("filename", filePath); tester.submit(); tester.assertTextPresent("Your project has been successfully imported"); } log.info("Restored data from '" + filePath + "'"); } catch(AssertionFailedError e) { throw new RuntimeException("Your project failed to import successfully. See logs for details", e); } }
diff --git a/iwsn/runtime.wsn-app/src/main/java/de/uniluebeck/itm/tr/runtime/wsnapp/WSNDeviceAppConnectorFactory.java b/iwsn/runtime.wsn-app/src/main/java/de/uniluebeck/itm/tr/runtime/wsnapp/WSNDeviceAppConnectorFactory.java index 77476ec3..015ae272 100644 --- a/iwsn/runtime.wsn-app/src/main/java/de/uniluebeck/itm/tr/runtime/wsnapp/WSNDeviceAppConnectorFactory.java +++ b/iwsn/runtime.wsn-app/src/main/java/de/uniluebeck/itm/tr/runtime/wsnapp/WSNDeviceAppConnectorFactory.java @@ -1,99 +1,99 @@ /********************************************************************************************************************** * Copyright (c) 2010, Institute of Telematics, University of Luebeck * * All rights reserved. * * * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * * following conditions are met: * * * * - Redistributions of source code must retain the above copyright notice, this list of conditions and the following * * disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the * * following disclaimer in the documentation and/or other materials provided with the distribution. * * - Neither the name of the University of Luebeck nor the names of its contributors may be used to endorse or promote* * products derived from this software without specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * **********************************************************************************************************************/ package de.uniluebeck.itm.tr.runtime.wsnapp; import de.uniluebeck.itm.gtr.common.SchedulerService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class WSNDeviceAppConnectorFactory { private static final Logger log = LoggerFactory.getLogger(WSNDeviceAppConnectorFactory.class); public static WSNDeviceAppConnector create(final String nodeUrn, final String nodeType, final String nodeUSBChipID, final String nodeSerialInterface, final Integer timeoutNodeAPI, final Integer maximumMessageRate, final SchedulerService schedulerService, final Integer timeoutReset, final Integer timeoutFlash) { // TODO remove this temporary driver switch as soon as the new drivers can replace the old ones boolean isLocal = "isense".equals(nodeType) || "telosb".equals(nodeType) || "pacemate".equals(nodeType) || "mock".equals(nodeType); if (isLocal) { - boolean newDrivers = System.getProperties().containsValue("testbed.newdrivers"); + boolean newDrivers = System.getProperties().containsKey("testbed.newdrivers"); if (newDrivers) { log.debug("{} => Using new drivers", nodeUrn); return new WSNDeviceAppConnectorLocalNew( nodeUrn, nodeType, nodeUSBChipID, nodeSerialInterface, timeoutNodeAPI, maximumMessageRate, schedulerService, timeoutReset, timeoutFlash ); } else { log.debug("{} => Using old drivers", nodeUrn); return new WSNDeviceAppConnectorLocal( nodeUrn, nodeType, nodeUSBChipID, nodeSerialInterface, timeoutNodeAPI, maximumMessageRate, schedulerService, timeoutReset, timeoutFlash ); } } else if ("isense-motap".equals(nodeType)) { return new WSNDeviceAppConnectorRemote( nodeUrn, nodeType, timeoutNodeAPI, schedulerService, timeoutReset, timeoutFlash ); } throw new RuntimeException("Unknown device type!"); } }
true
true
public static WSNDeviceAppConnector create(final String nodeUrn, final String nodeType, final String nodeUSBChipID, final String nodeSerialInterface, final Integer timeoutNodeAPI, final Integer maximumMessageRate, final SchedulerService schedulerService, final Integer timeoutReset, final Integer timeoutFlash) { // TODO remove this temporary driver switch as soon as the new drivers can replace the old ones boolean isLocal = "isense".equals(nodeType) || "telosb".equals(nodeType) || "pacemate".equals(nodeType) || "mock".equals(nodeType); if (isLocal) { boolean newDrivers = System.getProperties().containsValue("testbed.newdrivers"); if (newDrivers) { log.debug("{} => Using new drivers", nodeUrn); return new WSNDeviceAppConnectorLocalNew( nodeUrn, nodeType, nodeUSBChipID, nodeSerialInterface, timeoutNodeAPI, maximumMessageRate, schedulerService, timeoutReset, timeoutFlash ); } else { log.debug("{} => Using old drivers", nodeUrn); return new WSNDeviceAppConnectorLocal( nodeUrn, nodeType, nodeUSBChipID, nodeSerialInterface, timeoutNodeAPI, maximumMessageRate, schedulerService, timeoutReset, timeoutFlash ); } } else if ("isense-motap".equals(nodeType)) { return new WSNDeviceAppConnectorRemote( nodeUrn, nodeType, timeoutNodeAPI, schedulerService, timeoutReset, timeoutFlash ); } throw new RuntimeException("Unknown device type!"); }
public static WSNDeviceAppConnector create(final String nodeUrn, final String nodeType, final String nodeUSBChipID, final String nodeSerialInterface, final Integer timeoutNodeAPI, final Integer maximumMessageRate, final SchedulerService schedulerService, final Integer timeoutReset, final Integer timeoutFlash) { // TODO remove this temporary driver switch as soon as the new drivers can replace the old ones boolean isLocal = "isense".equals(nodeType) || "telosb".equals(nodeType) || "pacemate".equals(nodeType) || "mock".equals(nodeType); if (isLocal) { boolean newDrivers = System.getProperties().containsKey("testbed.newdrivers"); if (newDrivers) { log.debug("{} => Using new drivers", nodeUrn); return new WSNDeviceAppConnectorLocalNew( nodeUrn, nodeType, nodeUSBChipID, nodeSerialInterface, timeoutNodeAPI, maximumMessageRate, schedulerService, timeoutReset, timeoutFlash ); } else { log.debug("{} => Using old drivers", nodeUrn); return new WSNDeviceAppConnectorLocal( nodeUrn, nodeType, nodeUSBChipID, nodeSerialInterface, timeoutNodeAPI, maximumMessageRate, schedulerService, timeoutReset, timeoutFlash ); } } else if ("isense-motap".equals(nodeType)) { return new WSNDeviceAppConnectorRemote( nodeUrn, nodeType, timeoutNodeAPI, schedulerService, timeoutReset, timeoutFlash ); } throw new RuntimeException("Unknown device type!"); }
diff --git a/ImportPlugin/src/org/gephi/io/importer/plugin/file/ImporterGraphML.java b/ImportPlugin/src/org/gephi/io/importer/plugin/file/ImporterGraphML.java index 84a7c3184..204a5ae34 100644 --- a/ImportPlugin/src/org/gephi/io/importer/plugin/file/ImporterGraphML.java +++ b/ImportPlugin/src/org/gephi/io/importer/plugin/file/ImporterGraphML.java @@ -1,687 +1,687 @@ /* Copyright 2008-2010 Gephi Authors : Mathieu Bastian <[email protected]> Website : http://www.gephi.org This file is part of Gephi. Gephi is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Gephi is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Gephi. If not, see <http://www.gnu.org/licenses/>. */ package org.gephi.io.importer.plugin.file; import java.io.Reader; import java.util.HashMap; import javax.xml.stream.Location; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLReporter; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.events.XMLEvent; import org.gephi.data.attributes.api.AttributeColumn; import org.gephi.data.attributes.api.AttributeOrigin; import org.gephi.data.attributes.api.AttributeType; import org.gephi.io.importer.api.ContainerLoader; import org.gephi.io.importer.api.EdgeDefault; import org.gephi.io.importer.api.EdgeDraft; import org.gephi.io.importer.api.Issue; import org.gephi.io.importer.api.NodeDraft; import org.gephi.io.importer.api.PropertiesAssociations; import org.gephi.io.importer.api.PropertiesAssociations.EdgeProperties; import org.gephi.io.importer.api.PropertiesAssociations.NodeProperties; import org.gephi.io.importer.api.Report; import org.gephi.io.importer.spi.FileImporter; import org.gephi.utils.longtask.spi.LongTask; import org.gephi.utils.progress.Progress; import org.gephi.utils.progress.ProgressTicket; import org.openide.util.NbBundle; /** * * @author Mathieu Bastian */ public class ImporterGraphML implements FileImporter, LongTask { //GEXF private static final String GRAPHML = "graphml"; private static final String GRAPH = "graph"; private static final String GRAPH_DEFAULT_EDGETYPE = "edgedefault"; private static final String GRAPH_ID = "id"; private static final String NODE = "node"; private static final String NODE_ID = "id"; private static final String EDGE = "edge"; private static final String EDGE_ID = "id"; private static final String EDGE_SOURCE = "source"; private static final String EDGE_TARGET = "target"; private static final String EDGE_DIRECTED = "directed"; private static final String ATTRIBUTE = "key"; private static final String ATTRIBUTE_ID = "id"; private static final String ATTRIBUTE_TITLE = "attr.name"; private static final String ATTRIBUTE_TYPE = "attr.type"; private static final String ATTRIBUTE_DEFAULT = "default"; private static final String ATTRIBUTE_FOR = "for"; private static final String ATTVALUE = "data"; private static final String ATTVALUE_FOR = "key"; //Architecture private Reader reader; private ContainerLoader container; private boolean cancel; private Report report; private ProgressTicket progress; private XMLStreamReader xmlReader; private PropertiesAssociations properties = new PropertiesAssociations(); private HashMap<String, NodeProperties> nodePropertiesAttributes = new HashMap<String, NodeProperties>(); private HashMap<String, EdgeProperties> edgePropertiesAttributes = new HashMap<String, EdgeProperties>(); public ImporterGraphML() { //Default node associations properties.addNodePropertyAssociation(NodeProperties.LABEL, "label"); properties.addNodePropertyAssociation(NodeProperties.LABEL, "d3"); // Default node label used by yEd from yworks.com. properties.addNodePropertyAssociation(NodeProperties.X, "x"); properties.addNodePropertyAssociation(NodeProperties.Y, "y"); properties.addNodePropertyAssociation(NodeProperties.Z, "z"); properties.addNodePropertyAssociation(NodeProperties.SIZE, "size"); properties.addNodePropertyAssociation(NodeProperties.R, "r"); properties.addNodePropertyAssociation(NodeProperties.G, "g"); properties.addNodePropertyAssociation(NodeProperties.B, "b"); //Default edge associations properties.addEdgePropertyAssociation(EdgeProperties.LABEL, "label"); properties.addEdgePropertyAssociation(EdgeProperties.LABEL, "edgelabel"); properties.addEdgePropertyAssociation(EdgeProperties.LABEL, "d7"); // Default edge label used by yEd from yworks.com. properties.addEdgePropertyAssociation(EdgeProperties.WEIGHT, "weight"); properties.addEdgePropertyAssociation(EdgeProperties.ID, "id"); properties.addEdgePropertyAssociation(EdgeProperties.ID, "edgeid"); properties.addEdgePropertyAssociation(EdgeProperties.R, "r"); properties.addEdgePropertyAssociation(EdgeProperties.G, "g"); properties.addEdgePropertyAssociation(EdgeProperties.B, "b"); } public boolean execute(ContainerLoader container) { this.container = container; this.report = new Report(); Progress.start(progress); try { XMLInputFactory inputFactory = XMLInputFactory.newInstance(); if (inputFactory.isPropertySupported("javax.xml.stream.isValidating")) { inputFactory.setProperty("javax.xml.stream.isValidating", Boolean.FALSE); } inputFactory.setXMLReporter(new XMLReporter() { @Override public void report(String message, String errorType, Object relatedInformation, Location location) throws XMLStreamException { System.out.println("Error:" + errorType + ", message : " + message); } }); xmlReader = inputFactory.createXMLStreamReader(reader); while (xmlReader.hasNext()) { Integer eventType = xmlReader.next(); if (eventType.equals(XMLEvent.START_ELEMENT)) { String name = xmlReader.getLocalName(); if (GRAPHML.equalsIgnoreCase(name)) { } else if (GRAPH.equalsIgnoreCase(name)) { readGraph(xmlReader); } else if (NODE.equalsIgnoreCase(name)) { readNode(xmlReader, null); } else if (EDGE.equalsIgnoreCase(name)) { readEdge(xmlReader); } else if (ATTRIBUTE.equalsIgnoreCase(name)) { readAttribute(xmlReader); } } else if (eventType.equals(XMLStreamReader.END_ELEMENT)) { String name = xmlReader.getLocalName(); if (NODE.equalsIgnoreCase(name)) { } } } xmlReader.close(); } catch (Exception e) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } throw new RuntimeException(e); } Progress.finish(progress); return !cancel; } private void readGraph(XMLStreamReader reader) throws Exception { String id = ""; String defaultEdgeType = ""; //Attributes for (int i = 0; i < reader.getAttributeCount(); i++) { String attName = reader.getAttributeName(i).getLocalPart(); if (GRAPH_DEFAULT_EDGETYPE.equalsIgnoreCase(attName)) { defaultEdgeType = reader.getAttributeValue(i); } else if (GRAPH_ID.equalsIgnoreCase(attName)) { id = reader.getAttributeValue(i); } } //Edge Type if (!defaultEdgeType.isEmpty()) { if (defaultEdgeType.equalsIgnoreCase("undirected")) { container.setEdgeDefault(EdgeDefault.UNDIRECTED); } else if (defaultEdgeType.equalsIgnoreCase("directed")) { container.setEdgeDefault(EdgeDefault.DIRECTED); } else { report.logIssue(new Issue(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_error_defaultedgetype", defaultEdgeType), Issue.Level.SEVERE)); } } } private void readNode(XMLStreamReader reader, NodeDraft parent) throws Exception { String id = ""; //Attributes for (int i = 0; i < reader.getAttributeCount(); i++) { String attName = reader.getAttributeName(i).getLocalPart(); if (NODE_ID.equalsIgnoreCase(attName)) { id = reader.getAttributeValue(i); } } if (id.isEmpty()) { report.logIssue(new Issue(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_error_nodeid"), Issue.Level.SEVERE)); return; } NodeDraft node = null; if (container.nodeExists(id)) { node = container.getNode(id); } else { node = container.factory().newNodeDraft(); } node.setId(id); //Parent if (parent != null) { node.setParent(parent); } if (!container.nodeExists(id)) { container.addNode(node); } boolean end = false; while (reader.hasNext() && !end) { int type = reader.next(); switch (type) { case XMLStreamReader.START_ELEMENT: String name = xmlReader.getLocalName(); if (ATTVALUE.equalsIgnoreCase(xmlReader.getLocalName())) { readNodeAttValue(reader, node); } else if (NODE.equalsIgnoreCase(name)) { readNode(reader, node); } break; case XMLStreamReader.END_ELEMENT: if (NODE.equalsIgnoreCase(xmlReader.getLocalName())) { end = true; } break; } } } private void readNodeAttValue(XMLStreamReader reader, NodeDraft node) throws Exception { String fore = ""; String value = ""; for (int i = 0; i < reader.getAttributeCount(); i++) { String attName = reader.getAttributeName(i).getLocalPart(); if (ATTVALUE_FOR.equalsIgnoreCase(attName)) { fore = reader.getAttributeValue(i); } } if (fore.isEmpty()) { report.logIssue(new Issue(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_error_datakey", node), Issue.Level.SEVERE)); return; } boolean end = false; while (reader.hasNext() && !end) { int xmltype = reader.next(); switch (xmltype) { case XMLStreamReader.CHARACTERS: if (!xmlReader.isWhiteSpace()) { value += xmlReader.getText(); } break; case XMLStreamReader.END_ELEMENT: if (ATTVALUE.equalsIgnoreCase(xmlReader.getLocalName())) { end = true; } break; } } if (!value.isEmpty()) { //Property NodeProperties prop = nodePropertiesAttributes.get(fore); if (prop != null) { try { switch (prop) { case X: node.setX(parseFloat(value)); break; case Y: node.setY(parseFloat(value)); break; case Z: node.setZ(parseFloat(value)); break; case SIZE: node.setSize(parseFloat(value)); break; case LABEL: node.setLabel(value); break; case R: if (node.getColor() == null) { node.setColor(Integer.parseInt(value), 0, 0); } else { node.setColor(Integer.parseInt(value), node.getColor().getGreen(), node.getColor().getBlue()); } break; case G: if (node.getColor() == null) { node.setColor(0, Integer.parseInt(value), 0); } else { node.setColor(node.getColor().getRed(), Integer.parseInt(value), node.getColor().getBlue()); } break; case B: if (node.getColor() == null) { node.setColor(0, 0, Integer.parseInt(value)); } else { node.setColor(node.getColor().getRed(), node.getColor().getGreen(), Integer.parseInt(value)); } break; } } catch (Exception e) { report.logIssue(new Issue(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_error_datavalue", fore, node, prop.toString()), Issue.Level.SEVERE)); } return; } //Data attribute value AttributeColumn column = container.getAttributeModel().getNodeTable().getColumn(fore); if (column != null) { try { Object val = column.getType().parse(value); node.addAttributeValue(column, val); } catch (Exception e) { report.logIssue(new Issue(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_error_datavalue", fore, node, column.getTitle()), Issue.Level.SEVERE)); } } } } private void readEdge(XMLStreamReader reader) throws Exception { String id = ""; String source = ""; String target = ""; String directed = ""; //Attributes for (int i = 0; i < reader.getAttributeCount(); i++) { String attName = reader.getAttributeName(i).getLocalPart(); if (EDGE_SOURCE.equalsIgnoreCase(attName)) { source = reader.getAttributeValue(i); } else if (EDGE_TARGET.equalsIgnoreCase(attName)) { target = reader.getAttributeValue(i); } else if (EDGE_ID.equalsIgnoreCase(attName)) { id = reader.getAttributeValue(i); } else if (EDGE_DIRECTED.equalsIgnoreCase(attName)) { directed = reader.getAttributeValue(i); } } EdgeDraft edge = container.factory().newEdgeDraft(); NodeDraft nodeSource = container.getNode(source); NodeDraft nodeTarget = container.getNode(target); edge.setSource(nodeSource); edge.setTarget(nodeTarget); //Type if (!directed.isEmpty()) { if (directed.equalsIgnoreCase("true")) { edge.setType(EdgeDraft.EdgeType.DIRECTED); } else if (directed.equalsIgnoreCase("false")) { edge.setType(EdgeDraft.EdgeType.UNDIRECTED); } else { report.logIssue(new Issue(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_error_edgetype", directed, edge), Issue.Level.SEVERE)); } } //Id if (!id.isEmpty()) { edge.setId(id); } boolean end = false; while (reader.hasNext() && !end) { int type = reader.next(); switch (type) { case XMLStreamReader.START_ELEMENT: if (ATTVALUE.equalsIgnoreCase(xmlReader.getLocalName())) { readEdgeAttValue(reader, edge); } break; case XMLStreamReader.END_ELEMENT: if (EDGE.equalsIgnoreCase(xmlReader.getLocalName())) { end = true; } break; } } container.addEdge(edge); } private void readEdgeAttValue(XMLStreamReader reader, EdgeDraft edge) throws Exception { String fore = ""; String value = ""; for (int i = 0; i < reader.getAttributeCount(); i++) { String attName = reader.getAttributeName(i).getLocalPart(); if (ATTVALUE_FOR.equalsIgnoreCase(attName)) { fore = reader.getAttributeValue(i); } } if (fore.isEmpty()) { report.logIssue(new Issue(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_error_datakey", edge), Issue.Level.SEVERE)); return; } boolean end = false; while (reader.hasNext() && !end) { int xmltype = reader.next(); switch (xmltype) { case XMLStreamReader.CHARACTERS: if (!xmlReader.isWhiteSpace()) { value += xmlReader.getText(); } break; case XMLStreamReader.END_ELEMENT: if (ATTVALUE.equalsIgnoreCase(xmlReader.getLocalName())) { end = true; } break; } } if (!value.isEmpty()) { EdgeProperties prop = edgePropertiesAttributes.get(fore); if (prop != null) { try { switch (prop) { case WEIGHT: edge.setWeight(parseFloat(value)); break; case LABEL: edge.setLabel(value); break; case ID: edge.setId(value); break; case R: if (edge.getColor() == null) { edge.setColor(Integer.parseInt(value), 0, 0); } else { edge.setColor(Integer.parseInt(value), edge.getColor().getGreen(), edge.getColor().getBlue()); } break; case G: if (edge.getColor() == null) { edge.setColor(0, Integer.parseInt(value), 0); } else { edge.setColor(edge.getColor().getRed(), Integer.parseInt(value), edge.getColor().getBlue()); } break; case B: if (edge.getColor() == null) { edge.setColor(0, 0, Integer.parseInt(value)); } else { edge.setColor(edge.getColor().getRed(), edge.getColor().getGreen(), Integer.parseInt(value)); } break; } } catch (Exception e) { report.logIssue(new Issue(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_error_datavalue", fore, edge, prop.toString()), Issue.Level.SEVERE)); } return; } //Data attribute value AttributeColumn column = container.getAttributeModel().getNodeTable().getColumn(fore); if (column != null) { try { Object val = column.getType().parse(value); edge.addAttributeValue(column, val); } catch (Exception e) { report.logIssue(new Issue(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_error_datavalue", fore, edge, column.getTitle()), Issue.Level.SEVERE)); } } } } private void readAttribute(XMLStreamReader reader) throws Exception { String id = ""; String type = ""; String title = ""; String defaultStr = ""; String forStr = ""; for (int i = 0; i < reader.getAttributeCount(); i++) { String attName = reader.getAttributeName(i).getLocalPart(); if (ATTRIBUTE_ID.equalsIgnoreCase(attName)) { id = reader.getAttributeValue(i); } else if (ATTRIBUTE_TYPE.equalsIgnoreCase(attName)) { type = reader.getAttributeValue(i); } else if (ATTRIBUTE_TITLE.equalsIgnoreCase(attName)) { title = reader.getAttributeValue(i); } else if (ATTRIBUTE_FOR.equalsIgnoreCase(attName)) { forStr = reader.getAttributeValue(i); } } if (title.isEmpty()) { title = id; } boolean property = false; if (!id.isEmpty()) { //Properties if (forStr.equalsIgnoreCase("node")) { NodeProperties prop = properties.getNodeProperty(id) == null ? properties.getNodeProperty(title) : properties.getNodeProperty(id); if (prop != null) { nodePropertiesAttributes.put(id, prop); report.log(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_log_nodeproperty", title)); property = true; } } else if (forStr.equalsIgnoreCase("edge")) { EdgeProperties prop = properties.getEdgeProperty(id) == null ? properties.getEdgeProperty(title) : properties.getEdgeProperty(id); if (prop != null) { edgePropertiesAttributes.put(id, prop); report.log(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_log_edgeproperty", title)); property = true; } } if (property) { return; } } else { report.logIssue(new Issue(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_error_attributeempty", title), Issue.Level.SEVERE)); return; } if (!property && type.isEmpty()) { report.logIssue(new Issue(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_error_attributetype1", title), Issue.Level.SEVERE)); type = "string"; } if (!property) { //Class type if (forStr.isEmpty() || !(forStr.equalsIgnoreCase("node") || forStr.equalsIgnoreCase("edge") || forStr.equalsIgnoreCase("all"))) { report.logIssue(new Issue(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_error_attributeclass", title), Issue.Level.SEVERE)); return; } //Default? boolean end = false; boolean defaultFlag = false; while (reader.hasNext() && !end) { int xmltype = reader.next(); switch (xmltype) { case XMLStreamReader.START_ELEMENT: if (ATTRIBUTE_DEFAULT.equalsIgnoreCase(xmlReader.getLocalName())) { defaultFlag = true; } break; case XMLStreamReader.CHARACTERS: if (defaultFlag && !xmlReader.isWhiteSpace()) { defaultStr = xmlReader.getText(); } break; case XMLStreamReader.END_ELEMENT: if (ATTRIBUTE.equalsIgnoreCase(xmlReader.getLocalName())) { end = true; } break; } } //Type AttributeType attributeType = AttributeType.STRING; if (type.equalsIgnoreCase("boolean") || type.equalsIgnoreCase("bool")) { attributeType = AttributeType.BOOLEAN; } else if (type.equalsIgnoreCase("integer") || type.equalsIgnoreCase("int")) { attributeType = AttributeType.INT; } else if (type.equalsIgnoreCase("long")) { attributeType = AttributeType.LONG; } else if (type.equalsIgnoreCase("float")) { attributeType = AttributeType.FLOAT; } else if (type.equalsIgnoreCase("double")) { attributeType = AttributeType.DOUBLE; } else if (type.equalsIgnoreCase("string")) { attributeType = AttributeType.STRING; } else if (type.equalsIgnoreCase("bigdecimal")) { attributeType = AttributeType.BIGDECIMAL; } else if (type.equalsIgnoreCase("biginteger")) { attributeType = AttributeType.BIGINTEGER; } else if (type.equalsIgnoreCase("byte")) { attributeType = AttributeType.BYTE; } else if (type.equalsIgnoreCase("char")) { attributeType = AttributeType.CHAR; } else if (type.equalsIgnoreCase("short")) { attributeType = AttributeType.SHORT; } else if (type.equalsIgnoreCase("listboolean")) { attributeType = AttributeType.LIST_BOOLEAN; } else if (type.equalsIgnoreCase("listint")) { attributeType = AttributeType.LIST_INTEGER; } else if (type.equalsIgnoreCase("listlong")) { attributeType = AttributeType.LIST_LONG; } else if (type.equalsIgnoreCase("listfloat")) { attributeType = AttributeType.LIST_FLOAT; } else if (type.equalsIgnoreCase("listdouble")) { attributeType = AttributeType.LIST_DOUBLE; } else if (type.equalsIgnoreCase("liststring")) { attributeType = AttributeType.LIST_STRING; } else if (type.equalsIgnoreCase("listbigdecimal")) { attributeType = AttributeType.LIST_BIGDECIMAL; } else if (type.equalsIgnoreCase("listbiginteger")) { attributeType = AttributeType.LIST_BIGINTEGER; } else if (type.equalsIgnoreCase("listbyte")) { attributeType = AttributeType.LIST_BYTE; } else if (type.equalsIgnoreCase("listchar")) { attributeType = AttributeType.LIST_CHARACTER; } else if (type.equalsIgnoreCase("listshort")) { attributeType = AttributeType.LIST_SHORT; } else { report.logIssue(new Issue(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_error_attributetype2", type), Issue.Level.SEVERE)); return; } //Default Object Object defaultValue = null; if (!defaultStr.isEmpty()) { try { defaultValue = attributeType.parse(defaultStr); report.log(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_log_default", defaultStr, title)); } catch (Exception e) { report.logIssue(new Issue(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_error_attributedefault", title, attributeType.getTypeString()), Issue.Level.SEVERE)); } } //Add to model if ("node".equalsIgnoreCase(forStr) || "all".equalsIgnoreCase(forStr)) { if (container.getAttributeModel().getNodeTable().hasColumn(id) || container.getAttributeModel().getNodeTable().hasColumn(title)) { report.log(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_error_attributecolumn_exist", id)); return; } container.getAttributeModel().getNodeTable().addColumn(id, title, attributeType, AttributeOrigin.DATA, defaultValue); report.log(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_log_nodeattribute", title, attributeType.getTypeString())); } else if ("edge".equalsIgnoreCase(forStr) || "all".equalsIgnoreCase(forStr)) { if (container.getAttributeModel().getEdgeTable().hasColumn(id) || container.getAttributeModel().getEdgeTable().hasColumn(title)) { - report.log(NbBundle.getMessage(ImporterGraphML.class, "importerGraphMLF_error_attributecolumn_exist", id)); + report.log(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_error_attributecolumn_exist", id)); return; } container.getAttributeModel().getEdgeTable().addColumn(id, title, attributeType, AttributeOrigin.DATA, defaultValue); report.log(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_log_edgeattribute", title, attributeType.getTypeString())); } } else { report.logIssue(new Issue(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_error_attributeempty", title), Issue.Level.SEVERE)); } } private float parseFloat(String str) { str = str.replace(',', '.'); return Float.parseFloat(str); } public void setReader(Reader reader) { this.reader = reader; } public ContainerLoader getContainer() { return container; } public Report getReport() { return report; } public boolean cancel() { cancel = true; return true; } public void setProgressTicket(ProgressTicket progressTicket) { this.progress = progressTicket; } }
true
true
private void readAttribute(XMLStreamReader reader) throws Exception { String id = ""; String type = ""; String title = ""; String defaultStr = ""; String forStr = ""; for (int i = 0; i < reader.getAttributeCount(); i++) { String attName = reader.getAttributeName(i).getLocalPart(); if (ATTRIBUTE_ID.equalsIgnoreCase(attName)) { id = reader.getAttributeValue(i); } else if (ATTRIBUTE_TYPE.equalsIgnoreCase(attName)) { type = reader.getAttributeValue(i); } else if (ATTRIBUTE_TITLE.equalsIgnoreCase(attName)) { title = reader.getAttributeValue(i); } else if (ATTRIBUTE_FOR.equalsIgnoreCase(attName)) { forStr = reader.getAttributeValue(i); } } if (title.isEmpty()) { title = id; } boolean property = false; if (!id.isEmpty()) { //Properties if (forStr.equalsIgnoreCase("node")) { NodeProperties prop = properties.getNodeProperty(id) == null ? properties.getNodeProperty(title) : properties.getNodeProperty(id); if (prop != null) { nodePropertiesAttributes.put(id, prop); report.log(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_log_nodeproperty", title)); property = true; } } else if (forStr.equalsIgnoreCase("edge")) { EdgeProperties prop = properties.getEdgeProperty(id) == null ? properties.getEdgeProperty(title) : properties.getEdgeProperty(id); if (prop != null) { edgePropertiesAttributes.put(id, prop); report.log(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_log_edgeproperty", title)); property = true; } } if (property) { return; } } else { report.logIssue(new Issue(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_error_attributeempty", title), Issue.Level.SEVERE)); return; } if (!property && type.isEmpty()) { report.logIssue(new Issue(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_error_attributetype1", title), Issue.Level.SEVERE)); type = "string"; } if (!property) { //Class type if (forStr.isEmpty() || !(forStr.equalsIgnoreCase("node") || forStr.equalsIgnoreCase("edge") || forStr.equalsIgnoreCase("all"))) { report.logIssue(new Issue(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_error_attributeclass", title), Issue.Level.SEVERE)); return; } //Default? boolean end = false; boolean defaultFlag = false; while (reader.hasNext() && !end) { int xmltype = reader.next(); switch (xmltype) { case XMLStreamReader.START_ELEMENT: if (ATTRIBUTE_DEFAULT.equalsIgnoreCase(xmlReader.getLocalName())) { defaultFlag = true; } break; case XMLStreamReader.CHARACTERS: if (defaultFlag && !xmlReader.isWhiteSpace()) { defaultStr = xmlReader.getText(); } break; case XMLStreamReader.END_ELEMENT: if (ATTRIBUTE.equalsIgnoreCase(xmlReader.getLocalName())) { end = true; } break; } } //Type AttributeType attributeType = AttributeType.STRING; if (type.equalsIgnoreCase("boolean") || type.equalsIgnoreCase("bool")) { attributeType = AttributeType.BOOLEAN; } else if (type.equalsIgnoreCase("integer") || type.equalsIgnoreCase("int")) { attributeType = AttributeType.INT; } else if (type.equalsIgnoreCase("long")) { attributeType = AttributeType.LONG; } else if (type.equalsIgnoreCase("float")) { attributeType = AttributeType.FLOAT; } else if (type.equalsIgnoreCase("double")) { attributeType = AttributeType.DOUBLE; } else if (type.equalsIgnoreCase("string")) { attributeType = AttributeType.STRING; } else if (type.equalsIgnoreCase("bigdecimal")) { attributeType = AttributeType.BIGDECIMAL; } else if (type.equalsIgnoreCase("biginteger")) { attributeType = AttributeType.BIGINTEGER; } else if (type.equalsIgnoreCase("byte")) { attributeType = AttributeType.BYTE; } else if (type.equalsIgnoreCase("char")) { attributeType = AttributeType.CHAR; } else if (type.equalsIgnoreCase("short")) { attributeType = AttributeType.SHORT; } else if (type.equalsIgnoreCase("listboolean")) { attributeType = AttributeType.LIST_BOOLEAN; } else if (type.equalsIgnoreCase("listint")) { attributeType = AttributeType.LIST_INTEGER; } else if (type.equalsIgnoreCase("listlong")) { attributeType = AttributeType.LIST_LONG; } else if (type.equalsIgnoreCase("listfloat")) { attributeType = AttributeType.LIST_FLOAT; } else if (type.equalsIgnoreCase("listdouble")) { attributeType = AttributeType.LIST_DOUBLE; } else if (type.equalsIgnoreCase("liststring")) { attributeType = AttributeType.LIST_STRING; } else if (type.equalsIgnoreCase("listbigdecimal")) { attributeType = AttributeType.LIST_BIGDECIMAL; } else if (type.equalsIgnoreCase("listbiginteger")) { attributeType = AttributeType.LIST_BIGINTEGER; } else if (type.equalsIgnoreCase("listbyte")) { attributeType = AttributeType.LIST_BYTE; } else if (type.equalsIgnoreCase("listchar")) { attributeType = AttributeType.LIST_CHARACTER; } else if (type.equalsIgnoreCase("listshort")) { attributeType = AttributeType.LIST_SHORT; } else { report.logIssue(new Issue(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_error_attributetype2", type), Issue.Level.SEVERE)); return; } //Default Object Object defaultValue = null; if (!defaultStr.isEmpty()) { try { defaultValue = attributeType.parse(defaultStr); report.log(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_log_default", defaultStr, title)); } catch (Exception e) { report.logIssue(new Issue(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_error_attributedefault", title, attributeType.getTypeString()), Issue.Level.SEVERE)); } } //Add to model if ("node".equalsIgnoreCase(forStr) || "all".equalsIgnoreCase(forStr)) { if (container.getAttributeModel().getNodeTable().hasColumn(id) || container.getAttributeModel().getNodeTable().hasColumn(title)) { report.log(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_error_attributecolumn_exist", id)); return; } container.getAttributeModel().getNodeTable().addColumn(id, title, attributeType, AttributeOrigin.DATA, defaultValue); report.log(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_log_nodeattribute", title, attributeType.getTypeString())); } else if ("edge".equalsIgnoreCase(forStr) || "all".equalsIgnoreCase(forStr)) { if (container.getAttributeModel().getEdgeTable().hasColumn(id) || container.getAttributeModel().getEdgeTable().hasColumn(title)) { report.log(NbBundle.getMessage(ImporterGraphML.class, "importerGraphMLF_error_attributecolumn_exist", id)); return; } container.getAttributeModel().getEdgeTable().addColumn(id, title, attributeType, AttributeOrigin.DATA, defaultValue); report.log(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_log_edgeattribute", title, attributeType.getTypeString())); } } else { report.logIssue(new Issue(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_error_attributeempty", title), Issue.Level.SEVERE)); } }
private void readAttribute(XMLStreamReader reader) throws Exception { String id = ""; String type = ""; String title = ""; String defaultStr = ""; String forStr = ""; for (int i = 0; i < reader.getAttributeCount(); i++) { String attName = reader.getAttributeName(i).getLocalPart(); if (ATTRIBUTE_ID.equalsIgnoreCase(attName)) { id = reader.getAttributeValue(i); } else if (ATTRIBUTE_TYPE.equalsIgnoreCase(attName)) { type = reader.getAttributeValue(i); } else if (ATTRIBUTE_TITLE.equalsIgnoreCase(attName)) { title = reader.getAttributeValue(i); } else if (ATTRIBUTE_FOR.equalsIgnoreCase(attName)) { forStr = reader.getAttributeValue(i); } } if (title.isEmpty()) { title = id; } boolean property = false; if (!id.isEmpty()) { //Properties if (forStr.equalsIgnoreCase("node")) { NodeProperties prop = properties.getNodeProperty(id) == null ? properties.getNodeProperty(title) : properties.getNodeProperty(id); if (prop != null) { nodePropertiesAttributes.put(id, prop); report.log(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_log_nodeproperty", title)); property = true; } } else if (forStr.equalsIgnoreCase("edge")) { EdgeProperties prop = properties.getEdgeProperty(id) == null ? properties.getEdgeProperty(title) : properties.getEdgeProperty(id); if (prop != null) { edgePropertiesAttributes.put(id, prop); report.log(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_log_edgeproperty", title)); property = true; } } if (property) { return; } } else { report.logIssue(new Issue(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_error_attributeempty", title), Issue.Level.SEVERE)); return; } if (!property && type.isEmpty()) { report.logIssue(new Issue(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_error_attributetype1", title), Issue.Level.SEVERE)); type = "string"; } if (!property) { //Class type if (forStr.isEmpty() || !(forStr.equalsIgnoreCase("node") || forStr.equalsIgnoreCase("edge") || forStr.equalsIgnoreCase("all"))) { report.logIssue(new Issue(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_error_attributeclass", title), Issue.Level.SEVERE)); return; } //Default? boolean end = false; boolean defaultFlag = false; while (reader.hasNext() && !end) { int xmltype = reader.next(); switch (xmltype) { case XMLStreamReader.START_ELEMENT: if (ATTRIBUTE_DEFAULT.equalsIgnoreCase(xmlReader.getLocalName())) { defaultFlag = true; } break; case XMLStreamReader.CHARACTERS: if (defaultFlag && !xmlReader.isWhiteSpace()) { defaultStr = xmlReader.getText(); } break; case XMLStreamReader.END_ELEMENT: if (ATTRIBUTE.equalsIgnoreCase(xmlReader.getLocalName())) { end = true; } break; } } //Type AttributeType attributeType = AttributeType.STRING; if (type.equalsIgnoreCase("boolean") || type.equalsIgnoreCase("bool")) { attributeType = AttributeType.BOOLEAN; } else if (type.equalsIgnoreCase("integer") || type.equalsIgnoreCase("int")) { attributeType = AttributeType.INT; } else if (type.equalsIgnoreCase("long")) { attributeType = AttributeType.LONG; } else if (type.equalsIgnoreCase("float")) { attributeType = AttributeType.FLOAT; } else if (type.equalsIgnoreCase("double")) { attributeType = AttributeType.DOUBLE; } else if (type.equalsIgnoreCase("string")) { attributeType = AttributeType.STRING; } else if (type.equalsIgnoreCase("bigdecimal")) { attributeType = AttributeType.BIGDECIMAL; } else if (type.equalsIgnoreCase("biginteger")) { attributeType = AttributeType.BIGINTEGER; } else if (type.equalsIgnoreCase("byte")) { attributeType = AttributeType.BYTE; } else if (type.equalsIgnoreCase("char")) { attributeType = AttributeType.CHAR; } else if (type.equalsIgnoreCase("short")) { attributeType = AttributeType.SHORT; } else if (type.equalsIgnoreCase("listboolean")) { attributeType = AttributeType.LIST_BOOLEAN; } else if (type.equalsIgnoreCase("listint")) { attributeType = AttributeType.LIST_INTEGER; } else if (type.equalsIgnoreCase("listlong")) { attributeType = AttributeType.LIST_LONG; } else if (type.equalsIgnoreCase("listfloat")) { attributeType = AttributeType.LIST_FLOAT; } else if (type.equalsIgnoreCase("listdouble")) { attributeType = AttributeType.LIST_DOUBLE; } else if (type.equalsIgnoreCase("liststring")) { attributeType = AttributeType.LIST_STRING; } else if (type.equalsIgnoreCase("listbigdecimal")) { attributeType = AttributeType.LIST_BIGDECIMAL; } else if (type.equalsIgnoreCase("listbiginteger")) { attributeType = AttributeType.LIST_BIGINTEGER; } else if (type.equalsIgnoreCase("listbyte")) { attributeType = AttributeType.LIST_BYTE; } else if (type.equalsIgnoreCase("listchar")) { attributeType = AttributeType.LIST_CHARACTER; } else if (type.equalsIgnoreCase("listshort")) { attributeType = AttributeType.LIST_SHORT; } else { report.logIssue(new Issue(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_error_attributetype2", type), Issue.Level.SEVERE)); return; } //Default Object Object defaultValue = null; if (!defaultStr.isEmpty()) { try { defaultValue = attributeType.parse(defaultStr); report.log(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_log_default", defaultStr, title)); } catch (Exception e) { report.logIssue(new Issue(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_error_attributedefault", title, attributeType.getTypeString()), Issue.Level.SEVERE)); } } //Add to model if ("node".equalsIgnoreCase(forStr) || "all".equalsIgnoreCase(forStr)) { if (container.getAttributeModel().getNodeTable().hasColumn(id) || container.getAttributeModel().getNodeTable().hasColumn(title)) { report.log(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_error_attributecolumn_exist", id)); return; } container.getAttributeModel().getNodeTable().addColumn(id, title, attributeType, AttributeOrigin.DATA, defaultValue); report.log(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_log_nodeattribute", title, attributeType.getTypeString())); } else if ("edge".equalsIgnoreCase(forStr) || "all".equalsIgnoreCase(forStr)) { if (container.getAttributeModel().getEdgeTable().hasColumn(id) || container.getAttributeModel().getEdgeTable().hasColumn(title)) { report.log(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_error_attributecolumn_exist", id)); return; } container.getAttributeModel().getEdgeTable().addColumn(id, title, attributeType, AttributeOrigin.DATA, defaultValue); report.log(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_log_edgeattribute", title, attributeType.getTypeString())); } } else { report.logIssue(new Issue(NbBundle.getMessage(ImporterGraphML.class, "importerGraphML_error_attributeempty", title), Issue.Level.SEVERE)); } }
diff --git a/src/com/eteks/sweethome3d/swing/SwingTools.java b/src/com/eteks/sweethome3d/swing/SwingTools.java index c755e1ca..128cb8b3 100644 --- a/src/com/eteks/sweethome3d/swing/SwingTools.java +++ b/src/com/eteks/sweethome3d/swing/SwingTools.java @@ -1,494 +1,494 @@ /* * SwingTools.java 21 oct. 2008 * * Copyright (c) 2008 Emmanuel PUYBARET / eTeks <[email protected]>. All Rights Reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.eteks.sweethome3d.swing; import java.awt.Color; import java.awt.Component; import java.awt.EventQueue; import java.awt.Frame; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Insets; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.Window; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.awt.image.FilteredImageSource; import java.awt.image.RGBImageFilter; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Enumeration; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.concurrent.Executors; import javax.imageio.ImageIO; import javax.swing.BorderFactory; import javax.swing.ButtonGroup; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JOptionPane; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JToggleButton; import javax.swing.JViewport; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.border.AbstractBorder; import javax.swing.border.Border; import javax.swing.text.JTextComponent; import com.eteks.sweethome3d.model.TextureImage; import com.eteks.sweethome3d.model.UserPreferences; import com.eteks.sweethome3d.tools.OperatingSystem; /** * Gathers some useful tools for Swing. * @author Emmanuel Puybaret */ public class SwingTools { // Borders for focused views private static Border unfocusedViewBorder; private static Border focusedViewBorder; private SwingTools() { // This class contains only tools } /** * Updates the border of <code>component</code> with an empty border * changed to a colored border when it will gain focus. * If the <code>component</code> component is the child of a <code>JViewPort</code> * instance this border will be installed on its scroll pane parent. */ public static void installFocusBorder(JComponent component) { if (unfocusedViewBorder == null) { Border unfocusedViewInteriorBorder = new AbstractBorder() { private Color topLeftColor; private Color botomRightColor; private Insets insets = new Insets(1, 1, 1, 1); { if (OperatingSystem.isMacOSX()) { this.topLeftColor = Color.GRAY; this.botomRightColor = Color.LIGHT_GRAY; } else { this.topLeftColor = UIManager.getColor("TextField.darkShadow"); - this.botomRightColor = UIManager.getColor("TextField.light"); + this.botomRightColor = UIManager.getColor("TextField.shadow"); } } public Insets getBorderInsets(Component c) { return this.insets; } public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { Color previousColor = g.getColor(); Rectangle rect = getInteriorRectangle(c, x, y, width, height); g.setColor(topLeftColor); g.drawLine(rect.x - 1, rect.y - 1, rect.x + rect.width, rect.y - 1); g.drawLine(rect.x - 1, rect.y - 1, rect.x - 1, rect.y + rect.height); g.setColor(botomRightColor); g.drawLine(rect.x, rect.y + rect.height, rect.x + rect.width, rect.y + rect.height); g.drawLine(rect.x + rect.width, rect.y, rect.x + rect.width, rect.y + rect.height); g.setColor(previousColor); } }; if (OperatingSystem.isMacOSXLeopardOrSuperior()) { unfocusedViewBorder = BorderFactory.createCompoundBorder( BorderFactory.createLineBorder(UIManager.getColor("Panel.background"), 2), unfocusedViewInteriorBorder); focusedViewBorder = new AbstractBorder() { private Insets insets = new Insets(3, 3, 3, 3); public Insets getBorderInsets(Component c) { return this.insets; } public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { Color previousColor = g.getColor(); // Paint a gradient paint around component Rectangle rect = getInteriorRectangle(c, x, y, width, height); g.setColor(Color.GRAY); g.drawLine(rect.x - 1, rect.y - 1, rect.x + rect.width, rect.y - 1); g.drawLine(rect.x - 1, rect.y - 1, rect.x - 1, rect.y + rect.height); g.setColor(Color.LIGHT_GRAY); g.drawLine(rect.x, rect.y + rect.height, rect.x + rect.width, rect.y + rect.height); g.drawLine(rect.x + rect.width, rect.y, rect.x + rect.width, rect.y + rect.height); Color focusColor = UIManager.getColor("Focus.color"); int transparencyOutline = 128; int transparencyInline = 180; if (focusColor == null) { focusColor = UIManager.getColor("textHighlight"); transparencyOutline = 128; transparencyInline = 255; } g.setColor(new Color(focusColor.getRed(), focusColor.getGreen(), focusColor.getBlue(), transparencyOutline)); g.drawRoundRect(rect.x - 3, rect.y - 3, rect.width + 5, rect.height + 5, 6, 6); g.drawRect(rect.x - 1, rect.y - 1, rect.width + 1, rect.height + 1); g.setColor(new Color(focusColor.getRed(), focusColor.getGreen(), focusColor.getBlue(), transparencyInline)); g.drawRoundRect(rect.x - 2, rect.y - 2, rect.width + 3, rect.height + 3, 4, 4); // Draw corners g.setColor(UIManager.getColor("Panel.background")); g.drawLine(rect.x - 3, rect.y - 3, rect.x - 2, rect.y - 3); g.drawLine(rect.x - 3, rect.y - 2, rect.x - 3, rect.y - 2); g.drawLine(rect.x + rect.width + 1, rect.y - 3, rect.x + rect.width + 2, rect.y - 3); g.drawLine(rect.x + rect.width + 2, rect.y - 2, rect.x + rect.width + 2, rect.y - 2); g.drawLine(rect.x - 3, rect.y + rect.height + 2, rect.x - 2, rect.y + rect.height + 2); g.drawLine(rect.x - 3, rect.y + rect.height + 1, rect.x - 3, rect.y + rect.height + 1); g.drawLine(rect.x + rect.width + 1, rect.y + rect.height + 2, rect.x + rect.width + 2, rect.y + rect.height + 2); g.drawLine(rect.x + rect.width + 2, rect.y + rect.height + 1, rect.x + rect.width + 2, rect.y + rect.height + 1); g.setColor(previousColor); } }; } else { if (OperatingSystem.isMacOSX()) { unfocusedViewBorder = BorderFactory.createCompoundBorder( BorderFactory.createLineBorder(UIManager.getColor("Panel.background"), 1), unfocusedViewInteriorBorder); } else { unfocusedViewBorder = BorderFactory.createCompoundBorder( BorderFactory.createEmptyBorder(1, 1, 1, 1), unfocusedViewInteriorBorder); } focusedViewBorder = BorderFactory.createLineBorder(UIManager.getColor("textHighlight"), 2); } } final JComponent feedbackComponent; if (component.getParent() instanceof JViewport && component.getParent().getParent() instanceof JScrollPane) { feedbackComponent = (JComponent)component.getParent().getParent(); } else { feedbackComponent = component; } feedbackComponent.setBorder(unfocusedViewBorder); component.addFocusListener(new FocusListener() { public void focusLost(FocusEvent ev) { feedbackComponent.setBorder(unfocusedViewBorder); } public void focusGained(FocusEvent ev) { feedbackComponent.setBorder(focusedViewBorder); } }); } /** * Updates the Swing resource bundle in use from the current Locale. */ public static void updateSwingResourceLanguage() { // Read Swing localized properties because Swing doesn't update its internal strings automatically // when default Locale is updated (see bug http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4884480) String [] swingResources = {"com.sun.swing.internal.plaf.basic.resources.basic", "com.sun.swing.internal.plaf.metal.resources.metal"}; for (String swingResource : swingResources) { ResourceBundle resource; try { resource = ResourceBundle.getBundle(swingResource); } catch (MissingResourceException ex) { resource = ResourceBundle.getBundle(swingResource, Locale.ENGLISH); } // Update UIManager properties for (Enumeration<?> it = resource.getKeys(); it.hasMoreElements(); ) { String property = (String)it.nextElement(); UIManager.put(property, resource.getString(property)); } }; } /** * Returns a localized text for menus items and labels depending on the system. */ public static String getLocalizedLabelText(UserPreferences preferences, Class<?> resourceClass, String resourceKey, Object ... resourceParameters) { String localizedString = preferences.getLocalizedString(resourceClass, resourceKey, resourceParameters); // Under Mac OS X, remove bracketed upper case roman letter used in oriental languages to indicate mnemonic String language = Locale.getDefault().getLanguage(); if (OperatingSystem.isMacOSX() && (language.equals(Locale.CHINESE.getLanguage()) || language.equals(Locale.JAPANESE.getLanguage()) || language.equals(Locale.KOREAN.getLanguage()))) { int openingBracketIndex = localizedString.indexOf('('); if (openingBracketIndex != -1) { int closingBracketIndex = localizedString.indexOf(')'); if (openingBracketIndex == closingBracketIndex - 2) { char c = localizedString.charAt(openingBracketIndex + 1); if (c >= 'A' && c <= 'Z') { localizedString = localizedString.substring(0, openingBracketIndex) + localizedString.substring(closingBracketIndex + 1); } } } } return localizedString; } /** * Adds focus and mouse listeners to the given <code>textComponent</code> that will * select all its text when it gains focus by transfer. */ public static void addAutoSelectionOnFocusGain(final JTextComponent textComponent) { // A focus and mouse listener able to select text field characters // when it gains focus after a focus transfer class SelectionOnFocusManager extends MouseAdapter implements FocusListener { private boolean mousePressedInTextField = false; private int selectionStartBeforeFocusLost = -1; private int selectionEndBeforeFocusLost = -1; @Override public void mousePressed(MouseEvent ev) { this.mousePressedInTextField = true; this.selectionStartBeforeFocusLost = -1; } public void focusLost(FocusEvent ev) { if (ev.getOppositeComponent() == null || SwingUtilities.getWindowAncestor(ev.getOppositeComponent()) != SwingUtilities.getWindowAncestor(textComponent)) { // Keep selection indices when focus on text field is transfered // to an other window this.selectionStartBeforeFocusLost = textComponent.getSelectionStart(); this.selectionEndBeforeFocusLost = textComponent.getSelectionEnd(); } else { this.selectionStartBeforeFocusLost = -1; } } public void focusGained(FocusEvent ev) { if (this.selectionStartBeforeFocusLost != -1) { EventQueue.invokeLater(new Runnable() { public void run() { // Reselect the same characters in text field textComponent.setSelectionStart(selectionStartBeforeFocusLost); textComponent.setSelectionEnd(selectionEndBeforeFocusLost); } }); } else if (!this.mousePressedInTextField && ev.getOppositeComponent() != null && SwingUtilities.getWindowAncestor(ev.getOppositeComponent()) == SwingUtilities.getWindowAncestor(textComponent)) { EventQueue.invokeLater(new Runnable() { public void run() { // Select all characters when text field got the focus because of a transfer textComponent.selectAll(); } }); } this.mousePressedInTextField = false; } }; SelectionOnFocusManager selectionOnFocusManager = new SelectionOnFocusManager(); textComponent.addFocusListener(selectionOnFocusManager); textComponent.addMouseListener(selectionOnFocusManager); } /** * Forces radio buttons to be deselected even if they belong to a button group. */ public static void deselectAllRadioButtons(JRadioButton ... radioButtons) { for (JRadioButton radioButton : radioButtons) { ButtonGroup group = ((JToggleButton.ToggleButtonModel)radioButton.getModel()).getGroup(); group.remove(radioButton); radioButton.setSelected(false); group.add(radioButton); } } /** * Displays <code>messageComponent</code> in a modal dialog box, giving focus to one of its components. */ public static int showConfirmDialog(JComponent parentComponent, JComponent messageComponent, String title, final JComponent focusedComponent) { JOptionPane optionPane = new JOptionPane(messageComponent, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION); final JDialog dialog = optionPane.createDialog(SwingUtilities.getRootPane(parentComponent), title); if (focusedComponent != null) { // Add a listener that transfer focus to focusedComponent when dialog is shown dialog.addComponentListener(new ComponentAdapter() { @Override public void componentShown(ComponentEvent ev) { focusedComponent.requestFocusInWindow(); dialog.removeComponentListener(this); } }); } dialog.setVisible(true); dialog.dispose(); Object value = optionPane.getValue(); if (value instanceof Integer) { return (Integer)value; } else { return JOptionPane.CLOSED_OPTION; } } /** * Displays <code>messageComponent</code> in a modal dialog box, giving focus to one of its components. */ public static void showMessageDialog(JComponent parentComponent, JComponent messageComponent, String title, int messageType, final JComponent focusedComponent) { JOptionPane optionPane = new JOptionPane(messageComponent, messageType, JOptionPane.DEFAULT_OPTION); final JDialog dialog = optionPane.createDialog(SwingUtilities.getRootPane(parentComponent), title); if (focusedComponent != null) { // Add a listener that transfer focus to focusedComponent when dialog is shown dialog.addComponentListener(new ComponentAdapter() { @Override public void componentShown(ComponentEvent ev) { focusedComponent.requestFocusInWindow(); dialog.removeComponentListener(this); } }); } dialog.setVisible(true); dialog.dispose(); } private static Map<TextureImage, BufferedImage> patternImages; /** * Returns the image matching a given pattern. */ public static BufferedImage getPatternImage(TextureImage pattern, Color backgroundColor, Color foregroundColor) { if (patternImages == null) { patternImages = new HashMap<TextureImage, BufferedImage>(); } BufferedImage image = new BufferedImage( (int)pattern.getWidth(), (int)pattern.getHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D imageGraphics = (Graphics2D)image.getGraphics(); imageGraphics.setColor(backgroundColor); imageGraphics.fillRect(0, 0, image.getWidth(), image.getHeight()); // Get pattern image from cache BufferedImage patternImage = patternImages.get(pattern); if (patternImage == null) { try { InputStream imageInput = pattern.getImage().openStream(); patternImage = ImageIO.read(imageInput); imageInput.close(); patternImages.put(pattern, patternImage); } catch (IOException ex) { throw new IllegalArgumentException("Can't read pattern image " + pattern.getName()); } } // Draw the pattern image with foreground color final int foregroundColorRgb = foregroundColor.getRGB() & 0xFFFFFF; imageGraphics.drawImage(Toolkit.getDefaultToolkit().createImage( new FilteredImageSource(patternImage.getSource(), new RGBImageFilter() { { this.canFilterIndexColorModel = true; } @Override public int filterRGB(int x, int y, int rgba) { // Always use foreground color and alpha return (rgba & 0xFF000000) | foregroundColorRgb; } })), 0, 0, null); imageGraphics.dispose(); return image; } /** * Returns the border of a component where a user may drop objects. */ public static Border getDropableComponentBorder() { Border border = null; if (OperatingSystem.isMacOSXLeopardOrSuperior()) { border = UIManager.getBorder("InsetBorder.aquaVariant"); } if (border == null) { border = BorderFactory.createLoweredBevelBorder(); } return border; } /** * Displays the image referenced by <code>imageUrl</code> in an AWT window * disposed once an other AWT frame is created. * If the <code>imageUrl</code> is incorrect, nothing happens. */ public static void showSplashScreenWindow(URL imageUrl) { try { final BufferedImage image = ImageIO.read(imageUrl); final Window splashScreenWindow = new Window(new Frame()) { @Override public void paint(Graphics g) { g.drawImage(image, 0, 0, this); } }; splashScreenWindow.setSize(image.getWidth(), image.getHeight()); splashScreenWindow.setLocationRelativeTo(null); splashScreenWindow.setVisible(true); Executors.newSingleThreadExecutor().execute(new Runnable() { public void run() { try { while (splashScreenWindow.isVisible()) { Thread.sleep(500); // If an other frame is created, dispose splash window EventQueue.invokeLater(new Runnable() { public void run() { if (Frame.getFrames().length > 1) { splashScreenWindow.dispose(); } } }); } } catch (InterruptedException ex) { EventQueue.invokeLater(new Runnable() { public void run() { splashScreenWindow.dispose(); } }); }; } }); } catch (IOException ex) { // Ignore splash screen } } }
true
true
public static void installFocusBorder(JComponent component) { if (unfocusedViewBorder == null) { Border unfocusedViewInteriorBorder = new AbstractBorder() { private Color topLeftColor; private Color botomRightColor; private Insets insets = new Insets(1, 1, 1, 1); { if (OperatingSystem.isMacOSX()) { this.topLeftColor = Color.GRAY; this.botomRightColor = Color.LIGHT_GRAY; } else { this.topLeftColor = UIManager.getColor("TextField.darkShadow"); this.botomRightColor = UIManager.getColor("TextField.light"); } } public Insets getBorderInsets(Component c) { return this.insets; } public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { Color previousColor = g.getColor(); Rectangle rect = getInteriorRectangle(c, x, y, width, height); g.setColor(topLeftColor); g.drawLine(rect.x - 1, rect.y - 1, rect.x + rect.width, rect.y - 1); g.drawLine(rect.x - 1, rect.y - 1, rect.x - 1, rect.y + rect.height); g.setColor(botomRightColor); g.drawLine(rect.x, rect.y + rect.height, rect.x + rect.width, rect.y + rect.height); g.drawLine(rect.x + rect.width, rect.y, rect.x + rect.width, rect.y + rect.height); g.setColor(previousColor); } }; if (OperatingSystem.isMacOSXLeopardOrSuperior()) { unfocusedViewBorder = BorderFactory.createCompoundBorder( BorderFactory.createLineBorder(UIManager.getColor("Panel.background"), 2), unfocusedViewInteriorBorder); focusedViewBorder = new AbstractBorder() { private Insets insets = new Insets(3, 3, 3, 3); public Insets getBorderInsets(Component c) { return this.insets; } public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { Color previousColor = g.getColor(); // Paint a gradient paint around component Rectangle rect = getInteriorRectangle(c, x, y, width, height); g.setColor(Color.GRAY); g.drawLine(rect.x - 1, rect.y - 1, rect.x + rect.width, rect.y - 1); g.drawLine(rect.x - 1, rect.y - 1, rect.x - 1, rect.y + rect.height); g.setColor(Color.LIGHT_GRAY); g.drawLine(rect.x, rect.y + rect.height, rect.x + rect.width, rect.y + rect.height); g.drawLine(rect.x + rect.width, rect.y, rect.x + rect.width, rect.y + rect.height); Color focusColor = UIManager.getColor("Focus.color"); int transparencyOutline = 128; int transparencyInline = 180; if (focusColor == null) { focusColor = UIManager.getColor("textHighlight"); transparencyOutline = 128; transparencyInline = 255; } g.setColor(new Color(focusColor.getRed(), focusColor.getGreen(), focusColor.getBlue(), transparencyOutline)); g.drawRoundRect(rect.x - 3, rect.y - 3, rect.width + 5, rect.height + 5, 6, 6); g.drawRect(rect.x - 1, rect.y - 1, rect.width + 1, rect.height + 1); g.setColor(new Color(focusColor.getRed(), focusColor.getGreen(), focusColor.getBlue(), transparencyInline)); g.drawRoundRect(rect.x - 2, rect.y - 2, rect.width + 3, rect.height + 3, 4, 4); // Draw corners g.setColor(UIManager.getColor("Panel.background")); g.drawLine(rect.x - 3, rect.y - 3, rect.x - 2, rect.y - 3); g.drawLine(rect.x - 3, rect.y - 2, rect.x - 3, rect.y - 2); g.drawLine(rect.x + rect.width + 1, rect.y - 3, rect.x + rect.width + 2, rect.y - 3); g.drawLine(rect.x + rect.width + 2, rect.y - 2, rect.x + rect.width + 2, rect.y - 2); g.drawLine(rect.x - 3, rect.y + rect.height + 2, rect.x - 2, rect.y + rect.height + 2); g.drawLine(rect.x - 3, rect.y + rect.height + 1, rect.x - 3, rect.y + rect.height + 1); g.drawLine(rect.x + rect.width + 1, rect.y + rect.height + 2, rect.x + rect.width + 2, rect.y + rect.height + 2); g.drawLine(rect.x + rect.width + 2, rect.y + rect.height + 1, rect.x + rect.width + 2, rect.y + rect.height + 1); g.setColor(previousColor); } }; } else { if (OperatingSystem.isMacOSX()) { unfocusedViewBorder = BorderFactory.createCompoundBorder( BorderFactory.createLineBorder(UIManager.getColor("Panel.background"), 1), unfocusedViewInteriorBorder); } else { unfocusedViewBorder = BorderFactory.createCompoundBorder( BorderFactory.createEmptyBorder(1, 1, 1, 1), unfocusedViewInteriorBorder); } focusedViewBorder = BorderFactory.createLineBorder(UIManager.getColor("textHighlight"), 2); } } final JComponent feedbackComponent; if (component.getParent() instanceof JViewport && component.getParent().getParent() instanceof JScrollPane) { feedbackComponent = (JComponent)component.getParent().getParent(); } else { feedbackComponent = component; } feedbackComponent.setBorder(unfocusedViewBorder); component.addFocusListener(new FocusListener() { public void focusLost(FocusEvent ev) { feedbackComponent.setBorder(unfocusedViewBorder); } public void focusGained(FocusEvent ev) { feedbackComponent.setBorder(focusedViewBorder); } }); }
public static void installFocusBorder(JComponent component) { if (unfocusedViewBorder == null) { Border unfocusedViewInteriorBorder = new AbstractBorder() { private Color topLeftColor; private Color botomRightColor; private Insets insets = new Insets(1, 1, 1, 1); { if (OperatingSystem.isMacOSX()) { this.topLeftColor = Color.GRAY; this.botomRightColor = Color.LIGHT_GRAY; } else { this.topLeftColor = UIManager.getColor("TextField.darkShadow"); this.botomRightColor = UIManager.getColor("TextField.shadow"); } } public Insets getBorderInsets(Component c) { return this.insets; } public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { Color previousColor = g.getColor(); Rectangle rect = getInteriorRectangle(c, x, y, width, height); g.setColor(topLeftColor); g.drawLine(rect.x - 1, rect.y - 1, rect.x + rect.width, rect.y - 1); g.drawLine(rect.x - 1, rect.y - 1, rect.x - 1, rect.y + rect.height); g.setColor(botomRightColor); g.drawLine(rect.x, rect.y + rect.height, rect.x + rect.width, rect.y + rect.height); g.drawLine(rect.x + rect.width, rect.y, rect.x + rect.width, rect.y + rect.height); g.setColor(previousColor); } }; if (OperatingSystem.isMacOSXLeopardOrSuperior()) { unfocusedViewBorder = BorderFactory.createCompoundBorder( BorderFactory.createLineBorder(UIManager.getColor("Panel.background"), 2), unfocusedViewInteriorBorder); focusedViewBorder = new AbstractBorder() { private Insets insets = new Insets(3, 3, 3, 3); public Insets getBorderInsets(Component c) { return this.insets; } public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { Color previousColor = g.getColor(); // Paint a gradient paint around component Rectangle rect = getInteriorRectangle(c, x, y, width, height); g.setColor(Color.GRAY); g.drawLine(rect.x - 1, rect.y - 1, rect.x + rect.width, rect.y - 1); g.drawLine(rect.x - 1, rect.y - 1, rect.x - 1, rect.y + rect.height); g.setColor(Color.LIGHT_GRAY); g.drawLine(rect.x, rect.y + rect.height, rect.x + rect.width, rect.y + rect.height); g.drawLine(rect.x + rect.width, rect.y, rect.x + rect.width, rect.y + rect.height); Color focusColor = UIManager.getColor("Focus.color"); int transparencyOutline = 128; int transparencyInline = 180; if (focusColor == null) { focusColor = UIManager.getColor("textHighlight"); transparencyOutline = 128; transparencyInline = 255; } g.setColor(new Color(focusColor.getRed(), focusColor.getGreen(), focusColor.getBlue(), transparencyOutline)); g.drawRoundRect(rect.x - 3, rect.y - 3, rect.width + 5, rect.height + 5, 6, 6); g.drawRect(rect.x - 1, rect.y - 1, rect.width + 1, rect.height + 1); g.setColor(new Color(focusColor.getRed(), focusColor.getGreen(), focusColor.getBlue(), transparencyInline)); g.drawRoundRect(rect.x - 2, rect.y - 2, rect.width + 3, rect.height + 3, 4, 4); // Draw corners g.setColor(UIManager.getColor("Panel.background")); g.drawLine(rect.x - 3, rect.y - 3, rect.x - 2, rect.y - 3); g.drawLine(rect.x - 3, rect.y - 2, rect.x - 3, rect.y - 2); g.drawLine(rect.x + rect.width + 1, rect.y - 3, rect.x + rect.width + 2, rect.y - 3); g.drawLine(rect.x + rect.width + 2, rect.y - 2, rect.x + rect.width + 2, rect.y - 2); g.drawLine(rect.x - 3, rect.y + rect.height + 2, rect.x - 2, rect.y + rect.height + 2); g.drawLine(rect.x - 3, rect.y + rect.height + 1, rect.x - 3, rect.y + rect.height + 1); g.drawLine(rect.x + rect.width + 1, rect.y + rect.height + 2, rect.x + rect.width + 2, rect.y + rect.height + 2); g.drawLine(rect.x + rect.width + 2, rect.y + rect.height + 1, rect.x + rect.width + 2, rect.y + rect.height + 1); g.setColor(previousColor); } }; } else { if (OperatingSystem.isMacOSX()) { unfocusedViewBorder = BorderFactory.createCompoundBorder( BorderFactory.createLineBorder(UIManager.getColor("Panel.background"), 1), unfocusedViewInteriorBorder); } else { unfocusedViewBorder = BorderFactory.createCompoundBorder( BorderFactory.createEmptyBorder(1, 1, 1, 1), unfocusedViewInteriorBorder); } focusedViewBorder = BorderFactory.createLineBorder(UIManager.getColor("textHighlight"), 2); } } final JComponent feedbackComponent; if (component.getParent() instanceof JViewport && component.getParent().getParent() instanceof JScrollPane) { feedbackComponent = (JComponent)component.getParent().getParent(); } else { feedbackComponent = component; } feedbackComponent.setBorder(unfocusedViewBorder); component.addFocusListener(new FocusListener() { public void focusLost(FocusEvent ev) { feedbackComponent.setBorder(unfocusedViewBorder); } public void focusGained(FocusEvent ev) { feedbackComponent.setBorder(focusedViewBorder); } }); }
diff --git a/Core/util.bundle/src/de/hszg/atocc/core/util/compile/AbstractExecutor.java b/Core/util.bundle/src/de/hszg/atocc/core/util/compile/AbstractExecutor.java index dc0e8d6..52af667 100644 --- a/Core/util.bundle/src/de/hszg/atocc/core/util/compile/AbstractExecutor.java +++ b/Core/util.bundle/src/de/hszg/atocc/core/util/compile/AbstractExecutor.java @@ -1,109 +1,109 @@ package de.hszg.atocc.core.util.compile; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public abstract class AbstractExecutor implements Executor { protected static final Charset UTF8 = Charset.forName("UTF-8"); private ZipOutputStream zip; private Path tempDirectory; private Path srcDirectory; private TaskDefinition task; @Override public final void execute(TaskDefinition taskDefinition, ZipOutputStream stream) throws IOException, CompilationException { zip = stream; task = taskDefinition; try { initialize(); execute(); } catch (IOException | CompilationException e) { throw e; } finally { cleanUp(); } } protected final void addFileToZip(File file) throws IOException { final byte[] data = Files.readAllBytes(Paths.get(file.getAbsolutePath())); zip.putNextEntry(new ZipEntry(file.getName())); zip.write(data); zip.closeEntry(); } protected final void addFileToZip(File file, String dir) throws IOException { final byte[] data = Files.readAllBytes(Paths.get(file.getAbsolutePath())); zip.putNextEntry(new ZipEntry(dir + "/" + file.getName())); zip.write(data); zip.closeEntry(); } protected final void addDirectoryToZip(String dir) throws IOException { zip.putNextEntry(new ZipEntry(dir)); zip.closeEntry(); } protected final TaskDefinition getTask() { return task; } protected final Path getTempDirectory() { return tempDirectory; } protected final Path getSourceDirectory() { return srcDirectory; } protected void initialize() throws IOException { tempDirectory = Files.createTempDirectory("atocc.compile"); srcDirectory = Paths.get(tempDirectory.toAbsolutePath().toString(), "src"); Files.createDirectory(srcDirectory); } protected abstract void execute() throws CompilationException; protected final void cleanUp() throws IOException { deleteTempDirectory(); } private void deleteTempDirectory() throws IOException { Files.walkFileTree(tempDirectory, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override - public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { + public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException { - if (exc == null) { + if (e == null) { Files.delete(dir); return FileVisitResult.CONTINUE; } else { - throw exc; + throw e; } } }); } }
false
true
private void deleteTempDirectory() throws IOException { Files.walkFileTree(tempDirectory, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { if (exc == null) { Files.delete(dir); return FileVisitResult.CONTINUE; } else { throw exc; } } }); }
private void deleteTempDirectory() throws IOException { Files.walkFileTree(tempDirectory, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException { if (e == null) { Files.delete(dir); return FileVisitResult.CONTINUE; } else { throw e; } } }); }
diff --git a/src/rs/pedjaapps/KernelTuner/ui/KernelTuner.java b/src/rs/pedjaapps/KernelTuner/ui/KernelTuner.java index 3a21a3b..58819ef 100644 --- a/src/rs/pedjaapps/KernelTuner/ui/KernelTuner.java +++ b/src/rs/pedjaapps/KernelTuner/ui/KernelTuner.java @@ -1,2005 +1,2005 @@ /* * This file is part of the Kernel Tuner. * * Copyright Predrag Čokulov <[email protected]> * * Kernel Tuner is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Kernel Tuner is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Kernel Tuner. If not, see <http://www.gnu.org/licenses/>. */ package rs.pedjaapps.KernelTuner.ui; import android.app.*; import android.app.ActivityManager.*; import android.content.*; import android.content.pm.*; import android.content.res.*; import android.graphics.*; import android.os.*; import android.preference.*; import android.util.*; import android.view.*; import android.view.View.*; import android.widget.*; import com.actionbarsherlock.app.*; import com.google.ads.*; import java.io.*; import java.util.*; import rs.pedjaapps.KernelTuner.*; import rs.pedjaapps.KernelTuner.helpers.*; import rs.pedjaapps.KernelTuner.services.*; import rs.pedjaapps.KernelTuner.tools.*; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import java.lang.Process; public class KernelTuner extends SherlockActivity { private List<IOHelper.FreqsEntry> freqEntries; private List<IOHelper.VoltageList> voltageFreqs; private List<String> voltages = new ArrayList<String>(); private TextView batteryLevel; private TextView batteryTemp; private TextView cputemptxt; private String tempPref; private long mLastBackPressTime = 0; private Toast mToast; private RelativeLayout tempLayout; private AlertDialog alert; private String tmp; int i = 0; Context c; private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() { @Override public void onReceive(Context arg0, Intent intent) { int level = intent.getIntExtra("level", 0); double temperature = intent.getIntExtra( BatteryManager.EXTRA_TEMPERATURE, 0) / 10; if (tempPref.equals("fahrenheit")) { temperature = (temperature * 1.8) + 32; batteryTemp.setText(((int) temperature) + "°F"); if (temperature <= 104) { batteryTemp.setTextColor(Color.GREEN); } else if (temperature > 104 && temperature < 131) { batteryTemp.setTextColor(Color.YELLOW); } else if (temperature >= 131 && temperature < 140) { batteryTemp.setTextColor(Color.RED); } else if (temperature >= 140) { batteryTemp.setTextColor(Color.RED); } } else if (tempPref.equals("celsius")) { batteryTemp.setText(temperature + "°C"); if (temperature < 45) { batteryTemp.setTextColor(Color.GREEN); } else if (temperature > 45 && temperature < 55) { batteryTemp.setTextColor(Color.YELLOW); } else if (temperature >= 55 && temperature < 60) { batteryTemp.setTextColor(Color.RED); } else if (temperature >= 60) { batteryTemp.setTextColor(Color.RED); } } else if (tempPref.equals("kelvin")) { temperature = temperature + 273.15; batteryTemp.setText(temperature + "°K"); if (temperature < 318.15) { batteryTemp.setTextColor(Color.GREEN); } else if (temperature > 318.15 && temperature < 328.15) { batteryTemp.setTextColor(Color.YELLOW); } else if (temperature >= 328.15 && temperature < 333.15) { batteryTemp.setTextColor(Color.RED); } else if (temperature >= 333.15) { batteryTemp.setTextColor(Color.RED); } } // /F = (C x 1.8) + 32 batteryLevel.setText(level + "%"); if (level < 15 && level >= 5) { batteryLevel.setTextColor(Color.RED); } else if (level > 15 && level <= 30) { batteryLevel.setTextColor(Color.YELLOW); } else if (level > 30) { batteryLevel.setTextColor(Color.GREEN); } else if (level < 5) { batteryLevel.setTextColor(Color.RED); } } }; private boolean thread = true; private String freqcpu0 = "offline"; private String freqcpu1= "offline"; private String cpu0max = " "; private String cpu1max = " "; private String cpu2max = " "; private String cpu3max = " "; private String freqcpu2 = "offline"; private String freqcpu3 = "offline"; private float fLoad; private TextView cpu0prog; private TextView cpu1prog; private TextView cpu2prog; private TextView cpu3prog; private ProgressBar cpu0progbar; private ProgressBar cpu1progbar; private ProgressBar cpu2progbar; private ProgressBar cpu3progbar; private List<String> freqlist = new ArrayList<String>(); private SharedPreferences preferences; private ProgressDialog pd = null; private int load; private Handler mHandler; private SharedPreferences.Editor editor; private class CPUToggle extends AsyncTask<String, Void, Object> { @Override protected Object doInBackground(String... args) { File file = new File("/sys/devices/system/cpu/cpu"+args[0]+"/cpufreq/scaling_governor"); if(file.exists()){ RootExecuter.exec(new String[]{ "echo 1 > /sys/kernel/msm_mpdecision/conf/enabled\n", "chmod 777 /sys/devices/system/cpu/cpu"+args[0]+"/online\n", "echo 0 > /sys/devices/system/cpu/cpu"+args[0]+"/online\n", "chown system /sys/devices/system/cpu/cpu"+args[0]+"/online\n"}); } else{ RootExecuter.exec(new String[]{ "echo 0 > /sys/kernel/msm_mpdecision/conf/enabled\n", "chmod 666 /sys/devices/system/cpu/cpu"+args[0]+"/online\n", "echo 1 > /sys/devices/system/cpu/cpu"+args[0]+"/online\n", "chmod 444 /sys/devices/system/cpu/cpu"+args[0]+"/online\n", "chown system /sys/devices/system/cpu/cpu"+args[0]+"/online\n"}); } return ""; } @Override protected void onPostExecute(Object result) { KernelTuner.this.pd.dismiss(); } } private class mountDebugFs extends AsyncTask<String, Void, Object> { @Override protected Object doInBackground(String... args) { RootExecuter.exec(new String[]{ "mount -t debugfs debugfs /sys/kernel/debug\n"}); return ""; } @Override protected void onPostExecute(Object result) { } } private class enableTempMonitor extends AsyncTask<String, Void, Object> { @Override protected Object doInBackground(String... args) { RootExecuter.exec(new String[]{ "chmod 777 /sys/devices/virtual/thermal/thermal_zone1/mode\n", "chmod 777 /sys/devices/virtual/thermal/thermal_zone0/mode\n", "echo -n enabled > /sys/devices/virtual/thermal/thermal_zone1/mode\n", "echo -n enabled > /sys/devices/virtual/thermal/thermal_zone0/mode\n"}); return ""; } } boolean first; boolean isLight; String theme; boolean dump; Button[] buttons; @Override public void onCreate(Bundle savedInstanceState) { /*StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll().build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectAll().build());*/ c = this; freqEntries = IOHelper.frequencies(); voltageFreqs = IOHelper.voltages(); preferences = PreferenceManager.getDefaultSharedPreferences(c); editor = preferences.edit(); theme = preferences.getString("theme", "light"); if (theme.equals("light")) { setTheme(R.style.Theme_Sherlock_Light); } else if (theme.equals("dark")) { setTheme(R.style.Theme_Sherlock); } else if (theme.equals("light_dark_action_bar")) { setTheme(R.style.Theme_Sherlock_Light_DarkActionBar); } super.onCreate(savedInstanceState); setContentView(R.layout.main); mHandler = new Handler(); cpu0prog = (TextView)findViewById(R.id.ptextView3); cpu1prog = (TextView)findViewById(R.id.ptextView4); cpu2prog = (TextView)findViewById(R.id.ptextView7); cpu3prog = (TextView)findViewById(R.id.ptextView8); cpu0progbar = (ProgressBar)findViewById(R.id.progressBar1); cpu1progbar = (ProgressBar)findViewById(R.id.progressBar2); cpu2progbar = (ProgressBar)findViewById(R.id.progressBar3); cpu3progbar = (ProgressBar)findViewById(R.id.progressBar4); /** * Get temperature unit from preferences */ tempPref = preferences.getString("temp", "celsius"); batteryLevel = (TextView) findViewById(R.id.textView42); batteryTemp = (TextView) findViewById(R.id.textView40); tempLayout = (RelativeLayout) findViewById(R.id.test1a); /** * Extract assets if first launch */ first = preferences.getBoolean("first_launch", false); if (first == false) { CopyAssets(); } ActionBar actionBar = getSupportActionBar(); actionBar.setSubtitle("Various kernel and system tuning"); actionBar.setHomeButtonEnabled(false); File file = new File("/sys/kernel/debug"); if (file.exists() && file.list().length > 0) { } else { new mountDebugFs().execute(); } /* * Enable temperature monitor */ if (IOHelper.isTempEnabled() == false) { new enableTempMonitor().execute(); } /* * Load ads if not disabled */ boolean ads = preferences.getBoolean("ads", true); if (ads == true) { AdView adView = (AdView)findViewById(R.id.ad); adView.loadAd(new AdRequest()); } editor.putString("kernel", IOHelper.kernel()); editor.commit(); /** * Show changelog if application updated */ changelog(); /** * Read all available frequency steps */ for(IOHelper.FreqsEntry f: freqEntries){ freqlist.add(new StringBuilder().append(f.getFreq()).toString()); } /*for(CPUInfo.FreqsEntry f: freqEntries){ freqNames.add(f.getFreqName()); }*/ for (IOHelper.VoltageList v : voltageFreqs) { voltages.add(new StringBuilder().append(v.getFreq()).toString()); } initialCheck(); /*** * Create new thread that will loop and show current frequency for each * core */ new Thread(new Runnable() { @Override public void run() { while (thread) { try { Thread.sleep(1000); freqcpu0 = IOHelper.cpu0CurFreq(); cpu0max = IOHelper.cpu0MaxFreq(); tmp = IOHelper.cpuTemp(); if (IOHelper.cpu1Online() == true) { freqcpu1 = IOHelper.cpu1CurFreq(); cpu1max = IOHelper.cpu1MaxFreq(); } if (IOHelper.cpu2Online() == true) { freqcpu2 = IOHelper.cpu2CurFreq(); cpu2max = IOHelper.cpu2MaxFreq(); } if (IOHelper.cpu3Online() == true) { freqcpu3 = IOHelper.cpu3CurFreq(); cpu3max = IOHelper.cpu3MaxFreq(); } mHandler.post(new Runnable() { @Override public void run() { cpuTemp(tmp); cpu0update(); if (IOHelper.cpu1Online()) { cpu1update(); } if (IOHelper.cpu2Online()) { cpu2update(); } if (IOHelper.cpu3Online()) { cpu3update(); } } }); } catch (Exception e) { } } } }).start(); /** * Declare buttons and set onClickListener for each */ Button gpu = (Button) findViewById(R.id.button3); gpu.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent myIntent = new Intent(c, Gpu.class); c.startActivity(myIntent); } }); gpu.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View arg0) { return true; } }); Button voltage = (Button) findViewById(R.id.button6); voltage.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent myIntent = new Intent(c, VoltageActivity.class); c.startActivity(myIntent); } }); Button cpu = (Button) findViewById(R.id.button2); cpu.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String cpu = preferences.getString("show_cpu_as", "full"); Intent myIntent = null; if(cpu.equals("full")){ myIntent = new Intent(c, CPUActivity.class); } else if(cpu.equals("minimal")){ myIntent = new Intent(c, CPUActivityOld.class); } startActivity(myIntent); } }); Button tis = (Button) findViewById(R.id.button5); tis.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String tisChoice = preferences.getString("tis_open_as", "ask"); if (tisChoice.equals("ask")) { AlertDialog.Builder builder = new AlertDialog.Builder( c); builder.setTitle("Display As"); LayoutInflater inflater = (LayoutInflater) c .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.tis_dialog, null); ImageView list = (ImageView) view .findViewById(R.id.imageView1); ImageView chart = (ImageView) view .findViewById(R.id.imageView2); final CheckBox remember = (CheckBox) view .findViewById(R.id.checkBox1); list.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent myIntent = new Intent(c, TISActivity.class); startActivity(myIntent); if (remember.isChecked()) { editor.putString("tis_open_as", "list"); editor.commit(); } alert.dismiss(); } }); chart.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent myIntent = new Intent(c, TISActivityChart.class); startActivity(myIntent); if (remember.isChecked()) { editor.putString("tis_open_as", "chart"); editor.commit(); } alert.dismiss(); } }); builder.setView(view); alert = builder.create(); alert.show(); } else if (tisChoice.equals("list")) { Intent myIntent = new Intent(c, TISActivity.class); startActivity(myIntent); } else if (tisChoice.equals("chart")) { Intent myIntent = new Intent(c, TISActivityChart.class); startActivity(myIntent); } } }); Button mpdec = (Button) findViewById(R.id.button7); mpdec.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent myIntent = null; if(new File(Constants.MPDEC_THR_DOWN).exists()){ myIntent = new Intent(c, Mpdecision.class); } else if(new File(Constants.MPDEC_THR_0).exists()){ myIntent = new Intent(c, MpdecisionNew.class); } startActivity(myIntent); } }); Button misc = (Button) findViewById(R.id.button4); misc.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent myIntent = new Intent(c, MiscTweaks.class); startActivity(myIntent); } }); Button cpu1toggle = (Button)findViewById(R.id.button1); cpu1toggle.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { KernelTuner.this.pd = ProgressDialog.show(c, null, getResources().getString(R.string.applying_settings), true, true); new CPUToggle().execute(new String[] {"1"}); } }); Button cpu2toggle = (Button) findViewById(R.id.button8); cpu2toggle.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { KernelTuner.this.pd = ProgressDialog.show(c, null, getResources().getString(R.string.applying_settings), true, true); new CPUToggle().execute(new String[] {"2"}); } }); Button cpu3toggle = (Button) findViewById(R.id.button9); cpu3toggle.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { KernelTuner.this.pd = ProgressDialog.show(c, null, getResources().getString(R.string.applying_settings), true, true); new CPUToggle().execute(new String[] {"3"}); } }); Button governor = (Button) findViewById(R.id.button10); governor.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent myIntent = new Intent(c, GovernorActivity.class); startActivity(myIntent); } }); Button oom = (Button) findViewById(R.id.button13); oom.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent myIntent = new Intent(c, OOM.class); startActivity(myIntent); } }); Button profiles = (Button)findViewById(R.id.button12); profiles.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent myIntent = new Intent(c, Profiles.class); startActivity(myIntent); } }); Button thermald = (Button)findViewById(R.id.button11); thermald.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent myIntent = new Intent(c, Thermald.class); startActivity(myIntent); } }); Button sd = (Button)findViewById(R.id.button15); sd.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent myIntent = new Intent(c, SDScannerConfigActivity.class); startActivity(myIntent); } }); Button sys = (Button)findViewById(R.id.button14); sys.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent myIntent = new Intent(c, SystemInfo.class); startActivity(myIntent); } }); //buttons = new Button[] {cpu, tis, voltage, governor, mpdec, thermald, //gpu, misc, profiles, oom, sd, sys}; /*for(int i =0; i<buttons.length; i++){ buttons[i].startAnimation(l2r); }*/ /* mHandler.postDelayed(new Runnable(){ @Override public void run(){ buttons[0].startAnimation(l2r); } }, 500); mHandler.postDelayed(new Runnable(){ @Override public void run(){ buttons[1].startAnimation(l2r); } }, 1000);*/ //cpu.startAnimation(l2r); /*final Timer timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { if(buttons.length>i){ buttons[i].startAnimation(l2r); i++; } else{ timer.cancel(); } } }); } }, 0, 500);*/ startCpuLoadThread(); if (preferences.getBoolean("notificationService", false) == true && isNotificationServiceRunning() == false) { startService(new Intent(c, NotificationService.class)); } else if (preferences.getBoolean("notificationService", false) == false && isNotificationServiceRunning() == true) { stopService(new Intent(c, NotificationService.class)); } } @Override public void onPause() { super.onPause(); } @Override protected void onResume() { /** * Register BroadcastReceiver that will listen for battery changes and * update ui */ this.registerReceiver(this.mBatInfoReceiver, new IntentFilter( Intent.ACTION_BATTERY_CHANGED)); /** * I init.d is selected for restore settings on boot make inid.d files * else remove them */ String boot = preferences.getString("boot", "init.d"); if (boot.equals("init.d")) { initdExport(); } else { new Initd().execute(new String[] { "rm" }); } super.onResume(); } @Override public void onStop() { /** * Unregister receiver */ if (mBatInfoReceiver != null) { unregisterReceiver(mBatInfoReceiver); mBatInfoReceiver = null; } super.onStop(); } @Override public void onDestroy() { /** * set thread false so that cpu info thread stop repeating */ super.onDestroy(); thread = false; java.lang.System.exit(0); } private void setCpuLoad(){ TextView cpuLoadTxt = (TextView)findViewById(R.id.textView1); ProgressBar cpuLoad = (ProgressBar)findViewById(R.id.progressBar5); cpuLoad.setProgress(load); cpuLoadTxt.setText(load+"%"); } /** * Start new thread that will get cpu load and update UI */ private void startCpuLoadThread() { // Do something long Runnable runnable = new Runnable() { @Override public void run() { while(thread) { try { RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r"); String load = reader.readLine(); String[] toks = load.split(" "); long idle1 = Long.parseLong(toks[5]); long cpu1 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4]) + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]); try { Thread.sleep(360); } catch (Exception e) {} reader.seek(0); load = reader.readLine(); reader.close(); toks = load.split(" "); long idle2 = Long.parseLong(toks[5]); long cpu2 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4]) + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]); fLoad = (float)(cpu2 - cpu1) / ((cpu2 + idle2) - (cpu1 + idle1)); } catch (IOException ex) { ex.printStackTrace(); } load =(int) (fLoad*100); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } mHandler.post(new Runnable() { @Override public void run() { setCpuLoad(); // progress.setProgress(value); } }); } } }; new Thread(runnable).start(); } /** * Display changelog if version is higher than one stored on shared preferences than store curent version*/ private void changelog() { String versionpref = preferences.getString("version", ""); try { PackageInfo pInfo = getPackageManager().getPackageInfo( getPackageName(), 0); String version = pInfo.versionName; if (!versionpref.equals(version)) { Intent myIntent = new Intent(c, Changelog.class); startActivity(myIntent); if (first == true) { CopyAssets(); } } editor.putString("version", version); editor.commit(); } catch (PackageManager.NameNotFoundException e) { } } /** * CPU Temperature */ private void cpuTemp(String cputemp) { cputemptxt = (TextView) findViewById(R.id.textView38); tempLayout.setVisibility(View.VISIBLE); /** * If fahrenheit is selected in settings, convert temp to * fahreinheit */ if(!cputemp.equals("") || cputemp.length()!=0) { if (tempPref.equals("fahrenheit")) { cputemp = String .valueOf((int) (Double.parseDouble(cputemp) * 1.8) + 32); cputemptxt.setText(cputemp + "°F"); int temp = Integer.parseInt(cputemp); if (temp < 113) { cputemptxt.setTextColor(Color.GREEN); // cpuTempWarningStop(); } else if (temp >= 113 && temp < 138) { cputemptxt.setTextColor(Color.YELLOW); // cpuTempWarningStop(); } else if (temp >= 138) { // cpuTempWarning(); cputemptxt.setTextColor(Color.RED); } } else if (tempPref.equals("celsius")) { cputemptxt.setText(cputemp + "°C"); int temp = Integer.parseInt(cputemp); if (temp < 45) { cputemptxt.setTextColor(Color.GREEN); // cpuTempWarningStop(); } else if (temp >= 45 && temp <= 59) { cputemptxt.setTextColor(Color.YELLOW); // cpuTempWarningStop(); } else if (temp > 59) { // cpuTempWarning(); cputemptxt.setTextColor(Color.RED); } } /** * If kelvin is selected in settings convert cpu temp to kelvin */ else if (tempPref.equals("kelvin")) { cputemp = String .valueOf((int) (Double.parseDouble(cputemp) + 273.15)); cputemptxt.setText(cputemp + "°K"); int temp = Integer.parseInt(cputemp); if (temp < 318) { cputemptxt.setTextColor(Color.GREEN); } else if (temp >= 318 && temp <= 332) { cputemptxt.setTextColor(Color.YELLOW); } else if (temp > 332) { cputemptxt.setTextColor(Color.RED); } } } else{ tempLayout.setVisibility(View.GONE); } } private void initialCheck() { /** * Show/hide certain Views depending on number of cpus */ if (IOHelper.cpu1Online() == true) { Button b2 = (Button) findViewById(R.id.button1); b2.setVisibility(View.VISIBLE); ProgressBar cpu1progbar = (ProgressBar)findViewById(R.id.progressBar2); cpu1progbar.setVisibility(View.VISIBLE); TextView tv1 = (TextView) findViewById(R.id.ptextView2); tv1.setVisibility(View.VISIBLE); TextView tv4 = (TextView) findViewById(R.id.ptextView4); tv4.setVisibility(View.VISIBLE); } else { Button b2 = (Button) findViewById(R.id.button1); b2.setVisibility(View.GONE); ProgressBar cpu1progbar = (ProgressBar)findViewById(R.id.progressBar2); cpu1progbar.setVisibility(View.GONE); TextView tv1 = (TextView) findViewById(R.id.ptextView2); tv1.setVisibility(View.GONE); TextView tv4 = (TextView) findViewById(R.id.ptextView4); tv4.setVisibility(View.GONE); } if (IOHelper.cpu2Online() == true) { Button b3 = (Button) findViewById(R.id.button8); b3.setVisibility(View.VISIBLE); ProgressBar cpu1progbar = (ProgressBar)findViewById(R.id.progressBar3); cpu1progbar.setVisibility(View.VISIBLE); TextView tv1 = (TextView) findViewById(R.id.ptextView5); tv1.setVisibility(View.VISIBLE); TextView tv4 = (TextView) findViewById(R.id.ptextView7); tv4.setVisibility(View.VISIBLE); } else { Button b3 = (Button) findViewById(R.id.button8); b3.setVisibility(View.GONE); ProgressBar cpu1progbar = (ProgressBar)findViewById(R.id.progressBar3); cpu1progbar.setVisibility(View.GONE); TextView tv1 = (TextView) findViewById(R.id.ptextView5); tv1.setVisibility(View.GONE); TextView tv4 = (TextView) findViewById(R.id.ptextView7); tv4.setVisibility(View.GONE); } if (IOHelper.cpu3Online() == true) { Button b4 = (Button) findViewById(R.id.button9); b4.setVisibility(View.VISIBLE); ProgressBar cpu1progbar = (ProgressBar)findViewById(R.id.progressBar4); cpu1progbar.setVisibility(View.VISIBLE); TextView tv1 = (TextView) findViewById(R.id.ptextView6); tv1.setVisibility(View.VISIBLE); TextView tv4 = (TextView) findViewById(R.id.ptextView8); tv4.setVisibility(View.VISIBLE); } else { Button b4 = (Button) findViewById(R.id.button9); b4.setVisibility(View.GONE); ProgressBar cpu1progbar = (ProgressBar)findViewById(R.id.progressBar4); cpu1progbar.setVisibility(View.GONE); TextView tv1 = (TextView) findViewById(R.id.ptextView6); tv1.setVisibility(View.GONE); TextView tv4 = (TextView) findViewById(R.id.ptextView8); tv4.setVisibility(View.GONE); } /** * Check for certain files in sysfs and if they doesnt exists hide * depending views */ File file4 = new File(Constants.CPU0_FREQS); File file5 = new File(Constants.TIMES_IN_STATE_CPU0); try { InputStream fIn = new FileInputStream(file4); fIn.close(); } catch (FileNotFoundException e) { try { InputStream fIn = new FileInputStream(file5); fIn.close(); } catch (FileNotFoundException e2) { Button cpu = (Button) findViewById(R.id.button2); cpu.setVisibility(View.GONE); } catch (IOException e1) { } } catch (IOException e) { } File file = new File(Constants.VOLTAGE_PATH); try { InputStream fIn = new FileInputStream(file); fIn.close(); } catch (FileNotFoundException e) { File file2 = new File(Constants.VOLTAGE_PATH_TEGRA_3); try { InputStream fIn = new FileInputStream(file2); fIn.close(); } catch (FileNotFoundException ex) { Button voltage = (Button) findViewById(R.id.button6); voltage.setVisibility(View.GONE); } catch (IOException e1) { } } catch (IOException e) { } File file2 = new File(Constants.TIMES_IN_STATE_CPU0); try { InputStream fIn = new FileInputStream(file2); fIn.close(); } catch (FileNotFoundException e) { Button times = (Button) findViewById(R.id.button5); times.setVisibility(View.GONE); } catch (IOException e) { } File file6 = new File(Constants.MPDECISION); try { InputStream fIn = new FileInputStream(file6); fIn.close(); } catch (FileNotFoundException e) { Button mpdec = (Button) findViewById(R.id.button7); mpdec.setVisibility(View.GONE); } catch (IOException e) { } File file7 = new File(Constants.THERMALD); try { InputStream fIn = new FileInputStream(file7); fIn.close(); } catch (FileNotFoundException e) { Button td = (Button) findViewById(R.id.button11); td.setVisibility(View.GONE); } catch (IOException e) { } File file3 = new File(Constants.GPU_3D); try { InputStream fIn = new FileInputStream(file3); fIn.close(); } catch (FileNotFoundException e) { Button gpu = (Button) findViewById(R.id.button3); gpu.setVisibility(View.GONE); } catch (IOException e) { } } /** * Create init.d files and export them to private application folder */ private void initdExport() { SharedPreferences sharedPrefs = PreferenceManager .getDefaultSharedPreferences(c); String gpu3d = sharedPrefs.getString("gpu3d", ""); String gpu2d = sharedPrefs.getString("gpu2d", ""); String hw = sharedPrefs.getString("hw", ""); String cdepth = sharedPrefs.getString("cdepth", ""); String cpu1min = sharedPrefs.getString("cpu1min", ""); String cpu1max = sharedPrefs.getString("cpu1max", ""); String cpu0max = sharedPrefs.getString("cpu0max", ""); String cpu0min = sharedPrefs.getString("cpu0min", ""); String cpu3min = sharedPrefs.getString("cpu3min", ""); String cpu3max = sharedPrefs.getString("cpu3max", ""); String cpu2max = sharedPrefs.getString("cpu2max", ""); String cpu2min = sharedPrefs.getString("cpu2min", ""); String fastcharge = sharedPrefs.getString("fastcharge", ""); String mpdecisionscroff = sharedPrefs.getString("mpdecisionscroff", ""); String backbuff = sharedPrefs.getString("backbuf", ""); String vsync = sharedPrefs.getString("vsync", ""); String led = sharedPrefs.getString("led", ""); String cpu0gov = sharedPrefs.getString("cpu0gov", ""); String cpu1gov = sharedPrefs.getString("cpu1gov", ""); String cpu2gov = sharedPrefs.getString("cpu2gov", ""); String cpu3gov = sharedPrefs.getString("cpu3gov", ""); String io = sharedPrefs.getString("io", ""); String sdcache = sharedPrefs.getString("sdcache", ""); String delaynew = sharedPrefs.getString("delaynew", ""); String pausenew = sharedPrefs.getString("pausenew", ""); String thruploadnew = sharedPrefs.getString("thruploadnew", ""); String thrupmsnew = sharedPrefs.getString("thrupmsnew", ""); String thrdownloadnew = sharedPrefs.getString("thrdownloadnew", ""); String thrdownmsnew = sharedPrefs.getString("thrdownmsnew", ""); String ldt = sharedPrefs.getString("ldt", ""); String s2w = sharedPrefs.getString("s2w", ""); String s2wStart = sharedPrefs.getString("s2wStart", ""); String s2wEnd = sharedPrefs.getString("s2wEnd", ""); String p1freq = sharedPrefs.getString("p1freq", ""); String p2freq = sharedPrefs.getString("p2freq", ""); String p3freq = sharedPrefs.getString("p3freq", ""); String p1low = sharedPrefs.getString("p1low", ""); String p1high = sharedPrefs.getString("p1high", ""); String p2low = sharedPrefs.getString("p2low", ""); String p2high = sharedPrefs.getString("p2high", ""); String p3low = sharedPrefs.getString("p3low", ""); String p3high = sharedPrefs.getString("p3high", ""); boolean swap = sharedPrefs.getBoolean("swap", false); String swapLocation = sharedPrefs.getString("swap_location", ""); String swappiness = sharedPrefs.getString("swappiness", ""); String oom = sharedPrefs.getString("oom", ""); String otg = sharedPrefs.getString("otg", ""); String idle_freq = sharedPrefs.getString("idle_freq", ""); String scroff = sharedPrefs.getString("scroff", ""); String scroff_single = sharedPrefs.getString("scroff_single", ""); String[] thr = new String[6]; String[] tim = new String[6]; thr[0] = sharedPrefs.getString("thr0", ""); thr[1] = sharedPrefs.getString("thr2", ""); thr[2] = sharedPrefs.getString("thr3", ""); thr[3] = sharedPrefs.getString("thr4", ""); thr[4] = sharedPrefs.getString("thr5", ""); thr[5] = sharedPrefs.getString("thr7", ""); tim[0] = sharedPrefs.getString("tim0", ""); tim[1] = sharedPrefs.getString("tim2", ""); tim[2] = sharedPrefs.getString("tim3", ""); tim[3] = sharedPrefs.getString("tim4", ""); tim[4] = sharedPrefs.getString("tim5", ""); tim[5] = sharedPrefs.getString("tim7", ""); String maxCpus = sharedPrefs.getString("max_cpus", ""); String minCpus = sharedPrefs.getString("min_cpus", ""); StringBuilder gpubuilder = new StringBuilder(); gpubuilder.append("#!/system/bin/sh"); gpubuilder.append("\n"); if (!gpu3d.equals("")) { gpubuilder .append("echo ") .append("\"") .append(gpu3d) .append("\"") .append(" > /sys/devices/platform/kgsl-3d0.0/kgsl/kgsl-3d0/max_gpuclk") .append("\n"); } if (!gpu2d.equals("")) { gpubuilder .append("echo ") .append("\"") .append(gpu2d) .append("\"") .append(" > /sys/devices/platform/kgsl-2d0.0/kgsl/kgsl-2d0/max_gpuclk"); gpubuilder.append("\n"); gpubuilder .append("echo ").append( "\"").append( gpu2d).append( "\"").append( " > /sys/devices/platform/kgsl-2d1.1/kgsl/kgsl-2d1/max_gpuclk"); gpubuilder.append("\n"); } String gpu = gpubuilder.toString(); StringBuilder cpubuilder = new StringBuilder(); cpubuilder.append("#!/system/bin/sh"); cpubuilder.append("\n"); /** * cpu0 * */ if (!cpu0gov.equals("")) { cpubuilder .append("chmod 666 /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor \n").append( "echo ").append( "\"").append( cpu0gov).append( "\"").append( " > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor\n").append( "chmod 444 /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor \n"); } if (!cpu0max.equals("")) { cpubuilder .append("chmod 666 /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq \n").append( "echo ").append( "\"").append( cpu0max).append( "\"").append( " > /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq \n").append( "chmod 444 /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq\n"); } if (!cpu0min.equals("")) { cpubuilder .append("chmod 666 /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq \n").append( "echo ").append( "\"").append( cpu0min).append( "\"").append( " > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq \n\n").append( "chmod 444 /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq \n"); } /** * cpu1 * */ if (!cpu1gov.equals("")) { cpubuilder .append("chmod 666 /sys/devices/system/cpu/cpu1/cpufreq/scaling_governor \n").append( "echo ").append( "\"").append( cpu1gov).append( "\"").append( " > /sys/devices/system/cpu/cpu1/cpufreq/scaling_governor\n").append( "chmod 444 /sys/devices/system/cpu/cpu1/cpufreq/scaling_governor \n"); } if (!cpu1max.equals("")) { cpubuilder .append("chmod 666 /sys/devices/system/cpu/cpu1/cpufreq/scaling_max_freq \n").append( "echo ").append( "\"").append( cpu1max).append( "\"").append( " > /sys/devices/system/cpu/cpu1/cpufreq/scaling_max_freq \n").append( "chmod 444 /sys/devices/system/cpu/cpu1/cpufreq/scaling_max_freq \n"); } if (!cpu1min.equals("")) { cpubuilder .append("chmod 666 /sys/devices/system/cpu/cpu1/cpufreq/scaling_min_freq \n").append( "echo ").append( "\"").append( cpu1min).append( "\"").append( " > /sys/devices/system/cpu/cpu1/cpufreq/scaling_min_freq \n").append( "chmod 444 /sys/devices/system/cpu/cpu1/cpufreq/scaling_min_freq \n\n"); } /** * cpu2 * */ if (!cpu2gov.equals("")) { cpubuilder .append("chmod 666 /sys/devices/system/cpu/cpu2/cpufreq/scaling_governor \n").append( "echo ").append( "\"").append( cpu2gov).append( "\"").append( " > /sys/devices/system/cpu/cpu2/cpufreq/scaling_governor\n").append( "chmod 444 /sys/devices/system/cpu/cpu2/cpufreq/scaling_governor \n"); } if (!cpu2max.equals("")) { cpubuilder .append("chmod 666 /sys/devices/system/cpu/cpu2/cpufreq/scaling_max_freq \n").append( "echo ").append( "\"").append( cpu2max).append( "\"").append( " > /sys/devices/system/cpu/cpu2/cpufreq/scaling_max_freq \n").append( "chmod 444 /sys/devices/system/cpu/cpu2/cpufreq/scaling_max_freq \n"); } if (!cpu2min.equals("")) { cpubuilder .append("chmod 666 /sys/devices/system/cpu/cpu2/cpufreq/scaling_min_freq \n").append( "echo ").append( "\"").append( cpu2min).append( "\"").append( " > /sys/devices/system/cpu/cpu2/cpufreq/scaling_min_freq \n").append( "chmod 444 /sys/devices/system/cpu/cpu2/cpufreq/scaling_min_freq \n\n"); } /** * cpu3 * */ if (!cpu3gov.equals("")) { cpubuilder .append("chmod 666 /sys/devices/system/cpu/cpu3/cpufreq/scaling_governor \n").append( "echo ").append( "\"").append( cpu3gov).append( "\"").append( " > /sys/devices/system/cpu/cpu3/cpufreq/scaling_governor\n").append( "chmod 444 /sys/devices/system/cpu/cpu3/cpufreq/scaling_governor \n"); } if (!cpu3max.equals("")) { cpubuilder .append("chmod 666 /sys/devices/system/cpu/cpu3/cpufreq/scaling_max_freq \n").append( "echo ").append( "\"").append( cpu3max).append( "\"").append( " > /sys/devices/system/cpu/cpu3/cpufreq/scaling_max_freq \n").append( "chmod 444 /sys/devices/system/cpu/cpu3/cpufreq/scaling_max_freq \n"); } if (!cpu3min.equals("")) { cpubuilder .append("chmod 666 /sys/devices/system/cpu/cpu3/cpufreq/scaling_min_freq \n").append( "echo ").append( "\"").append( cpu3min).append( "\"").append( " > /sys/devices/system/cpu/cpu3/cpufreq/scaling_min_freq \n").append( "chmod 444 /sys/devices/system/cpu/cpu3/cpufreq/scaling_min_freq \n\n"); } List<String> govSettings = IOHelper.govSettings(); List<String> availableGovs = IOHelper.availableGovs(); for (String s : availableGovs) { for (String st : govSettings) { String temp = sharedPrefs.getString(s + "_" + st, ""); if (!temp.equals("")) { cpubuilder .append("chmod 777 /sys/devices/system/cpu/cpufreq/") .append(s).append( "/").append(st).append("\n"); cpubuilder.append("echo ").append("\"").append(temp).append("\"").append( " > /sys/devices/system/cpu/cpufreq/").append(s).append("/").append(st).append("\n"); } } } String cpu = cpubuilder.toString(); StringBuilder miscbuilder = new StringBuilder(); miscbuilder.append("#!/system/bin/sh \n\n#mount debug filesystem\nmount -t debugfs debugfs /sys/kernel/debug \n\n"); if (!vsync.equals("")) { miscbuilder.append("#vsync\nchmod 777 /sys/kernel/debug/msm_fb/0/vsync_enable \nchmod 777 /sys/kernel/debug/msm_fb/0/hw_vsync_mode \nchmod 777 /sys/kernel/debug/msm_fb/0/backbuff \necho " + "\"" + vsync + "\"" + " > /sys/kernel/debug/msm_fb/0/vsync_enable \n" + "echo " + "\"" + hw + "\"" + " > /sys/kernel/debug/msm_fb/0/hw_vsync_mode \n" + "echo " + "\"" + backbuff + "\"" + " > /sys/kernel/debug/msm_fb/0/backbuff \n\n"); } if (!led.equals("")) { miscbuilder .append("#capacitive buttons backlight\n" + "chmod 777 /sys/devices/platform/leds-pm8058/leds/button-backlight/currents \n" + "echo " + "\"" + led + "\"" + " > /sys/devices/platform/leds-pm8058/leds/button-backlight/currents \n\n"); } if (!fastcharge.equals("")) { miscbuilder.append("#fastcharge\n" + "chmod 777 /sys/kernel/fast_charge/force_fast_charge \n" + "echo " + "\"" + fastcharge + "\"" + " > /sys/kernel/fast_charge/force_fast_charge \n\n"); } if (!cdepth.equals("")) { miscbuilder.append("#color depth\n" + "chmod 777 /sys/kernel/debug/msm_fb/0/bpp \n" + "echo " + "\"" + cdepth + "\"" + " > /sys/kernel/debug/msm_fb/0/bpp \n\n"); } if (!mpdecisionscroff.equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_mpdecision/conf/scroff_single_core \n" + "echo " + "\"" + mpdecisionscroff + "\"" + " > /sys/kernel/msm_mpdecision/conf/scroff_single_core \n"); } if (!delaynew.equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_mpdecision/conf/delay \n" + "echo " + "\"" + delaynew.trim() + "\"" + " > /sys/kernel/msm_mpdecision/conf/delay \n"); } if (!pausenew.equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_mpdecision/conf/pause \n" + "echo " + "\"" + pausenew.trim() + "\"" + " > /sys/kernel/msm_mpdecision/conf/pause \n"); } if (!thruploadnew.equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_mpdecision/conf/nwns_threshold_up \n" + "echo " + "\"" + thruploadnew.trim() + "\"" + " > /sys/kernel/msm_mpdecision/conf/nwns_threshold_up \n"); } if (!thrdownloadnew.equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_mpdecision/conf/nwns_threshold_down \n" + "echo " + "\"" + thrdownloadnew.trim() + "\"" + " > /sys/kernel/msm_mpdecision/conf/nwns_threshold_down \n"); } if (!thrupmsnew.equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_mpdecision/conf/twts_threshold_up\n" + "echo " + "\"" + thrupmsnew.trim() + "\"" + " > /sys/kernel/msm_mpdecision/conf/twts_threshold_up \n"); } if (!thrdownmsnew.equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_mpdecision/conf/twts_threshold_down\n" + "echo " + "\"" + thrdownmsnew.trim() + "\"" + " > /sys/kernel/msm_mpdecision/conf/twts_threshold_down \n\n"); } if(!thr[0].equals("")){ for(int i = 0; i < 8; i++){ miscbuilder.append("chmod 777 /sys/kernel/msm_mpdecision/conf/nwns_threshold_"+i+"\n"); } miscbuilder.append("echo " + thr[1] + " > /sys/kernel/msm_mpdecision/conf/nwns_threshold_"+0+"\n"); miscbuilder.append("echo " + thr[2] + " > /sys/kernel/msm_mpdecision/conf/nwns_threshold_"+2+"\n"); miscbuilder.append("echo " + thr[3] + " > /sys/kernel/msm_mpdecision/conf/nwns_threshold_"+3+"\n"); miscbuilder.append("echo " + thr[4] + " > /sys/kernel/msm_mpdecision/conf/nwns_threshold_"+4+"\n"); miscbuilder.append("echo " + thr[5] + " > /sys/kernel/msm_mpdecision/conf/nwns_threshold_"+5+"\n"); miscbuilder.append("echo " + thr[6] + " > /sys/kernel/msm_mpdecision/conf/nwns_threshold_"+7+"\n"); } if(!tim[0].equals("")){ for(int i = 0; i < 8; i++){ miscbuilder.append("chmod 777 /sys/kernel/msm_mpdecision/conf/twts_threshold_"+i+"\n"); } - miscbuilder.append("echo " + tim[1] + " > /sys/kernel/msm_mpdecision/conf/twts_threshold_"+0+"\n"); - miscbuilder.append("echo " + tim[2] + " > /sys/kernel/msm_mpdecision/conf/twts_threshold_"+2+"\n"); + miscbuilder.append("echo " + tim[0] + " > /sys/kernel/msm_mpdecision/conf/twts_threshold_"+0+"\n"); + miscbuilder.append("echo " + tim[1] + " > /sys/kernel/msm_mpdecision/conf/twts_threshold_"+2+"\n"); miscbuilder.append("echo " + tim[3] + " > /sys/kernel/msm_mpdecision/conf/twts_threshold_"+3+"\n"); - miscbuilder.append("echo " + tim[4] + " > /sys/kernel/msm_mpdecision/conf/twts_threshold_"+4+"\n"); - miscbuilder.append("echo " + tim[5] + " > /sys/kernel/msm_mpdecision/conf/twts_threshold_"+5+"\n"); - miscbuilder.append("echo " + tim[6] + " > /sys/kernel/msm_mpdecision/conf/twts_threshold_"+7+"\n"); + miscbuilder.append("echo " + tim[3] + " > /sys/kernel/msm_mpdecision/conf/twts_threshold_"+4+"\n"); + miscbuilder.append("echo " + tim[4] + " > /sys/kernel/msm_mpdecision/conf/twts_threshold_"+5+"\n"); + miscbuilder.append("echo " + tim[5] + " > /sys/kernel/msm_mpdecision/conf/twts_threshold_"+7+"\n"); } if(!maxCpus.equals("")){ miscbuilder.append("echo " + maxCpus + " > /sys/kernel/msm_mpdecision/conf/max_cpus\n"); } if(!minCpus.equals("")){ miscbuilder.append("echo " + minCpus + " > /sys/kernel/msm_mpdecision/conf/min_cpus\n"); } if (!sdcache.equals("")) { miscbuilder .append("#sd card cache size\n" + "chmod 777 /sys/block/mmcblk1/queue/read_ahead_kb \n" + "chmod 777 /sys/block/mmcblk0/queue/read_ahead_kb \n" + "chmod 777 /sys/devices/virtual/bdi/179:0/read_ahead_kb \n" + "echo " + "\"" + sdcache + "\"" + " > /sys/block/mmcblk1/queue/read_ahead_kb \n" + "echo " + "\"" + sdcache + "\"" + " > /sys/block/mmcblk0/queue/read_ahead_kb \n" + "echo " + "\"" + sdcache + "\"" + " > /sys/devices/virtual/bdi/179:0/read_ahead_kb \n\n"); } if (!io.equals("")) { miscbuilder.append("#IO scheduler\n" + "chmod 777 /sys/block/mmcblk0/queue/scheduler \n" + "chmod 777 /sys/block/mmcblk1/queue/scheduler \n" + "echo " + "\"" + io + "\"" + " > /sys/block/mmcblk0/queue/scheduler \n" + "echo " + "\"" + io + "\"" + " > /sys/block/mmcblk1/queue/scheduler \n\n"); } if (!ldt.equals("")) { miscbuilder .append("#Notification LED Timeout\n" + "chmod 777 /sys/kernel/notification_leds/off_timer_multiplier\n" + "echo " + "\"" + ldt + "\"" + " > /sys/kernel/notification_leds/off_timer_multiplier\n\n"); } if (!s2w.equals("")) { miscbuilder.append("#Sweep2Wake\n" + "chmod 777 /sys/android_touch/sweep2wake\n" + "echo " + "\"" + s2w + "\"" + " > /sys/android_touch/sweep2wake\n\n"); } if (!s2wStart.equals("")) { miscbuilder .append("chmod 777 /sys/android_touch/sweep2wake_startbutton\n" + "echo " + s2wStart + " > /sys/android_touch/sweep2wake_startbutton\n" + "chmod 777 /sys/android_touch/sweep2wake_endbutton\n" + "echo " + s2wEnd + " > /sys/android_touch/sweep2wake_endbutton\n\n"); } if (!p1freq.trim().equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_thermal/conf/allowed_low_freq\n" + "echo " + "\"" + p1freq.trim() + "\"" + " > /sys/kernel/msm_thermal/conf/allowed_low_freq\n"); } if (!p2freq.trim().equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_thermal/conf/allowed_mid_freq\n" + "echo " + "\"" + p2freq.trim() + "\"" + " > /sys/kernel/msm_thermal/conf/allowed_mid_freq\n"); } if (!p3freq.trim().equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_thermal/conf/allowed_max_freq\n" + "echo " + "\"" + p3freq.trim() + "\"" + " > /sys/kernel/msm_thermal/conf/allowed_max_freq\n"); } if (!p1low.trim().equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_thermal/conf/allowed_low_low\n" + "echo " + "\"" + p1low.trim() + "\"" + " > /sys/kernel/msm_thermal/conf/allowed_low_low\n"); } if (!p1high.trim().equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_thermal/conf/allowed_low_high\n" + "echo " + "\"" + p1high.trim() + "\"" + " > /sys/kernel/msm_thermal/conf/allowed_low_high\n"); } if (!p2low.trim().equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_thermal/conf/allowed_mid_low\n" + "echo " + "\"" + p2low.trim() + "\"" + " > /sys/kernel/msm_thermal/conf/allowed_mid_low\n"); } if (!p2high.trim().equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_thermal/conf/allowed_mid_high\n" + "echo " + "\"" + p2high.trim() + "\"" + " > /sys/kernel/msm_thermal/conf/allowed_mid_high\n"); } if (!p3low.trim().equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_thermal/conf/allowed_high_low\n" + "echo " + "\"" + p3low.trim() + "\"" + " > /sys/kernel/msm_thermal/conf/allowed_high_low\n"); } if (!p3high.trim().equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_thermal/conf/allowed_high_high\n" + "echo " + "\"" + p3high.trim() + "\"" + " > /sys/kernel/msm_thermal/conf/allowed_high_high\n"); } if (!idle_freq.equals("")) { miscbuilder.append("echo " + idle_freq + " > /sys/kernel/msm_mpdecision/conf/idle_freq\n"); } if (!scroff.equals("")) { miscbuilder.append("echo " + scroff + " > /sys/kernel/msm_mpdecision/conf/scroff_freq\n"); } if (!scroff_single.equals("")) { miscbuilder .append("echo " + scroff_single + " > /sys/kernel/msm_mpdecision/conf/scroff_single_core\n\n"); } if (swap == true) { miscbuilder.append("echo " + swappiness + " > /proc/sys/vm/swappiness\n" + "swapon " + swapLocation.trim() + "\n\n"); } else if (swap == false) { miscbuilder.append("swapoff " + swapLocation.trim() + "\n\n"); } if (!oom.equals("")) { miscbuilder.append("echo " + oom + " > /sys/module/lowmemorykiller/parameters/minfree\n"); } if (!otg.equals("")) { miscbuilder.append("echo " + otg + " > /sys/kernel/debug/msm_otg/mode\n"); miscbuilder.append("echo " + otg + " > /sys/kernel/debug/otg/mode\n"); } miscbuilder.append("#Umount debug filesystem\n" + "umount /sys/kernel/debug \n"); String misc = miscbuilder.toString(); StringBuilder voltagebuilder = new StringBuilder(); voltagebuilder.append("#!/system/bin/sh \n"); for (String s : voltages) { String temp = sharedPrefs.getString("voltage_" + s, ""); if (!temp.equals("")) { voltagebuilder .append("echo " + "\"" + temp + "\"" + " > /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n"); } } String voltage = voltagebuilder.toString(); try { FileOutputStream fOut = openFileOutput("99ktcputweaks", MODE_PRIVATE); OutputStreamWriter osw = new OutputStreamWriter(fOut); osw.write(cpu); osw.flush(); osw.close(); } catch (IOException ioe) { } try { FileOutputStream fOut = openFileOutput("99ktgputweaks", MODE_PRIVATE); OutputStreamWriter osw = new OutputStreamWriter(fOut); osw.write(gpu); osw.flush(); osw.close(); } catch (IOException ioe) { } try { FileOutputStream fOut = openFileOutput("99ktmisctweaks", MODE_PRIVATE); OutputStreamWriter osw = new OutputStreamWriter(fOut); osw.write(misc); osw.flush(); osw.close(); } catch (IOException ioe) { } try { FileOutputStream fOut = openFileOutput("99ktvoltage", MODE_PRIVATE); OutputStreamWriter osw = new OutputStreamWriter(fOut); osw.write(voltage); osw.flush(); osw.close(); } catch (IOException ioe) { } new Initd().execute(new String[] { "apply" }); } /** Update UI with current frequency */ private void cpu0update() { if(!freqcpu0.equals("offline") && freqcpu0.length()!=0){ cpu0prog.setText(freqcpu0.trim().substring(0, freqcpu0.length()-3)+"MHz"); } else{ cpu0prog.setText("offline"); } if (freqlist != null) { cpu0progbar.setMax(freqlist.indexOf(cpu0max.trim()) + 1); cpu0progbar.setProgress(freqlist.indexOf(freqcpu0.trim()) + 1); } } private void cpu1update() { if(!freqcpu1.equals("offline") && freqcpu1.length()!=0){ cpu1prog.setText(freqcpu1.trim().substring(0, freqcpu1.length()-3)+"MHz"); } else{ cpu1prog.setText("offline"); } if (freqlist != null) { cpu1progbar.setMax(freqlist.indexOf(cpu1max.trim()) + 1); cpu1progbar.setProgress(freqlist.indexOf(freqcpu1.trim()) + 1); } } private void cpu2update() { if(!freqcpu2.equals("offline") && freqcpu2.length()!=0){ cpu2prog.setText(freqcpu2.trim().substring(0, freqcpu2.length()-3)+"MHz"); } else{ cpu2prog.setText("offline"); } if (freqlist != null) { cpu2progbar.setMax(freqlist.indexOf(cpu2max.trim()) + 1); cpu2progbar.setProgress(freqlist.indexOf(freqcpu2.trim()) + 1); } } private void cpu3update() { if(!freqcpu3.equals("offline") && freqcpu3.length()!=0){ cpu3prog.setText(freqcpu3.trim().substring(0, freqcpu3.length()-3)+"MHz"); } else{ cpu3prog.setText("offline"); } if (freqlist != null) { cpu3progbar.setMax(freqlist.indexOf(cpu3max.trim()) + 1); cpu3progbar.setProgress(freqlist.indexOf(freqcpu3.trim()) + 1); } } @Override public boolean onCreateOptionsMenu(Menu menu) { if (theme.equals("light")) { isLight = true; } else if (theme.equals("dark")) { isLight = false; } else if (theme.equals("light_dark_action_bar")) { isLight = false; } menu.add(1, 1, 1, "Settings") .setIcon( isLight ? R.drawable.settings_light : R.drawable.settings_dark) .setShowAsAction( MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT); menu.add(2, 2, 2, "Compatibility Check").setShowAsAction( MenuItem.SHOW_AS_ACTION_NEVER); menu.add(4, 4, 4, "Swap") .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == 1) { startActivity(new Intent(c, Preferences.class)); } else if (item.getItemId() == 2) { startActivity(new Intent(c, CompatibilityCheck.class)); } else if (item.getItemId() == 4) { startActivity(new Intent(c, Swap.class)); } return super.onOptionsItemSelected(item); } /** * Press back button twice to exit application */ @Override public void onBackPressed() { if (mLastBackPressTime < java.lang.System.currentTimeMillis() - 4000) { mToast = Toast.makeText(c, getResources().getString(R.string.press_again_to_exit), Toast.LENGTH_SHORT); mToast.show(); mLastBackPressTime = java.lang.System.currentTimeMillis(); } else { if (mToast != null) mToast.cancel(); KernelTuner.this.finish(); mLastBackPressTime = 0; } } private void CopyAssets() { AssetManager assetManager = getAssets(); String[] files = null; File file; try { files = assetManager.list(""); } catch (IOException e) { Log.e("tag", e.getMessage()); } for (String filename : files) { InputStream in = null; OutputStream out = null; try { in = assetManager.open(filename); file = new File(this.getFilesDir().getAbsolutePath() + "/" + filename); out = new FileOutputStream(file); copyFile(in, out); in.close(); Runtime.getRuntime().exec("chmod 755 " + file); file.setExecutable(false); in = null; out.flush(); out.close(); out = null; } catch (Exception e) { Log.e("tag", e.getMessage()); } } editor.putBoolean("first_launch", true); editor.commit(); } private void copyFile(InputStream in, OutputStream out) throws IOException { byte[] buffer = new byte[1024]; int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } } private boolean isNotificationServiceRunning() { ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); for (RunningServiceInfo service : manager .getRunningServices(Integer.MAX_VALUE)) { if (NotificationService.class.getName().equals( service.service.getClassName())) { return true; } } return false; } }
false
true
private void initdExport() { SharedPreferences sharedPrefs = PreferenceManager .getDefaultSharedPreferences(c); String gpu3d = sharedPrefs.getString("gpu3d", ""); String gpu2d = sharedPrefs.getString("gpu2d", ""); String hw = sharedPrefs.getString("hw", ""); String cdepth = sharedPrefs.getString("cdepth", ""); String cpu1min = sharedPrefs.getString("cpu1min", ""); String cpu1max = sharedPrefs.getString("cpu1max", ""); String cpu0max = sharedPrefs.getString("cpu0max", ""); String cpu0min = sharedPrefs.getString("cpu0min", ""); String cpu3min = sharedPrefs.getString("cpu3min", ""); String cpu3max = sharedPrefs.getString("cpu3max", ""); String cpu2max = sharedPrefs.getString("cpu2max", ""); String cpu2min = sharedPrefs.getString("cpu2min", ""); String fastcharge = sharedPrefs.getString("fastcharge", ""); String mpdecisionscroff = sharedPrefs.getString("mpdecisionscroff", ""); String backbuff = sharedPrefs.getString("backbuf", ""); String vsync = sharedPrefs.getString("vsync", ""); String led = sharedPrefs.getString("led", ""); String cpu0gov = sharedPrefs.getString("cpu0gov", ""); String cpu1gov = sharedPrefs.getString("cpu1gov", ""); String cpu2gov = sharedPrefs.getString("cpu2gov", ""); String cpu3gov = sharedPrefs.getString("cpu3gov", ""); String io = sharedPrefs.getString("io", ""); String sdcache = sharedPrefs.getString("sdcache", ""); String delaynew = sharedPrefs.getString("delaynew", ""); String pausenew = sharedPrefs.getString("pausenew", ""); String thruploadnew = sharedPrefs.getString("thruploadnew", ""); String thrupmsnew = sharedPrefs.getString("thrupmsnew", ""); String thrdownloadnew = sharedPrefs.getString("thrdownloadnew", ""); String thrdownmsnew = sharedPrefs.getString("thrdownmsnew", ""); String ldt = sharedPrefs.getString("ldt", ""); String s2w = sharedPrefs.getString("s2w", ""); String s2wStart = sharedPrefs.getString("s2wStart", ""); String s2wEnd = sharedPrefs.getString("s2wEnd", ""); String p1freq = sharedPrefs.getString("p1freq", ""); String p2freq = sharedPrefs.getString("p2freq", ""); String p3freq = sharedPrefs.getString("p3freq", ""); String p1low = sharedPrefs.getString("p1low", ""); String p1high = sharedPrefs.getString("p1high", ""); String p2low = sharedPrefs.getString("p2low", ""); String p2high = sharedPrefs.getString("p2high", ""); String p3low = sharedPrefs.getString("p3low", ""); String p3high = sharedPrefs.getString("p3high", ""); boolean swap = sharedPrefs.getBoolean("swap", false); String swapLocation = sharedPrefs.getString("swap_location", ""); String swappiness = sharedPrefs.getString("swappiness", ""); String oom = sharedPrefs.getString("oom", ""); String otg = sharedPrefs.getString("otg", ""); String idle_freq = sharedPrefs.getString("idle_freq", ""); String scroff = sharedPrefs.getString("scroff", ""); String scroff_single = sharedPrefs.getString("scroff_single", ""); String[] thr = new String[6]; String[] tim = new String[6]; thr[0] = sharedPrefs.getString("thr0", ""); thr[1] = sharedPrefs.getString("thr2", ""); thr[2] = sharedPrefs.getString("thr3", ""); thr[3] = sharedPrefs.getString("thr4", ""); thr[4] = sharedPrefs.getString("thr5", ""); thr[5] = sharedPrefs.getString("thr7", ""); tim[0] = sharedPrefs.getString("tim0", ""); tim[1] = sharedPrefs.getString("tim2", ""); tim[2] = sharedPrefs.getString("tim3", ""); tim[3] = sharedPrefs.getString("tim4", ""); tim[4] = sharedPrefs.getString("tim5", ""); tim[5] = sharedPrefs.getString("tim7", ""); String maxCpus = sharedPrefs.getString("max_cpus", ""); String minCpus = sharedPrefs.getString("min_cpus", ""); StringBuilder gpubuilder = new StringBuilder(); gpubuilder.append("#!/system/bin/sh"); gpubuilder.append("\n"); if (!gpu3d.equals("")) { gpubuilder .append("echo ") .append("\"") .append(gpu3d) .append("\"") .append(" > /sys/devices/platform/kgsl-3d0.0/kgsl/kgsl-3d0/max_gpuclk") .append("\n"); } if (!gpu2d.equals("")) { gpubuilder .append("echo ") .append("\"") .append(gpu2d) .append("\"") .append(" > /sys/devices/platform/kgsl-2d0.0/kgsl/kgsl-2d0/max_gpuclk"); gpubuilder.append("\n"); gpubuilder .append("echo ").append( "\"").append( gpu2d).append( "\"").append( " > /sys/devices/platform/kgsl-2d1.1/kgsl/kgsl-2d1/max_gpuclk"); gpubuilder.append("\n"); } String gpu = gpubuilder.toString(); StringBuilder cpubuilder = new StringBuilder(); cpubuilder.append("#!/system/bin/sh"); cpubuilder.append("\n"); /** * cpu0 * */ if (!cpu0gov.equals("")) { cpubuilder .append("chmod 666 /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor \n").append( "echo ").append( "\"").append( cpu0gov).append( "\"").append( " > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor\n").append( "chmod 444 /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor \n"); } if (!cpu0max.equals("")) { cpubuilder .append("chmod 666 /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq \n").append( "echo ").append( "\"").append( cpu0max).append( "\"").append( " > /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq \n").append( "chmod 444 /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq\n"); } if (!cpu0min.equals("")) { cpubuilder .append("chmod 666 /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq \n").append( "echo ").append( "\"").append( cpu0min).append( "\"").append( " > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq \n\n").append( "chmod 444 /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq \n"); } /** * cpu1 * */ if (!cpu1gov.equals("")) { cpubuilder .append("chmod 666 /sys/devices/system/cpu/cpu1/cpufreq/scaling_governor \n").append( "echo ").append( "\"").append( cpu1gov).append( "\"").append( " > /sys/devices/system/cpu/cpu1/cpufreq/scaling_governor\n").append( "chmod 444 /sys/devices/system/cpu/cpu1/cpufreq/scaling_governor \n"); } if (!cpu1max.equals("")) { cpubuilder .append("chmod 666 /sys/devices/system/cpu/cpu1/cpufreq/scaling_max_freq \n").append( "echo ").append( "\"").append( cpu1max).append( "\"").append( " > /sys/devices/system/cpu/cpu1/cpufreq/scaling_max_freq \n").append( "chmod 444 /sys/devices/system/cpu/cpu1/cpufreq/scaling_max_freq \n"); } if (!cpu1min.equals("")) { cpubuilder .append("chmod 666 /sys/devices/system/cpu/cpu1/cpufreq/scaling_min_freq \n").append( "echo ").append( "\"").append( cpu1min).append( "\"").append( " > /sys/devices/system/cpu/cpu1/cpufreq/scaling_min_freq \n").append( "chmod 444 /sys/devices/system/cpu/cpu1/cpufreq/scaling_min_freq \n\n"); } /** * cpu2 * */ if (!cpu2gov.equals("")) { cpubuilder .append("chmod 666 /sys/devices/system/cpu/cpu2/cpufreq/scaling_governor \n").append( "echo ").append( "\"").append( cpu2gov).append( "\"").append( " > /sys/devices/system/cpu/cpu2/cpufreq/scaling_governor\n").append( "chmod 444 /sys/devices/system/cpu/cpu2/cpufreq/scaling_governor \n"); } if (!cpu2max.equals("")) { cpubuilder .append("chmod 666 /sys/devices/system/cpu/cpu2/cpufreq/scaling_max_freq \n").append( "echo ").append( "\"").append( cpu2max).append( "\"").append( " > /sys/devices/system/cpu/cpu2/cpufreq/scaling_max_freq \n").append( "chmod 444 /sys/devices/system/cpu/cpu2/cpufreq/scaling_max_freq \n"); } if (!cpu2min.equals("")) { cpubuilder .append("chmod 666 /sys/devices/system/cpu/cpu2/cpufreq/scaling_min_freq \n").append( "echo ").append( "\"").append( cpu2min).append( "\"").append( " > /sys/devices/system/cpu/cpu2/cpufreq/scaling_min_freq \n").append( "chmod 444 /sys/devices/system/cpu/cpu2/cpufreq/scaling_min_freq \n\n"); } /** * cpu3 * */ if (!cpu3gov.equals("")) { cpubuilder .append("chmod 666 /sys/devices/system/cpu/cpu3/cpufreq/scaling_governor \n").append( "echo ").append( "\"").append( cpu3gov).append( "\"").append( " > /sys/devices/system/cpu/cpu3/cpufreq/scaling_governor\n").append( "chmod 444 /sys/devices/system/cpu/cpu3/cpufreq/scaling_governor \n"); } if (!cpu3max.equals("")) { cpubuilder .append("chmod 666 /sys/devices/system/cpu/cpu3/cpufreq/scaling_max_freq \n").append( "echo ").append( "\"").append( cpu3max).append( "\"").append( " > /sys/devices/system/cpu/cpu3/cpufreq/scaling_max_freq \n").append( "chmod 444 /sys/devices/system/cpu/cpu3/cpufreq/scaling_max_freq \n"); } if (!cpu3min.equals("")) { cpubuilder .append("chmod 666 /sys/devices/system/cpu/cpu3/cpufreq/scaling_min_freq \n").append( "echo ").append( "\"").append( cpu3min).append( "\"").append( " > /sys/devices/system/cpu/cpu3/cpufreq/scaling_min_freq \n").append( "chmod 444 /sys/devices/system/cpu/cpu3/cpufreq/scaling_min_freq \n\n"); } List<String> govSettings = IOHelper.govSettings(); List<String> availableGovs = IOHelper.availableGovs(); for (String s : availableGovs) { for (String st : govSettings) { String temp = sharedPrefs.getString(s + "_" + st, ""); if (!temp.equals("")) { cpubuilder .append("chmod 777 /sys/devices/system/cpu/cpufreq/") .append(s).append( "/").append(st).append("\n"); cpubuilder.append("echo ").append("\"").append(temp).append("\"").append( " > /sys/devices/system/cpu/cpufreq/").append(s).append("/").append(st).append("\n"); } } } String cpu = cpubuilder.toString(); StringBuilder miscbuilder = new StringBuilder(); miscbuilder.append("#!/system/bin/sh \n\n#mount debug filesystem\nmount -t debugfs debugfs /sys/kernel/debug \n\n"); if (!vsync.equals("")) { miscbuilder.append("#vsync\nchmod 777 /sys/kernel/debug/msm_fb/0/vsync_enable \nchmod 777 /sys/kernel/debug/msm_fb/0/hw_vsync_mode \nchmod 777 /sys/kernel/debug/msm_fb/0/backbuff \necho " + "\"" + vsync + "\"" + " > /sys/kernel/debug/msm_fb/0/vsync_enable \n" + "echo " + "\"" + hw + "\"" + " > /sys/kernel/debug/msm_fb/0/hw_vsync_mode \n" + "echo " + "\"" + backbuff + "\"" + " > /sys/kernel/debug/msm_fb/0/backbuff \n\n"); } if (!led.equals("")) { miscbuilder .append("#capacitive buttons backlight\n" + "chmod 777 /sys/devices/platform/leds-pm8058/leds/button-backlight/currents \n" + "echo " + "\"" + led + "\"" + " > /sys/devices/platform/leds-pm8058/leds/button-backlight/currents \n\n"); } if (!fastcharge.equals("")) { miscbuilder.append("#fastcharge\n" + "chmod 777 /sys/kernel/fast_charge/force_fast_charge \n" + "echo " + "\"" + fastcharge + "\"" + " > /sys/kernel/fast_charge/force_fast_charge \n\n"); } if (!cdepth.equals("")) { miscbuilder.append("#color depth\n" + "chmod 777 /sys/kernel/debug/msm_fb/0/bpp \n" + "echo " + "\"" + cdepth + "\"" + " > /sys/kernel/debug/msm_fb/0/bpp \n\n"); } if (!mpdecisionscroff.equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_mpdecision/conf/scroff_single_core \n" + "echo " + "\"" + mpdecisionscroff + "\"" + " > /sys/kernel/msm_mpdecision/conf/scroff_single_core \n"); } if (!delaynew.equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_mpdecision/conf/delay \n" + "echo " + "\"" + delaynew.trim() + "\"" + " > /sys/kernel/msm_mpdecision/conf/delay \n"); } if (!pausenew.equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_mpdecision/conf/pause \n" + "echo " + "\"" + pausenew.trim() + "\"" + " > /sys/kernel/msm_mpdecision/conf/pause \n"); } if (!thruploadnew.equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_mpdecision/conf/nwns_threshold_up \n" + "echo " + "\"" + thruploadnew.trim() + "\"" + " > /sys/kernel/msm_mpdecision/conf/nwns_threshold_up \n"); } if (!thrdownloadnew.equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_mpdecision/conf/nwns_threshold_down \n" + "echo " + "\"" + thrdownloadnew.trim() + "\"" + " > /sys/kernel/msm_mpdecision/conf/nwns_threshold_down \n"); } if (!thrupmsnew.equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_mpdecision/conf/twts_threshold_up\n" + "echo " + "\"" + thrupmsnew.trim() + "\"" + " > /sys/kernel/msm_mpdecision/conf/twts_threshold_up \n"); } if (!thrdownmsnew.equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_mpdecision/conf/twts_threshold_down\n" + "echo " + "\"" + thrdownmsnew.trim() + "\"" + " > /sys/kernel/msm_mpdecision/conf/twts_threshold_down \n\n"); } if(!thr[0].equals("")){ for(int i = 0; i < 8; i++){ miscbuilder.append("chmod 777 /sys/kernel/msm_mpdecision/conf/nwns_threshold_"+i+"\n"); } miscbuilder.append("echo " + thr[1] + " > /sys/kernel/msm_mpdecision/conf/nwns_threshold_"+0+"\n"); miscbuilder.append("echo " + thr[2] + " > /sys/kernel/msm_mpdecision/conf/nwns_threshold_"+2+"\n"); miscbuilder.append("echo " + thr[3] + " > /sys/kernel/msm_mpdecision/conf/nwns_threshold_"+3+"\n"); miscbuilder.append("echo " + thr[4] + " > /sys/kernel/msm_mpdecision/conf/nwns_threshold_"+4+"\n"); miscbuilder.append("echo " + thr[5] + " > /sys/kernel/msm_mpdecision/conf/nwns_threshold_"+5+"\n"); miscbuilder.append("echo " + thr[6] + " > /sys/kernel/msm_mpdecision/conf/nwns_threshold_"+7+"\n"); } if(!tim[0].equals("")){ for(int i = 0; i < 8; i++){ miscbuilder.append("chmod 777 /sys/kernel/msm_mpdecision/conf/twts_threshold_"+i+"\n"); } miscbuilder.append("echo " + tim[1] + " > /sys/kernel/msm_mpdecision/conf/twts_threshold_"+0+"\n"); miscbuilder.append("echo " + tim[2] + " > /sys/kernel/msm_mpdecision/conf/twts_threshold_"+2+"\n"); miscbuilder.append("echo " + tim[3] + " > /sys/kernel/msm_mpdecision/conf/twts_threshold_"+3+"\n"); miscbuilder.append("echo " + tim[4] + " > /sys/kernel/msm_mpdecision/conf/twts_threshold_"+4+"\n"); miscbuilder.append("echo " + tim[5] + " > /sys/kernel/msm_mpdecision/conf/twts_threshold_"+5+"\n"); miscbuilder.append("echo " + tim[6] + " > /sys/kernel/msm_mpdecision/conf/twts_threshold_"+7+"\n"); } if(!maxCpus.equals("")){ miscbuilder.append("echo " + maxCpus + " > /sys/kernel/msm_mpdecision/conf/max_cpus\n"); } if(!minCpus.equals("")){ miscbuilder.append("echo " + minCpus + " > /sys/kernel/msm_mpdecision/conf/min_cpus\n"); } if (!sdcache.equals("")) { miscbuilder .append("#sd card cache size\n" + "chmod 777 /sys/block/mmcblk1/queue/read_ahead_kb \n" + "chmod 777 /sys/block/mmcblk0/queue/read_ahead_kb \n" + "chmod 777 /sys/devices/virtual/bdi/179:0/read_ahead_kb \n" + "echo " + "\"" + sdcache + "\"" + " > /sys/block/mmcblk1/queue/read_ahead_kb \n" + "echo " + "\"" + sdcache + "\"" + " > /sys/block/mmcblk0/queue/read_ahead_kb \n" + "echo " + "\"" + sdcache + "\"" + " > /sys/devices/virtual/bdi/179:0/read_ahead_kb \n\n"); } if (!io.equals("")) { miscbuilder.append("#IO scheduler\n" + "chmod 777 /sys/block/mmcblk0/queue/scheduler \n" + "chmod 777 /sys/block/mmcblk1/queue/scheduler \n" + "echo " + "\"" + io + "\"" + " > /sys/block/mmcblk0/queue/scheduler \n" + "echo " + "\"" + io + "\"" + " > /sys/block/mmcblk1/queue/scheduler \n\n"); } if (!ldt.equals("")) { miscbuilder .append("#Notification LED Timeout\n" + "chmod 777 /sys/kernel/notification_leds/off_timer_multiplier\n" + "echo " + "\"" + ldt + "\"" + " > /sys/kernel/notification_leds/off_timer_multiplier\n\n"); } if (!s2w.equals("")) { miscbuilder.append("#Sweep2Wake\n" + "chmod 777 /sys/android_touch/sweep2wake\n" + "echo " + "\"" + s2w + "\"" + " > /sys/android_touch/sweep2wake\n\n"); } if (!s2wStart.equals("")) { miscbuilder .append("chmod 777 /sys/android_touch/sweep2wake_startbutton\n" + "echo " + s2wStart + " > /sys/android_touch/sweep2wake_startbutton\n" + "chmod 777 /sys/android_touch/sweep2wake_endbutton\n" + "echo " + s2wEnd + " > /sys/android_touch/sweep2wake_endbutton\n\n"); } if (!p1freq.trim().equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_thermal/conf/allowed_low_freq\n" + "echo " + "\"" + p1freq.trim() + "\"" + " > /sys/kernel/msm_thermal/conf/allowed_low_freq\n"); } if (!p2freq.trim().equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_thermal/conf/allowed_mid_freq\n" + "echo " + "\"" + p2freq.trim() + "\"" + " > /sys/kernel/msm_thermal/conf/allowed_mid_freq\n"); } if (!p3freq.trim().equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_thermal/conf/allowed_max_freq\n" + "echo " + "\"" + p3freq.trim() + "\"" + " > /sys/kernel/msm_thermal/conf/allowed_max_freq\n"); } if (!p1low.trim().equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_thermal/conf/allowed_low_low\n" + "echo " + "\"" + p1low.trim() + "\"" + " > /sys/kernel/msm_thermal/conf/allowed_low_low\n"); } if (!p1high.trim().equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_thermal/conf/allowed_low_high\n" + "echo " + "\"" + p1high.trim() + "\"" + " > /sys/kernel/msm_thermal/conf/allowed_low_high\n"); } if (!p2low.trim().equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_thermal/conf/allowed_mid_low\n" + "echo " + "\"" + p2low.trim() + "\"" + " > /sys/kernel/msm_thermal/conf/allowed_mid_low\n"); } if (!p2high.trim().equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_thermal/conf/allowed_mid_high\n" + "echo " + "\"" + p2high.trim() + "\"" + " > /sys/kernel/msm_thermal/conf/allowed_mid_high\n"); } if (!p3low.trim().equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_thermal/conf/allowed_high_low\n" + "echo " + "\"" + p3low.trim() + "\"" + " > /sys/kernel/msm_thermal/conf/allowed_high_low\n"); } if (!p3high.trim().equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_thermal/conf/allowed_high_high\n" + "echo " + "\"" + p3high.trim() + "\"" + " > /sys/kernel/msm_thermal/conf/allowed_high_high\n"); } if (!idle_freq.equals("")) { miscbuilder.append("echo " + idle_freq + " > /sys/kernel/msm_mpdecision/conf/idle_freq\n"); } if (!scroff.equals("")) { miscbuilder.append("echo " + scroff + " > /sys/kernel/msm_mpdecision/conf/scroff_freq\n"); } if (!scroff_single.equals("")) { miscbuilder .append("echo " + scroff_single + " > /sys/kernel/msm_mpdecision/conf/scroff_single_core\n\n"); } if (swap == true) { miscbuilder.append("echo " + swappiness + " > /proc/sys/vm/swappiness\n" + "swapon " + swapLocation.trim() + "\n\n"); } else if (swap == false) { miscbuilder.append("swapoff " + swapLocation.trim() + "\n\n"); } if (!oom.equals("")) { miscbuilder.append("echo " + oom + " > /sys/module/lowmemorykiller/parameters/minfree\n"); } if (!otg.equals("")) { miscbuilder.append("echo " + otg + " > /sys/kernel/debug/msm_otg/mode\n"); miscbuilder.append("echo " + otg + " > /sys/kernel/debug/otg/mode\n"); } miscbuilder.append("#Umount debug filesystem\n" + "umount /sys/kernel/debug \n"); String misc = miscbuilder.toString(); StringBuilder voltagebuilder = new StringBuilder(); voltagebuilder.append("#!/system/bin/sh \n"); for (String s : voltages) { String temp = sharedPrefs.getString("voltage_" + s, ""); if (!temp.equals("")) { voltagebuilder .append("echo " + "\"" + temp + "\"" + " > /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n"); } } String voltage = voltagebuilder.toString(); try { FileOutputStream fOut = openFileOutput("99ktcputweaks", MODE_PRIVATE); OutputStreamWriter osw = new OutputStreamWriter(fOut); osw.write(cpu); osw.flush(); osw.close(); } catch (IOException ioe) { } try { FileOutputStream fOut = openFileOutput("99ktgputweaks", MODE_PRIVATE); OutputStreamWriter osw = new OutputStreamWriter(fOut); osw.write(gpu); osw.flush(); osw.close(); } catch (IOException ioe) { } try { FileOutputStream fOut = openFileOutput("99ktmisctweaks", MODE_PRIVATE); OutputStreamWriter osw = new OutputStreamWriter(fOut); osw.write(misc); osw.flush(); osw.close(); } catch (IOException ioe) { } try { FileOutputStream fOut = openFileOutput("99ktvoltage", MODE_PRIVATE); OutputStreamWriter osw = new OutputStreamWriter(fOut); osw.write(voltage); osw.flush(); osw.close(); } catch (IOException ioe) { } new Initd().execute(new String[] { "apply" }); }
private void initdExport() { SharedPreferences sharedPrefs = PreferenceManager .getDefaultSharedPreferences(c); String gpu3d = sharedPrefs.getString("gpu3d", ""); String gpu2d = sharedPrefs.getString("gpu2d", ""); String hw = sharedPrefs.getString("hw", ""); String cdepth = sharedPrefs.getString("cdepth", ""); String cpu1min = sharedPrefs.getString("cpu1min", ""); String cpu1max = sharedPrefs.getString("cpu1max", ""); String cpu0max = sharedPrefs.getString("cpu0max", ""); String cpu0min = sharedPrefs.getString("cpu0min", ""); String cpu3min = sharedPrefs.getString("cpu3min", ""); String cpu3max = sharedPrefs.getString("cpu3max", ""); String cpu2max = sharedPrefs.getString("cpu2max", ""); String cpu2min = sharedPrefs.getString("cpu2min", ""); String fastcharge = sharedPrefs.getString("fastcharge", ""); String mpdecisionscroff = sharedPrefs.getString("mpdecisionscroff", ""); String backbuff = sharedPrefs.getString("backbuf", ""); String vsync = sharedPrefs.getString("vsync", ""); String led = sharedPrefs.getString("led", ""); String cpu0gov = sharedPrefs.getString("cpu0gov", ""); String cpu1gov = sharedPrefs.getString("cpu1gov", ""); String cpu2gov = sharedPrefs.getString("cpu2gov", ""); String cpu3gov = sharedPrefs.getString("cpu3gov", ""); String io = sharedPrefs.getString("io", ""); String sdcache = sharedPrefs.getString("sdcache", ""); String delaynew = sharedPrefs.getString("delaynew", ""); String pausenew = sharedPrefs.getString("pausenew", ""); String thruploadnew = sharedPrefs.getString("thruploadnew", ""); String thrupmsnew = sharedPrefs.getString("thrupmsnew", ""); String thrdownloadnew = sharedPrefs.getString("thrdownloadnew", ""); String thrdownmsnew = sharedPrefs.getString("thrdownmsnew", ""); String ldt = sharedPrefs.getString("ldt", ""); String s2w = sharedPrefs.getString("s2w", ""); String s2wStart = sharedPrefs.getString("s2wStart", ""); String s2wEnd = sharedPrefs.getString("s2wEnd", ""); String p1freq = sharedPrefs.getString("p1freq", ""); String p2freq = sharedPrefs.getString("p2freq", ""); String p3freq = sharedPrefs.getString("p3freq", ""); String p1low = sharedPrefs.getString("p1low", ""); String p1high = sharedPrefs.getString("p1high", ""); String p2low = sharedPrefs.getString("p2low", ""); String p2high = sharedPrefs.getString("p2high", ""); String p3low = sharedPrefs.getString("p3low", ""); String p3high = sharedPrefs.getString("p3high", ""); boolean swap = sharedPrefs.getBoolean("swap", false); String swapLocation = sharedPrefs.getString("swap_location", ""); String swappiness = sharedPrefs.getString("swappiness", ""); String oom = sharedPrefs.getString("oom", ""); String otg = sharedPrefs.getString("otg", ""); String idle_freq = sharedPrefs.getString("idle_freq", ""); String scroff = sharedPrefs.getString("scroff", ""); String scroff_single = sharedPrefs.getString("scroff_single", ""); String[] thr = new String[6]; String[] tim = new String[6]; thr[0] = sharedPrefs.getString("thr0", ""); thr[1] = sharedPrefs.getString("thr2", ""); thr[2] = sharedPrefs.getString("thr3", ""); thr[3] = sharedPrefs.getString("thr4", ""); thr[4] = sharedPrefs.getString("thr5", ""); thr[5] = sharedPrefs.getString("thr7", ""); tim[0] = sharedPrefs.getString("tim0", ""); tim[1] = sharedPrefs.getString("tim2", ""); tim[2] = sharedPrefs.getString("tim3", ""); tim[3] = sharedPrefs.getString("tim4", ""); tim[4] = sharedPrefs.getString("tim5", ""); tim[5] = sharedPrefs.getString("tim7", ""); String maxCpus = sharedPrefs.getString("max_cpus", ""); String minCpus = sharedPrefs.getString("min_cpus", ""); StringBuilder gpubuilder = new StringBuilder(); gpubuilder.append("#!/system/bin/sh"); gpubuilder.append("\n"); if (!gpu3d.equals("")) { gpubuilder .append("echo ") .append("\"") .append(gpu3d) .append("\"") .append(" > /sys/devices/platform/kgsl-3d0.0/kgsl/kgsl-3d0/max_gpuclk") .append("\n"); } if (!gpu2d.equals("")) { gpubuilder .append("echo ") .append("\"") .append(gpu2d) .append("\"") .append(" > /sys/devices/platform/kgsl-2d0.0/kgsl/kgsl-2d0/max_gpuclk"); gpubuilder.append("\n"); gpubuilder .append("echo ").append( "\"").append( gpu2d).append( "\"").append( " > /sys/devices/platform/kgsl-2d1.1/kgsl/kgsl-2d1/max_gpuclk"); gpubuilder.append("\n"); } String gpu = gpubuilder.toString(); StringBuilder cpubuilder = new StringBuilder(); cpubuilder.append("#!/system/bin/sh"); cpubuilder.append("\n"); /** * cpu0 * */ if (!cpu0gov.equals("")) { cpubuilder .append("chmod 666 /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor \n").append( "echo ").append( "\"").append( cpu0gov).append( "\"").append( " > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor\n").append( "chmod 444 /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor \n"); } if (!cpu0max.equals("")) { cpubuilder .append("chmod 666 /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq \n").append( "echo ").append( "\"").append( cpu0max).append( "\"").append( " > /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq \n").append( "chmod 444 /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq\n"); } if (!cpu0min.equals("")) { cpubuilder .append("chmod 666 /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq \n").append( "echo ").append( "\"").append( cpu0min).append( "\"").append( " > /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq \n\n").append( "chmod 444 /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq \n"); } /** * cpu1 * */ if (!cpu1gov.equals("")) { cpubuilder .append("chmod 666 /sys/devices/system/cpu/cpu1/cpufreq/scaling_governor \n").append( "echo ").append( "\"").append( cpu1gov).append( "\"").append( " > /sys/devices/system/cpu/cpu1/cpufreq/scaling_governor\n").append( "chmod 444 /sys/devices/system/cpu/cpu1/cpufreq/scaling_governor \n"); } if (!cpu1max.equals("")) { cpubuilder .append("chmod 666 /sys/devices/system/cpu/cpu1/cpufreq/scaling_max_freq \n").append( "echo ").append( "\"").append( cpu1max).append( "\"").append( " > /sys/devices/system/cpu/cpu1/cpufreq/scaling_max_freq \n").append( "chmod 444 /sys/devices/system/cpu/cpu1/cpufreq/scaling_max_freq \n"); } if (!cpu1min.equals("")) { cpubuilder .append("chmod 666 /sys/devices/system/cpu/cpu1/cpufreq/scaling_min_freq \n").append( "echo ").append( "\"").append( cpu1min).append( "\"").append( " > /sys/devices/system/cpu/cpu1/cpufreq/scaling_min_freq \n").append( "chmod 444 /sys/devices/system/cpu/cpu1/cpufreq/scaling_min_freq \n\n"); } /** * cpu2 * */ if (!cpu2gov.equals("")) { cpubuilder .append("chmod 666 /sys/devices/system/cpu/cpu2/cpufreq/scaling_governor \n").append( "echo ").append( "\"").append( cpu2gov).append( "\"").append( " > /sys/devices/system/cpu/cpu2/cpufreq/scaling_governor\n").append( "chmod 444 /sys/devices/system/cpu/cpu2/cpufreq/scaling_governor \n"); } if (!cpu2max.equals("")) { cpubuilder .append("chmod 666 /sys/devices/system/cpu/cpu2/cpufreq/scaling_max_freq \n").append( "echo ").append( "\"").append( cpu2max).append( "\"").append( " > /sys/devices/system/cpu/cpu2/cpufreq/scaling_max_freq \n").append( "chmod 444 /sys/devices/system/cpu/cpu2/cpufreq/scaling_max_freq \n"); } if (!cpu2min.equals("")) { cpubuilder .append("chmod 666 /sys/devices/system/cpu/cpu2/cpufreq/scaling_min_freq \n").append( "echo ").append( "\"").append( cpu2min).append( "\"").append( " > /sys/devices/system/cpu/cpu2/cpufreq/scaling_min_freq \n").append( "chmod 444 /sys/devices/system/cpu/cpu2/cpufreq/scaling_min_freq \n\n"); } /** * cpu3 * */ if (!cpu3gov.equals("")) { cpubuilder .append("chmod 666 /sys/devices/system/cpu/cpu3/cpufreq/scaling_governor \n").append( "echo ").append( "\"").append( cpu3gov).append( "\"").append( " > /sys/devices/system/cpu/cpu3/cpufreq/scaling_governor\n").append( "chmod 444 /sys/devices/system/cpu/cpu3/cpufreq/scaling_governor \n"); } if (!cpu3max.equals("")) { cpubuilder .append("chmod 666 /sys/devices/system/cpu/cpu3/cpufreq/scaling_max_freq \n").append( "echo ").append( "\"").append( cpu3max).append( "\"").append( " > /sys/devices/system/cpu/cpu3/cpufreq/scaling_max_freq \n").append( "chmod 444 /sys/devices/system/cpu/cpu3/cpufreq/scaling_max_freq \n"); } if (!cpu3min.equals("")) { cpubuilder .append("chmod 666 /sys/devices/system/cpu/cpu3/cpufreq/scaling_min_freq \n").append( "echo ").append( "\"").append( cpu3min).append( "\"").append( " > /sys/devices/system/cpu/cpu3/cpufreq/scaling_min_freq \n").append( "chmod 444 /sys/devices/system/cpu/cpu3/cpufreq/scaling_min_freq \n\n"); } List<String> govSettings = IOHelper.govSettings(); List<String> availableGovs = IOHelper.availableGovs(); for (String s : availableGovs) { for (String st : govSettings) { String temp = sharedPrefs.getString(s + "_" + st, ""); if (!temp.equals("")) { cpubuilder .append("chmod 777 /sys/devices/system/cpu/cpufreq/") .append(s).append( "/").append(st).append("\n"); cpubuilder.append("echo ").append("\"").append(temp).append("\"").append( " > /sys/devices/system/cpu/cpufreq/").append(s).append("/").append(st).append("\n"); } } } String cpu = cpubuilder.toString(); StringBuilder miscbuilder = new StringBuilder(); miscbuilder.append("#!/system/bin/sh \n\n#mount debug filesystem\nmount -t debugfs debugfs /sys/kernel/debug \n\n"); if (!vsync.equals("")) { miscbuilder.append("#vsync\nchmod 777 /sys/kernel/debug/msm_fb/0/vsync_enable \nchmod 777 /sys/kernel/debug/msm_fb/0/hw_vsync_mode \nchmod 777 /sys/kernel/debug/msm_fb/0/backbuff \necho " + "\"" + vsync + "\"" + " > /sys/kernel/debug/msm_fb/0/vsync_enable \n" + "echo " + "\"" + hw + "\"" + " > /sys/kernel/debug/msm_fb/0/hw_vsync_mode \n" + "echo " + "\"" + backbuff + "\"" + " > /sys/kernel/debug/msm_fb/0/backbuff \n\n"); } if (!led.equals("")) { miscbuilder .append("#capacitive buttons backlight\n" + "chmod 777 /sys/devices/platform/leds-pm8058/leds/button-backlight/currents \n" + "echo " + "\"" + led + "\"" + " > /sys/devices/platform/leds-pm8058/leds/button-backlight/currents \n\n"); } if (!fastcharge.equals("")) { miscbuilder.append("#fastcharge\n" + "chmod 777 /sys/kernel/fast_charge/force_fast_charge \n" + "echo " + "\"" + fastcharge + "\"" + " > /sys/kernel/fast_charge/force_fast_charge \n\n"); } if (!cdepth.equals("")) { miscbuilder.append("#color depth\n" + "chmod 777 /sys/kernel/debug/msm_fb/0/bpp \n" + "echo " + "\"" + cdepth + "\"" + " > /sys/kernel/debug/msm_fb/0/bpp \n\n"); } if (!mpdecisionscroff.equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_mpdecision/conf/scroff_single_core \n" + "echo " + "\"" + mpdecisionscroff + "\"" + " > /sys/kernel/msm_mpdecision/conf/scroff_single_core \n"); } if (!delaynew.equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_mpdecision/conf/delay \n" + "echo " + "\"" + delaynew.trim() + "\"" + " > /sys/kernel/msm_mpdecision/conf/delay \n"); } if (!pausenew.equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_mpdecision/conf/pause \n" + "echo " + "\"" + pausenew.trim() + "\"" + " > /sys/kernel/msm_mpdecision/conf/pause \n"); } if (!thruploadnew.equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_mpdecision/conf/nwns_threshold_up \n" + "echo " + "\"" + thruploadnew.trim() + "\"" + " > /sys/kernel/msm_mpdecision/conf/nwns_threshold_up \n"); } if (!thrdownloadnew.equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_mpdecision/conf/nwns_threshold_down \n" + "echo " + "\"" + thrdownloadnew.trim() + "\"" + " > /sys/kernel/msm_mpdecision/conf/nwns_threshold_down \n"); } if (!thrupmsnew.equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_mpdecision/conf/twts_threshold_up\n" + "echo " + "\"" + thrupmsnew.trim() + "\"" + " > /sys/kernel/msm_mpdecision/conf/twts_threshold_up \n"); } if (!thrdownmsnew.equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_mpdecision/conf/twts_threshold_down\n" + "echo " + "\"" + thrdownmsnew.trim() + "\"" + " > /sys/kernel/msm_mpdecision/conf/twts_threshold_down \n\n"); } if(!thr[0].equals("")){ for(int i = 0; i < 8; i++){ miscbuilder.append("chmod 777 /sys/kernel/msm_mpdecision/conf/nwns_threshold_"+i+"\n"); } miscbuilder.append("echo " + thr[1] + " > /sys/kernel/msm_mpdecision/conf/nwns_threshold_"+0+"\n"); miscbuilder.append("echo " + thr[2] + " > /sys/kernel/msm_mpdecision/conf/nwns_threshold_"+2+"\n"); miscbuilder.append("echo " + thr[3] + " > /sys/kernel/msm_mpdecision/conf/nwns_threshold_"+3+"\n"); miscbuilder.append("echo " + thr[4] + " > /sys/kernel/msm_mpdecision/conf/nwns_threshold_"+4+"\n"); miscbuilder.append("echo " + thr[5] + " > /sys/kernel/msm_mpdecision/conf/nwns_threshold_"+5+"\n"); miscbuilder.append("echo " + thr[6] + " > /sys/kernel/msm_mpdecision/conf/nwns_threshold_"+7+"\n"); } if(!tim[0].equals("")){ for(int i = 0; i < 8; i++){ miscbuilder.append("chmod 777 /sys/kernel/msm_mpdecision/conf/twts_threshold_"+i+"\n"); } miscbuilder.append("echo " + tim[0] + " > /sys/kernel/msm_mpdecision/conf/twts_threshold_"+0+"\n"); miscbuilder.append("echo " + tim[1] + " > /sys/kernel/msm_mpdecision/conf/twts_threshold_"+2+"\n"); miscbuilder.append("echo " + tim[3] + " > /sys/kernel/msm_mpdecision/conf/twts_threshold_"+3+"\n"); miscbuilder.append("echo " + tim[3] + " > /sys/kernel/msm_mpdecision/conf/twts_threshold_"+4+"\n"); miscbuilder.append("echo " + tim[4] + " > /sys/kernel/msm_mpdecision/conf/twts_threshold_"+5+"\n"); miscbuilder.append("echo " + tim[5] + " > /sys/kernel/msm_mpdecision/conf/twts_threshold_"+7+"\n"); } if(!maxCpus.equals("")){ miscbuilder.append("echo " + maxCpus + " > /sys/kernel/msm_mpdecision/conf/max_cpus\n"); } if(!minCpus.equals("")){ miscbuilder.append("echo " + minCpus + " > /sys/kernel/msm_mpdecision/conf/min_cpus\n"); } if (!sdcache.equals("")) { miscbuilder .append("#sd card cache size\n" + "chmod 777 /sys/block/mmcblk1/queue/read_ahead_kb \n" + "chmod 777 /sys/block/mmcblk0/queue/read_ahead_kb \n" + "chmod 777 /sys/devices/virtual/bdi/179:0/read_ahead_kb \n" + "echo " + "\"" + sdcache + "\"" + " > /sys/block/mmcblk1/queue/read_ahead_kb \n" + "echo " + "\"" + sdcache + "\"" + " > /sys/block/mmcblk0/queue/read_ahead_kb \n" + "echo " + "\"" + sdcache + "\"" + " > /sys/devices/virtual/bdi/179:0/read_ahead_kb \n\n"); } if (!io.equals("")) { miscbuilder.append("#IO scheduler\n" + "chmod 777 /sys/block/mmcblk0/queue/scheduler \n" + "chmod 777 /sys/block/mmcblk1/queue/scheduler \n" + "echo " + "\"" + io + "\"" + " > /sys/block/mmcblk0/queue/scheduler \n" + "echo " + "\"" + io + "\"" + " > /sys/block/mmcblk1/queue/scheduler \n\n"); } if (!ldt.equals("")) { miscbuilder .append("#Notification LED Timeout\n" + "chmod 777 /sys/kernel/notification_leds/off_timer_multiplier\n" + "echo " + "\"" + ldt + "\"" + " > /sys/kernel/notification_leds/off_timer_multiplier\n\n"); } if (!s2w.equals("")) { miscbuilder.append("#Sweep2Wake\n" + "chmod 777 /sys/android_touch/sweep2wake\n" + "echo " + "\"" + s2w + "\"" + " > /sys/android_touch/sweep2wake\n\n"); } if (!s2wStart.equals("")) { miscbuilder .append("chmod 777 /sys/android_touch/sweep2wake_startbutton\n" + "echo " + s2wStart + " > /sys/android_touch/sweep2wake_startbutton\n" + "chmod 777 /sys/android_touch/sweep2wake_endbutton\n" + "echo " + s2wEnd + " > /sys/android_touch/sweep2wake_endbutton\n\n"); } if (!p1freq.trim().equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_thermal/conf/allowed_low_freq\n" + "echo " + "\"" + p1freq.trim() + "\"" + " > /sys/kernel/msm_thermal/conf/allowed_low_freq\n"); } if (!p2freq.trim().equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_thermal/conf/allowed_mid_freq\n" + "echo " + "\"" + p2freq.trim() + "\"" + " > /sys/kernel/msm_thermal/conf/allowed_mid_freq\n"); } if (!p3freq.trim().equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_thermal/conf/allowed_max_freq\n" + "echo " + "\"" + p3freq.trim() + "\"" + " > /sys/kernel/msm_thermal/conf/allowed_max_freq\n"); } if (!p1low.trim().equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_thermal/conf/allowed_low_low\n" + "echo " + "\"" + p1low.trim() + "\"" + " > /sys/kernel/msm_thermal/conf/allowed_low_low\n"); } if (!p1high.trim().equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_thermal/conf/allowed_low_high\n" + "echo " + "\"" + p1high.trim() + "\"" + " > /sys/kernel/msm_thermal/conf/allowed_low_high\n"); } if (!p2low.trim().equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_thermal/conf/allowed_mid_low\n" + "echo " + "\"" + p2low.trim() + "\"" + " > /sys/kernel/msm_thermal/conf/allowed_mid_low\n"); } if (!p2high.trim().equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_thermal/conf/allowed_mid_high\n" + "echo " + "\"" + p2high.trim() + "\"" + " > /sys/kernel/msm_thermal/conf/allowed_mid_high\n"); } if (!p3low.trim().equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_thermal/conf/allowed_high_low\n" + "echo " + "\"" + p3low.trim() + "\"" + " > /sys/kernel/msm_thermal/conf/allowed_high_low\n"); } if (!p3high.trim().equals("")) { miscbuilder .append("chmod 777 /sys/kernel/msm_thermal/conf/allowed_high_high\n" + "echo " + "\"" + p3high.trim() + "\"" + " > /sys/kernel/msm_thermal/conf/allowed_high_high\n"); } if (!idle_freq.equals("")) { miscbuilder.append("echo " + idle_freq + " > /sys/kernel/msm_mpdecision/conf/idle_freq\n"); } if (!scroff.equals("")) { miscbuilder.append("echo " + scroff + " > /sys/kernel/msm_mpdecision/conf/scroff_freq\n"); } if (!scroff_single.equals("")) { miscbuilder .append("echo " + scroff_single + " > /sys/kernel/msm_mpdecision/conf/scroff_single_core\n\n"); } if (swap == true) { miscbuilder.append("echo " + swappiness + " > /proc/sys/vm/swappiness\n" + "swapon " + swapLocation.trim() + "\n\n"); } else if (swap == false) { miscbuilder.append("swapoff " + swapLocation.trim() + "\n\n"); } if (!oom.equals("")) { miscbuilder.append("echo " + oom + " > /sys/module/lowmemorykiller/parameters/minfree\n"); } if (!otg.equals("")) { miscbuilder.append("echo " + otg + " > /sys/kernel/debug/msm_otg/mode\n"); miscbuilder.append("echo " + otg + " > /sys/kernel/debug/otg/mode\n"); } miscbuilder.append("#Umount debug filesystem\n" + "umount /sys/kernel/debug \n"); String misc = miscbuilder.toString(); StringBuilder voltagebuilder = new StringBuilder(); voltagebuilder.append("#!/system/bin/sh \n"); for (String s : voltages) { String temp = sharedPrefs.getString("voltage_" + s, ""); if (!temp.equals("")) { voltagebuilder .append("echo " + "\"" + temp + "\"" + " > /sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels\n"); } } String voltage = voltagebuilder.toString(); try { FileOutputStream fOut = openFileOutput("99ktcputweaks", MODE_PRIVATE); OutputStreamWriter osw = new OutputStreamWriter(fOut); osw.write(cpu); osw.flush(); osw.close(); } catch (IOException ioe) { } try { FileOutputStream fOut = openFileOutput("99ktgputweaks", MODE_PRIVATE); OutputStreamWriter osw = new OutputStreamWriter(fOut); osw.write(gpu); osw.flush(); osw.close(); } catch (IOException ioe) { } try { FileOutputStream fOut = openFileOutput("99ktmisctweaks", MODE_PRIVATE); OutputStreamWriter osw = new OutputStreamWriter(fOut); osw.write(misc); osw.flush(); osw.close(); } catch (IOException ioe) { } try { FileOutputStream fOut = openFileOutput("99ktvoltage", MODE_PRIVATE); OutputStreamWriter osw = new OutputStreamWriter(fOut); osw.write(voltage); osw.flush(); osw.close(); } catch (IOException ioe) { } new Initd().execute(new String[] { "apply" }); }
diff --git a/hadoop-console/src/main/java/com/gaoshin/hadoop/hdfs/HadoopBaseService.java b/hadoop-console/src/main/java/com/gaoshin/hadoop/hdfs/HadoopBaseService.java index 2bc90c3..728b43a 100644 --- a/hadoop-console/src/main/java/com/gaoshin/hadoop/hdfs/HadoopBaseService.java +++ b/hadoop-console/src/main/java/com/gaoshin/hadoop/hdfs/HadoopBaseService.java @@ -1,44 +1,44 @@ package com.gaoshin.hadoop.hdfs; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hdfs.DFSClient; import org.springframework.beans.factory.annotation.Autowired; import com.gaoshin.configuration.ConfService; import com.gaoshin.job.bean.JobConf; public class HadoopBaseService { @Autowired private ConfService confService; private String hdfsUrl; public String getHdfsUrl() { if(hdfsUrl == null) { - JobConf conf = confService.get("hadoop.dfs.uri"); + JobConf conf = confService.getByKey("hadoop.dfs.uri"); if(conf != null) { hdfsUrl = conf.getValue(); } } return hdfsUrl; } public Configuration getConf() { Configuration conf = new Configuration(); conf.set("fs.default.name", getHdfsUrl()); conf.set("hadoop.job.ugi", "hadoop"); return conf; } public DFSClient getDfsClient() throws IOException { Configuration conf = getConf(); DFSClient dfsClient = new DFSClient(conf); return dfsClient; } public void setHdfsUrl(String hdfsUrl) { this.hdfsUrl = hdfsUrl; } }
true
true
public String getHdfsUrl() { if(hdfsUrl == null) { JobConf conf = confService.get("hadoop.dfs.uri"); if(conf != null) { hdfsUrl = conf.getValue(); } } return hdfsUrl; }
public String getHdfsUrl() { if(hdfsUrl == null) { JobConf conf = confService.getByKey("hadoop.dfs.uri"); if(conf != null) { hdfsUrl = conf.getValue(); } } return hdfsUrl; }
diff --git a/src/net/sf/antcontrib/cpptasks/CCTask.java b/src/net/sf/antcontrib/cpptasks/CCTask.java index bd31ccce..b385393d 100644 --- a/src/net/sf/antcontrib/cpptasks/CCTask.java +++ b/src/net/sf/antcontrib/cpptasks/CCTask.java @@ -1,1683 +1,1684 @@ /* * * Copyright 2001-2005 The Ant-Contrib project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.antcontrib.cpptasks; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashSet; import java.util.Hashtable; import java.util.List; import java.util.Set; import java.util.Vector; import net.sf.antcontrib.cpptasks.compiler.CompilerConfiguration; import net.sf.antcontrib.cpptasks.compiler.LinkType; import net.sf.antcontrib.cpptasks.compiler.Linker; import net.sf.antcontrib.cpptasks.compiler.LinkerConfiguration; import net.sf.antcontrib.cpptasks.compiler.Processor; import net.sf.antcontrib.cpptasks.compiler.ProcessorConfiguration; import net.sf.antcontrib.cpptasks.ide.ProjectDef; import net.sf.antcontrib.cpptasks.types.CompilerArgument; import net.sf.antcontrib.cpptasks.types.ConditionalFileSet; import net.sf.antcontrib.cpptasks.types.DefineSet; import net.sf.antcontrib.cpptasks.types.IncludePath; import net.sf.antcontrib.cpptasks.types.LibrarySet; import net.sf.antcontrib.cpptasks.types.LinkerArgument; import net.sf.antcontrib.cpptasks.types.SystemIncludePath; import net.sf.antcontrib.cpptasks.types.SystemLibrarySet; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.Task; import org.apache.tools.ant.types.Environment; /** * Compile and link task. * * <p> * This task can compile various source languages and produce executables, * shared libraries (aka DLL's) and static libraries. Compiler adaptors are * currently available for several C/C++ compilers, FORTRAN, MIDL and Windows * Resource files. * </p> * * * <p> * Copyright (c) 2001-2006, The Ant-Contrib project. * </p> * * <p> * Licensed under the Apache Software License 2.0, * http://www.apache.org/licenses/LICENSE-2.0. * </p> * * <p> * For use with Apache Ant 1.5 or later. This software is not a product of the * of the Apache Software Foundation and no endorsement is implied. * </p> * * <p> * THIS SOFTWARE IS PROVIDED 'AS-IS', See * http://www.apache.org/licenses/LICENSE-2.0 for additional disclaimers. * </p> * * To use: * <ol> * <li>Place cpptasks.jar into Ant's classpath by placing in Ant's lib * directory, adding to CLASSPATH environment variable or using the -lib command * line option.</li> * <li>Add type and task definitions in build file: * <ul> * <li>Ant 1.6 or later: add * xmlns:cpptasks="antlib:org.sf.net.antcontrib.cpptasks" to &lt;project&gt; * element.</li> * <li>Ant 1.5 or later: Add &lt;taskdef resource="cpptasks.tasks"/&gt; and * &lt;typedef resource="cpptasks.types"/&gt; to body of &lt;project&gt; * element.</li> * </ul> * </li> * <li>Add &lt;cc/&gt;, &lt;compiler/&gt; and &lt;linker/&gt elements to * project.</li> * <li>Set path and environment variables to be able to run compiler from * command line.</li> * <li>Build project.</li> * </ol> * * @author Adam Murdoch * @author Curt Arnold */ public class CCTask extends Task { private static class SystemLibraryCollector implements FileVisitor { private Hashtable libraries; private Linker linker; public SystemLibraryCollector(Linker linker, Hashtable libraries) { this.linker = linker; this.libraries = libraries; } public void visit(File basedir, String filename) { if (linker.bid(filename) > 0) { File libfile = new File(basedir, filename); String key = linker.getLibraryKey(libfile); libraries.put(key, libfile); } } } private static class ProjectFileCollector implements FileVisitor { private final List files; /** * Creates a new ProjectFileCollector. * * @param files * vector for collected files. */ public ProjectFileCollector(List files) { this.files = files; } /** * Called for each file to be considered for collection. * * @param parentDir * parent directory * @param filename * filename within directory */ public void visit(File parentDir, String filename) { files.add(new File(parentDir, filename)); } } private static final ProcessorConfiguration[] EMPTY_CONFIG_ARRAY = new ProcessorConfiguration[0]; /** * Builds a Hashtable to targets needing to be rebuilt keyed by compiler * configuration */ public static Hashtable getTargetsToBuildByConfiguration(Hashtable targets) { Hashtable targetsByConfig = new Hashtable(); Enumeration targetEnum = targets.elements(); while (targetEnum.hasMoreElements()) { TargetInfo target = (TargetInfo) targetEnum.nextElement(); if (target.getRebuild()) { Vector targetsForSameConfig = (Vector) targetsByConfig .get(target.getConfiguration()); if (targetsForSameConfig != null) { targetsForSameConfig.addElement(target); } else { targetsForSameConfig = new Vector(); targetsForSameConfig.addElement(target); targetsByConfig.put(target.getConfiguration(), targetsForSameConfig); } } } return targetsByConfig; } // FREEHEP private int maxCores = 0; /** The compiler definitions. */ private Vector _compilers = new Vector(); /** The output file type. */ // private LinkType _linkType = LinkType.EXECUTABLE; /** The library sets. */ private Vector _libsets = new Vector(); /** The linker definitions. */ private Vector _linkers = new Vector(); /** The object directory. */ private File _objDir; /** The output file. */ private File _outfile; /** The linker definitions. */ private final Vector targetPlatforms = new Vector(); /** The distributer definitions. */ private Vector distributers = new Vector(); private final Vector versionInfos = new Vector(); private final Vector projects = new Vector(); private boolean projectsOnly = false; /** * If true, stop build on compile failure. */ protected boolean failOnError = true; /** * Content that appears in <cc>and also in <compiler>are maintained by a * captive CompilerDef instance */ private final CompilerDef compilerDef = new CompilerDef(); /** The OS390 dataset to build to object to */ private String dataset; /** * * Depth of dependency checking * * Values < 0 indicate full dependency checking Values >= 0 indicate partial * dependency checking and for superficial compilation checks. Will throw * BuildException before attempting link */ private int dependencyDepth = -1; /** * Content that appears in <cc>and also in <linker>are maintained by a * captive CompilerDef instance */ private final LinkerDef linkerDef = new LinkerDef(); /** * contains the subsystem, output type and * */ private final LinkType linkType = new LinkType(); /** * The property name which will be set with the physical filename of the * file that is generated by the linker */ private String outputFileProperty; /** * if relentless = true, compilations should attempt to compile as many * files as possible before throwing a BuildException */ private boolean relentless; public CCTask() { } /** * Adds a compiler definition or reference. * * @param compiler * compiler * @throws NullPointerException * if compiler is null */ public void addConfiguredCompiler(CompilerDef compiler) { if (compiler == null) { throw new NullPointerException("compiler"); } compiler.setProject(getProject()); _compilers.addElement(compiler); } /** * Adds a compiler command-line arg. Argument will be inherited by all * nested compiler elements that do not have inherit="false". * */ public void addConfiguredCompilerArg(CompilerArgument arg) { compilerDef.addConfiguredCompilerArg(arg); } /** * Adds a defineset. Will be inherited by all compiler elements that do not * have inherit="false". * * @param defs * Define set */ public void addConfiguredDefineset(DefineSet defs) { compilerDef.addConfiguredDefineset(defs); } /** * Adds a linker definition. The first linker that is not disqualified by * its "if" and "unless" attributes will perform the link. If no child * linker element is active, the linker implied by the cc elements name or * classname attribute will be used. * * @param linker * linker * @throws NullPointerException * if linker is null */ public void addConfiguredLinker(LinkerDef linker) { if (linker == null) { throw new NullPointerException("linker"); } linker.setProject(getProject()); _linkers.addElement(linker); } /** * Adds a linker command-line arg. Argument will be inherited by all nested * linker elements that do not have inherit="false". */ public void addConfiguredLinkerArg(LinkerArgument arg) { linkerDef.addConfiguredLinkerArg(arg); } /** * Add an environment variable to the launched process. */ public void addEnv(Environment.Variable var) { compilerDef.addEnv(var); linkerDef.addEnv(var); } /** * Adds a source file set. * * Files in these filesets will be auctioned to the available compiler * configurations, with the default compiler implied by the cc element * bidding last. If no compiler is interested in the file, it will be passed * to the linker. * * To have a file be processed by a particular compiler configuration, add a * fileset to the corresponding compiler element. */ public void addFileset(ConditionalFileSet srcSet) { compilerDef.addFileset(srcSet); } /** * Adds a library set. * * Library sets will be inherited by all linker elements that do not have * inherit="false". * * @param libset * library set * @throws NullPointerException * if libset is null. */ public void addLibset(LibrarySet libset) { if (libset == null) { throw new NullPointerException("libset"); } linkerDef.addLibset(libset); } /** * Adds a system library set. Timestamps and locations of system library * sets are not used in dependency analysis. * * Essential libraries (such as C Runtime libraries) should not be specified * since the task will attempt to identify the correct libraries based on * the multithread, debug and runtime attributes. * * System library sets will be inherited by all linker elements that do not * have inherit="false". * * @param libset * library set * @throws NullPointerException * if libset is null. */ public void addSyslibset(SystemLibrarySet libset) { if (libset == null) { throw new NullPointerException("libset"); } linkerDef.addSyslibset(libset); } /** * Specifies the generation of IDE project file. Experimental. * * @param projectDef * project file generation specification */ public void addProject(final ProjectDef projectDef) { if (projectDef == null) { throw new NullPointerException("projectDef"); } projects.addElement(projectDef); } public void setProjectsOnly(final boolean value) { projectsOnly = value; } /** * Checks all targets that are not forced to be rebuilt or are missing * object files to be checked for modified include files * * @returns total number of targets to be rebuilt * */ protected int checkForChangedIncludeFiles(Hashtable targets) { int potentialTargets = 0; int definiteTargets = 0; Enumeration targetEnum = targets.elements(); while (targetEnum.hasMoreElements()) { TargetInfo target = (TargetInfo) targetEnum.nextElement(); if (!target.getRebuild()) { potentialTargets++; } else { definiteTargets++; } } // // If there were remaining targets that // might be out of date // if (potentialTargets > 0) { log("Starting dependency analysis for " + Integer.toString(potentialTargets) + " files."); DependencyTable dependencyTable = new DependencyTable(_objDir); try { dependencyTable.load(); } catch (Exception ex) { log("Problem reading dependencies.xml: " + ex.toString()); } targetEnum = targets.elements(); while (targetEnum.hasMoreElements()) { TargetInfo target = (TargetInfo) targetEnum.nextElement(); if (!target.getRebuild()) { if (dependencyTable.needsRebuild(this, target, dependencyDepth)) { target.mustRebuild(); } } } dependencyTable.commit(this); } // // count files being rebuilt now // int currentTargets = 0; targetEnum = targets.elements(); while (targetEnum.hasMoreElements()) { TargetInfo target = (TargetInfo) targetEnum.nextElement(); if (target.getRebuild()) { currentTargets++; } } if (potentialTargets > 0) { log(Integer.toString(potentialTargets - currentTargets + definiteTargets) + " files are up to date."); log(Integer.toString(currentTargets - definiteTargets) + " files to be recompiled from dependency analysis."); } log(Integer.toString(currentTargets) + " total files to be compiled."); return currentTargets; } protected LinkerConfiguration collectExplicitObjectFiles( Vector objectFiles, Vector sysObjectFiles, VersionInfo versionInfo) { // // find the first eligible linker // // ProcessorConfiguration linkerConfig = null; LinkerDef selectedLinkerDef = null; Linker selectedLinker = null; Hashtable sysLibraries = new Hashtable(); TargetDef targetPlatform = getTargetPlatform(); FileVisitor objCollector = null; FileVisitor sysLibraryCollector = null; for (int i = 0; i < _linkers.size(); i++) { LinkerDef currentLinkerDef = (LinkerDef) _linkers.elementAt(i); if (currentLinkerDef.isActive()) { selectedLinkerDef = currentLinkerDef; selectedLinker = currentLinkerDef.getProcessor().getLinker( linkType); // // skip the linker if it doesn't know how to // produce the specified link type if (selectedLinker != null) { linkerConfig = currentLinkerDef.createConfiguration(this, linkType, linkerDef, targetPlatform, versionInfo); if (linkerConfig != null) { // // create collectors for object files // and system libraries objCollector = new ObjectFileCollector(selectedLinker, objectFiles); sysLibraryCollector = new SystemLibraryCollector( selectedLinker, sysLibraries); // // if the <linker> has embedded <fileset>'s // (such as linker specific libraries) // add them as object files. // if (currentLinkerDef.hasFileSets()) { currentLinkerDef.visitFiles(objCollector); } // // user libraries are just a specialized form // of an object fileset selectedLinkerDef.visitUserLibraries(selectedLinker, objCollector); } break; } } } if (linkerConfig == null) { linkerConfig = linkerDef.createConfiguration(this, linkType, null, targetPlatform, versionInfo); selectedLinker = (Linker) linkerDef.getProcessor().getLinker( linkType); objCollector = new ObjectFileCollector(selectedLinker, objectFiles); sysLibraryCollector = new SystemLibraryCollector(selectedLinker, sysLibraries); } // // unless there was a <linker> element that // explicitly did not inherit files from // containing <cc> element if (selectedLinkerDef == null || selectedLinkerDef.getInherit()) { linkerDef.visitUserLibraries(selectedLinker, objCollector); linkerDef.visitSystemLibraries(selectedLinker, sysLibraryCollector); } // // if there was a <syslibset> in a nested <linker> // evaluate it last so it takes priority over // identically named libs from <cc> element // if (selectedLinkerDef != null) { // // add any system libraries to the hashtable // done in reverse order so the earliest // on the classpath takes priority selectedLinkerDef.visitSystemLibraries(selectedLinker, sysLibraryCollector); } // // copy over any system libraries to the // object files vector // Enumeration sysLibEnum = sysLibraries.elements(); while (sysLibEnum.hasMoreElements()) { sysObjectFiles.addElement(sysLibEnum.nextElement()); } return (LinkerConfiguration) linkerConfig; } /** * Adds an include path. * * Include paths will be inherited by nested compiler elements that do not * have inherit="false". */ public IncludePath createIncludePath() { return compilerDef.createIncludePath(); } /** * Specifies precompilation prototype file and exclusions. Inherited by all * compilers that do not have inherit="false". * */ public PrecompileDef createPrecompile() throws BuildException { return compilerDef.createPrecompile(); } /** * Adds a system include path. Locations and timestamps of files located * using the system include paths are not used in dependency analysis. * * * Standard include locations should not be specified. The compiler adapters * should recognized the settings from the appropriate environment variables * or configuration files. * * System include paths will be inherited by nested compiler elements that * do not have inherit="false". */ public SystemIncludePath createSysIncludePath() { return compilerDef.createSysIncludePath(); } /** * Executes the task. Compiles the given files. * * @throws BuildException * if someting goes wrong with the build */ public void execute() throws BuildException { // // if link type allowed objdir to be defaulted // provide it from outfile if (_objDir == null) { if (_outfile != null) { _objDir = new File(_outfile.getParent()); } else { _objDir = new File("."); } } // // if the object directory does not exist // if (!_objDir.exists()) { throw new BuildException("Object directory does not exist"); } TargetHistoryTable objHistory = new TargetHistoryTable(this, _objDir); // // get the first active version info // VersionInfo versionInfo = null; Enumeration versionEnum = versionInfos.elements(); while (versionEnum.hasMoreElements()) { versionInfo = (VersionInfo) versionEnum.nextElement(); versionInfo = versionInfo.merge(); if (versionInfo.isActive()) { break; } else { versionInfo = null; } } // // determine the eventual linker configuration // (may be null) and collect any explicit // object files or libraries Vector objectFiles = new Vector(); Vector sysObjectFiles = new Vector(); LinkerConfiguration linkerConfig = collectExplicitObjectFiles( objectFiles, sysObjectFiles, versionInfo); // // Assemble hashtable of all files // that we know how to compile (keyed by output file name) // Hashtable targets = getTargets(linkerConfig, objectFiles, versionInfo, _outfile); TargetInfo linkTarget = null; // // if output file is not specified, // then skip link step // if (_outfile != null) { linkTarget = getLinkTarget(linkerConfig, objectFiles, sysObjectFiles, targets, versionInfo); } if (projects.size() > 0) { ArrayList files = new ArrayList(); ProjectFileCollector matcher = new ProjectFileCollector(files); for (int i = 0; i < _compilers.size(); i++) { CompilerDef currentCompilerDef = (CompilerDef) _compilers .elementAt(i); if (currentCompilerDef.isActive()) { if (currentCompilerDef.hasFileSets()) { currentCompilerDef.visitFiles(matcher); } } } compilerDef.visitFiles(matcher); Enumeration iter = projects.elements(); while (iter.hasMoreElements()) { ProjectDef projectDef = (ProjectDef) iter.nextElement(); if (projectDef.isActive()) { projectDef.execute(this, files, targets, linkTarget); } } } if (projectsOnly) return; // // mark targets that don't have a history record or // whose source last modification time is not // the same as the history to be rebuilt // objHistory.markForRebuild(targets); CCTaskProgressMonitor monitor = new CCTaskProgressMonitor(objHistory, versionInfo); // // check for changed include files // int rebuildCount = checkForChangedIncludeFiles(targets); if (rebuildCount > 0) { BuildException compileException = null; // // compile all targets with getRebuild() == true // Hashtable targetsByConfig = getTargetsToBuildByConfiguration(targets); // // build array containing Vectors with precompiled generation // steps going first // Vector[] targetVectors = new Vector[targetsByConfig.size()]; int index = 0; Enumeration targetVectorEnum = targetsByConfig.elements(); while (targetVectorEnum.hasMoreElements()) { Vector targetsForConfig = (Vector) targetVectorEnum .nextElement(); // // get the configuration from the first entry // CompilerConfiguration config = (CompilerConfiguration) ((TargetInfo) targetsForConfig .elementAt(0)).getConfiguration(); if (config.isPrecompileGeneration()) { targetVectors[index++] = targetsForConfig; } } targetVectorEnum = targetsByConfig.elements(); while (targetVectorEnum.hasMoreElements()) { Vector targetsForConfig = (Vector) targetVectorEnum .nextElement(); for (int i = 0; i < targetVectors.length; i++) { if (targetVectors[i] == targetsForConfig) { break; } if (targetVectors[i] == null) { targetVectors[i] = targetsForConfig; break; } } } // BEGINFREEHEP Progress progress = new Progress(getObjdir(), rebuildCount); progress.start(); for (int i = 0; i < targetVectors.length; i++) { // // get the targets for this configuration // Vector targetsForConfig = targetVectors[i]; // // get the configuration from the first entry // CompilerConfiguration config = (CompilerConfiguration) ((TargetInfo) targetsForConfig .elementAt(0)).getConfiguration(); // // prepare the list of source files // // BEGINFREEHEP int noOfCores = Runtime.getRuntime().availableProcessors(); if (maxCores > 0) { noOfCores = Math.min(maxCores, noOfCores); } int noOfFiles = targetsForConfig.size(); if (noOfFiles < noOfCores) noOfCores = targetsForConfig.size(); Set[] sourceFiles = new HashSet[noOfCores]; for (int j = 0; j < sourceFiles.length; j++) { sourceFiles[j] = new HashSet(targetsForConfig.size() / sourceFiles.length); } Enumeration targetsEnum = targetsForConfig.elements(); index = 0; while (targetsEnum.hasMoreElements()) { TargetInfo targetInfo = ((TargetInfo) targetsEnum .nextElement()); sourceFiles[index++].add(targetInfo.getSources()[0] .toString()); index %= sourceFiles.length; } // setup cores/cpus Core[] cores = new Core[noOfCores]; for (int j = 0; j < cores.length; j++) { cores[j] = new Core(this, j, config, _objDir, sourceFiles[j], relentless, monitor); log("\nStarting Core " + j + " with " + sourceFiles[j].size() + " source files..."); } // starting cores for (int j = 0; j < cores.length; j++) { cores[j].start(); } // checking cores boolean alive = false; try { do { alive = false; for (int j = 0; j < cores.length; j++) { if (cores[j] != null) { if (cores[j].isAlive()) { alive = true; } else { Exception exception = cores[j].getException(); if (exception != null) { if ((compileException == null) && (exception instanceof BuildException)) { compileException = (BuildException)exception; } else { log(cores[j].getName()+" "+exception+" ", Project.MSG_ERR); } if (!relentless) { cores[j] = null; alive = false; break; } } cores[j] = null; } } } if (alive) { // wait for a maximum of 5 seconds or #files*2 seconds. Thread.sleep(Math.min(5000, sourceFiles[0].size()*2000)); } } while (alive); } catch (InterruptedException e) { break; } // killing leftovers for (int j = 0; j < cores.length; j++) { if (cores[j] != null) { cores[j].interrupt(); log(cores[j].getName()+" interrupted "); } } - if (!relentless) + if ((!relentless) && (compileException != null)) { break; + } // ENDFREEHEP } // BEGINFREEHEP progress.exit(); try { progress.join(); } catch (InterruptedException ex) { } // ENDFREEHEP // // save the details of the object file compilation // settings to disk for dependency analysis // try { objHistory.commit(); } catch (IOException ex) { this.log("Error writing history.xml: " + ex.toString()); } // // if we threw a compile exception and // didn't throw it at the time because // we were relentless then // save the history and // throw the exception // if (compileException != null) { if (failOnError) { throw compileException; } else { log(compileException.getMessage(), Project.MSG_ERR); return; } } } // // if the dependency tree was not fully // evaluated, then throw an exception // since we really didn't do what we // should have done // // if (dependencyDepth >= 0) { throw new BuildException( "All files at depth " + Integer.toString(dependencyDepth) + " from changes successfully compiled.\n" + "Remove or change dependencyDepth to -1 to perform full compilation."); } // // if no link target then // commit the history for the object files // and leave the task if (linkTarget != null) { // // get the history for the link target (may be the same // as the object history) TargetHistoryTable linkHistory = getLinkHistory(objHistory); // // see if it needs to be rebuilt // linkHistory.markForRebuild(linkTarget); // // if it needs to be rebuilt, rebuild it // File output = linkTarget.getOutput(); if (linkTarget.getRebuild()) { LinkerConfiguration linkConfig = (LinkerConfiguration) linkTarget .getConfiguration(); // BEGINFREEHEP log("Linking..."); log("Starting link {" + linkConfig.getIdentifier() + "}"); // ENDFREEHEP if (failOnError) { linkConfig.link(this, linkTarget); } else { try { linkConfig.link(this, linkTarget); } catch (BuildException ex) { log(ex.getMessage(), Project.MSG_ERR); return; } } if (outputFileProperty != null) getProject().setProperty(outputFileProperty, output.getAbsolutePath()); linkHistory.update(linkTarget); try { linkHistory.commit(); } catch (IOException ex) { log("Error writing link history.xml: " + ex.toString()); } } else { if (outputFileProperty != null) getProject().setProperty(outputFileProperty, output.getAbsolutePath()); } } } // BEGINFREEHEP class Core extends Thread { private CCTask task; private CompilerConfiguration config; private File objDir; private Set sourceFiles; private boolean relentless; private CCTaskProgressMonitor monitor; private Exception compileException; Core(CCTask task, int coreNo, CompilerConfiguration config, File objDir, Set set, boolean relentless, CCTaskProgressMonitor monitor) { super("Core "+coreNo); this.task = task; this.config = config; this.objDir = objDir; this.sourceFiles = set; this.relentless = relentless; this.monitor = monitor; } public Exception getException() { return compileException; } public void run() { super.run(); try { String[] sources = new String[sourceFiles.size()]; sources = (String[]) sourceFiles.toArray(sources); config.compile(task, objDir, sources, relentless, monitor); } catch (Exception ex) { if (compileException == null) { compileException = ex; } } } } // ENDFREEHEP // BEGINFREEHEP class Progress extends Thread { private boolean stop = false; private File objDir; private int rebuildCount; public Progress(File objDir, int rebuildCount) { this.objDir = objDir; this.rebuildCount = rebuildCount; } public void run() { if (rebuildCount < 10) return; try { FileFilter updatedFiles = new FileFilter() { private long startTime = System.currentTimeMillis(); public boolean accept(File file) { return file.lastModified() > startTime && !file.getName().endsWith(".xml"); } }; while (!stop) { System.err.print("\r" + objDir.listFiles(updatedFiles).length + " / " + rebuildCount + " files compiled..."); System.err.print("\r"); System.err.flush(); if (!stop) { Thread.sleep(5000); } } } catch (InterruptedException e) { } System.err .print("\r "); System.err.print("\r"); System.err.flush(); log(Integer.toString(rebuildCount) + " files were compiled."); } public void exit() { stop = true; } } // ENDFREEHEP /** * Gets the dataset. * * @return Returns a String */ public String getDataset() { return dataset; } protected TargetHistoryTable getLinkHistory(TargetHistoryTable objHistory) { File outputFileDir = new File(_outfile.getParent()); // // if the output file is being produced in the link // directory, then we can use the same history file // if (_objDir.equals(outputFileDir)) { return objHistory; } return new TargetHistoryTable(this, outputFileDir); } protected TargetInfo getLinkTarget(LinkerConfiguration linkerConfig, Vector objectFiles, Vector sysObjectFiles, Hashtable compileTargets, VersionInfo versionInfo) { // // walk the compile phase targets and // add those sources that have already been // assigned to the linker or // our output files the linker knows how to consume // files the linker knows how to consume // Enumeration compileTargetsEnum = compileTargets.elements(); while (compileTargetsEnum.hasMoreElements()) { TargetInfo compileTarget = (TargetInfo) compileTargetsEnum .nextElement(); // // output of compile tasks // int bid = linkerConfig.bid(compileTarget.getOutput().toString()); if (bid > 0) { objectFiles.addElement(compileTarget.getOutput()); } } File[] objectFileArray = new File[objectFiles.size()]; objectFiles.copyInto(objectFileArray); File[] sysObjectFileArray = new File[sysObjectFiles.size()]; sysObjectFiles.copyInto(sysObjectFileArray); String baseName = _outfile.getName(); String[] fullNames = linkerConfig.getOutputFileNames(baseName, versionInfo); File outputFile = new File(_outfile.getParent(), fullNames[0]); return new TargetInfo(linkerConfig, objectFileArray, sysObjectFileArray, outputFile, linkerConfig.getRebuild()); } public File getObjdir() { return _objDir; } public File getOutfile() { return _outfile; } public TargetDef getTargetPlatform() { return null; } /** * This method collects a Hashtable, keyed by output file name, of * TargetInfo's for every source file that is specified in the filesets of * the <cc>and nested <compiler>elements. The TargetInfo's contain the * appropriate compiler configurations for their possible compilation * */ private Hashtable getTargets(LinkerConfiguration linkerConfig, Vector objectFiles, VersionInfo versionInfo, File outputFile) { Hashtable targets = new Hashtable(1000); TargetDef targetPlatform = getTargetPlatform(); // // find active (specialized) compilers // Vector biddingProcessors = new Vector(_compilers.size()); for (int i = 0; i < _compilers.size(); i++) { CompilerDef currentCompilerDef = (CompilerDef) _compilers .elementAt(i); if (currentCompilerDef.isActive()) { ProcessorConfiguration config = currentCompilerDef .createConfiguration(this, linkType, compilerDef, targetPlatform, versionInfo); // // see if this processor had a precompile child element // PrecompileDef precompileDef = currentCompilerDef .getActivePrecompile(compilerDef); ProcessorConfiguration[] localConfigs = new ProcessorConfiguration[] { config }; // // if it does then // if (precompileDef != null) { File prototype = precompileDef.getPrototype(); // // will throw exceptions if prototype doesn't exist, etc // if (!prototype.exists()) { throw new BuildException("prototype (" + prototype.toString() + ") does not exist."); } if (prototype.isDirectory()) { throw new BuildException("prototype (" + prototype.toString() + ") is a directory."); } String[] exceptFiles = precompileDef.getExceptFiles(); // // create a precompile building and precompile using // variants of the configuration // or return null if compiler doesn't support // precompilation CompilerConfiguration[] configs = ((CompilerConfiguration) config) .createPrecompileConfigurations(prototype, exceptFiles); if (configs != null && configs.length == 2) { // // visit the precompiled file to add it into the // targets list (just like any other file if // compiler doesn't support precompilation) TargetMatcher matcher = new TargetMatcher(this, _objDir, new ProcessorConfiguration[] { configs[0] }, linkerConfig, objectFiles, targets, versionInfo); matcher.visit(new File(prototype.getParent()), prototype.getName()); // // only the configuration that uses the // precompiled header gets added to the bidding list biddingProcessors.addElement(configs[1]); localConfigs = new ProcessorConfiguration[2]; localConfigs[0] = configs[1]; localConfigs[1] = config; } } // // if the compiler has a fileset // then allow it to add its files // to the set of potential targets if (currentCompilerDef.hasFileSets()) { TargetMatcher matcher = new TargetMatcher(this, _objDir, localConfigs, linkerConfig, objectFiles, targets, versionInfo); currentCompilerDef.visitFiles(matcher); } biddingProcessors.addElement(config); } } // // add fallback compiler at the end // ProcessorConfiguration config = compilerDef.createConfiguration(this, linkType, null, targetPlatform, versionInfo); biddingProcessors.addElement(config); ProcessorConfiguration[] bidders = new ProcessorConfiguration[biddingProcessors .size()]; biddingProcessors.copyInto(bidders); // // bid out the <fileset>'s in the cctask // TargetMatcher matcher = new TargetMatcher(this, _objDir, bidders, linkerConfig, objectFiles, targets, versionInfo); compilerDef.visitFiles(matcher); if (outputFile != null && versionInfo != null) { boolean isDebug = linkerConfig.isDebug(); try { linkerConfig.getLinker().addVersionFiles(versionInfo, linkType, outputFile, isDebug, _objDir, matcher); } catch (IOException ex) { throw new BuildException(ex); } } return targets; } /** * Sets the default compiler adapter. Use the "name" attribute when the * compiler is a supported compiler. * * @param classname * fully qualified classname which implements CompilerAdapter */ public void setClassname(String classname) { compilerDef.setClassname(classname); linkerDef.setClassname(classname); } /** * Sets the dataset for OS/390 builds. * * @param dataset * The dataset to set */ public void setDataset(String dataset) { this.dataset = dataset; } /** * Enables or disables generation of debug info. */ public void setDebug(boolean debug) { compilerDef.setDebug(debug); linkerDef.setDebug(debug); } /** * Gets debug state. * * @return true if building for debugging */ public boolean getDebug() { return compilerDef.getDebug(null, 0); } /** * Deprecated. * * Controls the depth of the dependency evaluation. Used to do a quick check * of changes before a full build. * * Any negative value which will perform full dependency checking. Positive * values will truncate dependency checking. A value of 0 will cause only * those files that changed to be recompiled, a value of 1 which cause files * that changed or that explicitly include a file that changed to be * recompiled. * * Any non-negative value will cause a BuildException to be thrown before * attempting a link or completing the task. * */ public void setDependencyDepth(int depth) { dependencyDepth = depth; } /** * Enables generation of exception handling code */ public void setExceptions(boolean exceptions) { compilerDef.setExceptions(exceptions); } /** * Enables run-time type information. */ public void setRtti(boolean rtti) { compilerDef.setRtti(rtti); } // public LinkType getLinkType() { // return linkType; // } /** * Enables or disables incremental linking. * * @param incremental * new state */ public void setIncremental(boolean incremental) { linkerDef.setIncremental(incremental); } /** * Set use of libtool. * * If set to true, the "libtool " will be prepended to the command line for * compatible processors * * @param libtool * If true, use libtool. */ public void setLibtool(boolean libtool) { compilerDef.setLibtool(libtool); linkerDef.setLibtool(libtool); } /** * Sets the output file type. Supported values "executable", "shared", and * "static". Deprecated, specify outtype instead. * * @deprecated */ public void setLink(OutputTypeEnum outputType) { linkType.setOutputType(outputType); } // BEGINFREEHEP public void setLinkCPP(boolean linkCPP) { linkType.setLinkCPP(linkCPP); } // ENDFREEHEP /** * Enables or disables generation of multithreaded code * * @param multi * If true, generated code may be multithreaded. */ public void setMultithreaded(boolean multi) { compilerDef.setMultithreaded(multi); } // // keep near duplicate comment at CompilerDef.setName in sync // /** * Sets type of the default compiler and linker. * * <table width="100%" border="1"> <thead>Supported compilers </thead> * <tr> * <td>gcc (default)</td> * <td>GCC C++ compiler</td> * </tr> * <tr> * <td>g++</td> * <td>GCC C++ compiler</td> * </tr> * <tr> * <td>c++</td> * <td>GCC C++ compiler</td> * </tr> * <tr> * <td>g77</td> * <td>GNU FORTRAN compiler</td> * </tr> * <tr> * <td>msvc</td> * <td>Microsoft Visual C++</td> * </tr> * <tr> * <td>bcc</td> * <td>Borland C++ Compiler</td> * </tr> * <tr> * <td>msrc</td> * <td>Microsoft Resource Compiler</td> * </tr> * <tr> * <td>brc</td> * <td>Borland Resource Compiler</td> * </tr> * <tr> * <td>df</td> * <td>Compaq Visual Fortran Compiler</td> * </tr> * <tr> * <td>midl</td> * <td>Microsoft MIDL Compiler</td> * </tr> * <tr> * <td>icl</td> * <td>Intel C++ compiler for Windows (IA-32)</td> * </tr> * <tr> * <td>ecl</td> * <td>Intel C++ compiler for Windows (IA-64)</td> * </tr> * <tr> * <td>icc</td> * <td>Intel C++ compiler for Linux (IA-32)</td> * </tr> * <tr> * <td>ecc</td> * <td>Intel C++ compiler for Linux (IA-64)</td> * </tr> * <tr> * <td>CC</td> * <td>Sun ONE C++ compiler</td> * </tr> * <tr> * <td>aCC</td> * <td>HP aC++ C++ Compiler</td> * </tr> * <tr> * <td>os390</td> * <td>OS390 C Compiler</td> * </tr> * <tr> * <td>os400</td> * <td>Icc Compiler</td> * </tr> * <tr> * <td>sunc89</td> * <td>Sun C89 C Compiler</td> * </tr> * <tr> * <td>xlC</td> * <td>VisualAge C Compiler</td> * </tr> * <tr> * <td>uic</td> * <td>Qt user interface compiler (creates .h, .cpp and moc_*.cpp files).</td> * </tr> * <tr> * <td>moc</td> * <td>Qt meta-object compiler</td> * </tr> * <tr> * <td>xpidl</td> * <td>Mozilla xpidl compiler (creates .h and .xpt files).</td> * </tr> * <tr> * <td>wcl</td> * <td>OpenWatcom C/C++ compiler</td> * </tr> * <tr> * <td>wfl</td> * <td>OpenWatcom FORTRAN compiler</td> * </tr> * </table> * */ public void setName(CompilerEnum name) { compilerDef.setName(name); Processor compiler = compilerDef.getProcessor(); Linker linker = compiler.getLinker(linkType); linkerDef.setProcessor(linker); } /** * Do not propagate old environment when new environment variables are * specified. */ public void setNewenvironment(boolean newenv) { compilerDef.setNewenvironment(newenv); linkerDef.setNewenvironment(newenv); } /** * Sets the destination directory for object files. * * Generally this should be a property expression that evaluates to distinct * debug and release object file directories. * * @param dir * object directory */ public void setObjdir(File dir) { if (dir == null) { throw new NullPointerException("dir"); } _objDir = dir; } /** * Sets the output file name. If not specified, the task will only compile * files and not attempt to link. If an extension is not specified, the task * may use a system appropriate extension and prefix, for example, * outfile="example" may result in "libexample.so" being created. * * @param outfile * output file name */ public void setOutfile(File outfile) { // // if file name was empty, skip link step // if (outfile == null || outfile.toString().length() > 0) { _outfile = outfile; } } /** * Specifies the name of a property to set with the physical filename that * is produced by the linker */ public void setOutputFileProperty(String outputFileProperty) { this.outputFileProperty = outputFileProperty; } /** * Sets the output file type. Supported values "executable", "shared", and * "static". */ public void setOuttype(OutputTypeEnum outputType) { linkType.setOutputType(outputType); } /** * Gets output type. * * @return output type */ public String getOuttype() { return linkType.getOutputType(); } /** * Sets the project. */ public void setProject(Project project) { super.setProject(project); compilerDef.setProject(project); linkerDef.setProject(project); } /** * If set to true, all files will be rebuilt. * * @paran rebuildAll If true, all files will be rebuilt. If false, up to * date files will not be rebuilt. */ public void setRebuild(boolean rebuildAll) { compilerDef.setRebuild(rebuildAll); linkerDef.setRebuild(rebuildAll); } /** * If set to true, compilation errors will not stop the task until all files * have been attempted. * * @param relentless * If true, don't stop on the first compilation error * */ public void setRelentless(boolean relentless) { this.relentless = relentless; } /** * Sets the type of runtime library, possible values "dynamic", "static". */ public void setRuntime(RuntimeType rtlType) { linkType.setStaticRuntime((rtlType.getIndex() == 1)); } /** * Sets the nature of the subsystem under which that the program will * execute. * * <table width="100%" border="1"> <thead>Supported subsystems </thead> * <tr> * <td>gui</td> * <td>Graphical User Interface</td> * </tr> * <tr> * <td>console</td> * <td>Command Line Console</td> * </tr> * <tr> * <td>other</td> * <td>Other</td> * </tr> * </table> * * @param subsystem * subsystem * @throws NullPointerException * if subsystem is null */ public void setSubsystem(SubsystemEnum subsystem) { if (subsystem == null) { throw new NullPointerException("subsystem"); } linkType.setSubsystem(subsystem); } /** * Gets subsystem name. * * @return Subsystem name */ public String getSubsystem() { return linkType.getSubsystem(); } /** * Enumerated attribute with the values "none", "severe", "default", * "production", "diagnostic", and "failtask". */ public void setWarnings(WarningLevelEnum level) { compilerDef.setWarnings(level); } // BEGINFREEHEP public void setMaxCores(int maxCores) { this.maxCores = maxCores; } public int getMaxCores() { return maxCores; } // ENDFREEHEP /** * Indicates whether the build will continue even if there are compilation * errors; defaults to true. * * @param fail * if true halt the build on failure */ public void setFailonerror(boolean fail) { failOnError = fail; } /** * Gets the failonerror flag. * * @return the failonerror flag */ public boolean getFailonerror() { return failOnError; } /** * Adds a target definition or reference (Non-functional prototype). * * @param target * target * @throws NullPointerException * if compiler is null */ public void addConfiguredTarget(TargetDef target) { if (target == null) { throw new NullPointerException("target"); } target.setProject(getProject()); targetPlatforms.addElement(target); } /** * Adds a distributer definition or reference (Non-functional prototype). * * @param distributer * distributer * @throws NullPointerException * if compiler is null */ public void addConfiguredDistributer(DistributerDef distributer) { if (distributer == null) { throw new NullPointerException("distributer"); } distributer.setProject(getProject()); distributers.addElement(distributer); } /** * Sets optimization. * * @param optimization */ public void setOptimize(OptimizationEnum optimization) { compilerDef.setOptimize(optimization); } /** * Adds desriptive version information to be included in the generated file. * The first active version info block will be used. */ public void addConfiguredVersioninfo(VersionInfo newVersionInfo) { newVersionInfo.setProject(this.getProject()); versionInfos.addElement(newVersionInfo); } }
false
true
public void execute() throws BuildException { // // if link type allowed objdir to be defaulted // provide it from outfile if (_objDir == null) { if (_outfile != null) { _objDir = new File(_outfile.getParent()); } else { _objDir = new File("."); } } // // if the object directory does not exist // if (!_objDir.exists()) { throw new BuildException("Object directory does not exist"); } TargetHistoryTable objHistory = new TargetHistoryTable(this, _objDir); // // get the first active version info // VersionInfo versionInfo = null; Enumeration versionEnum = versionInfos.elements(); while (versionEnum.hasMoreElements()) { versionInfo = (VersionInfo) versionEnum.nextElement(); versionInfo = versionInfo.merge(); if (versionInfo.isActive()) { break; } else { versionInfo = null; } } // // determine the eventual linker configuration // (may be null) and collect any explicit // object files or libraries Vector objectFiles = new Vector(); Vector sysObjectFiles = new Vector(); LinkerConfiguration linkerConfig = collectExplicitObjectFiles( objectFiles, sysObjectFiles, versionInfo); // // Assemble hashtable of all files // that we know how to compile (keyed by output file name) // Hashtable targets = getTargets(linkerConfig, objectFiles, versionInfo, _outfile); TargetInfo linkTarget = null; // // if output file is not specified, // then skip link step // if (_outfile != null) { linkTarget = getLinkTarget(linkerConfig, objectFiles, sysObjectFiles, targets, versionInfo); } if (projects.size() > 0) { ArrayList files = new ArrayList(); ProjectFileCollector matcher = new ProjectFileCollector(files); for (int i = 0; i < _compilers.size(); i++) { CompilerDef currentCompilerDef = (CompilerDef) _compilers .elementAt(i); if (currentCompilerDef.isActive()) { if (currentCompilerDef.hasFileSets()) { currentCompilerDef.visitFiles(matcher); } } } compilerDef.visitFiles(matcher); Enumeration iter = projects.elements(); while (iter.hasMoreElements()) { ProjectDef projectDef = (ProjectDef) iter.nextElement(); if (projectDef.isActive()) { projectDef.execute(this, files, targets, linkTarget); } } } if (projectsOnly) return; // // mark targets that don't have a history record or // whose source last modification time is not // the same as the history to be rebuilt // objHistory.markForRebuild(targets); CCTaskProgressMonitor monitor = new CCTaskProgressMonitor(objHistory, versionInfo); // // check for changed include files // int rebuildCount = checkForChangedIncludeFiles(targets); if (rebuildCount > 0) { BuildException compileException = null; // // compile all targets with getRebuild() == true // Hashtable targetsByConfig = getTargetsToBuildByConfiguration(targets); // // build array containing Vectors with precompiled generation // steps going first // Vector[] targetVectors = new Vector[targetsByConfig.size()]; int index = 0; Enumeration targetVectorEnum = targetsByConfig.elements(); while (targetVectorEnum.hasMoreElements()) { Vector targetsForConfig = (Vector) targetVectorEnum .nextElement(); // // get the configuration from the first entry // CompilerConfiguration config = (CompilerConfiguration) ((TargetInfo) targetsForConfig .elementAt(0)).getConfiguration(); if (config.isPrecompileGeneration()) { targetVectors[index++] = targetsForConfig; } } targetVectorEnum = targetsByConfig.elements(); while (targetVectorEnum.hasMoreElements()) { Vector targetsForConfig = (Vector) targetVectorEnum .nextElement(); for (int i = 0; i < targetVectors.length; i++) { if (targetVectors[i] == targetsForConfig) { break; } if (targetVectors[i] == null) { targetVectors[i] = targetsForConfig; break; } } } // BEGINFREEHEP Progress progress = new Progress(getObjdir(), rebuildCount); progress.start(); for (int i = 0; i < targetVectors.length; i++) { // // get the targets for this configuration // Vector targetsForConfig = targetVectors[i]; // // get the configuration from the first entry // CompilerConfiguration config = (CompilerConfiguration) ((TargetInfo) targetsForConfig .elementAt(0)).getConfiguration(); // // prepare the list of source files // // BEGINFREEHEP int noOfCores = Runtime.getRuntime().availableProcessors(); if (maxCores > 0) { noOfCores = Math.min(maxCores, noOfCores); } int noOfFiles = targetsForConfig.size(); if (noOfFiles < noOfCores) noOfCores = targetsForConfig.size(); Set[] sourceFiles = new HashSet[noOfCores]; for (int j = 0; j < sourceFiles.length; j++) { sourceFiles[j] = new HashSet(targetsForConfig.size() / sourceFiles.length); } Enumeration targetsEnum = targetsForConfig.elements(); index = 0; while (targetsEnum.hasMoreElements()) { TargetInfo targetInfo = ((TargetInfo) targetsEnum .nextElement()); sourceFiles[index++].add(targetInfo.getSources()[0] .toString()); index %= sourceFiles.length; } // setup cores/cpus Core[] cores = new Core[noOfCores]; for (int j = 0; j < cores.length; j++) { cores[j] = new Core(this, j, config, _objDir, sourceFiles[j], relentless, monitor); log("\nStarting Core " + j + " with " + sourceFiles[j].size() + " source files..."); } // starting cores for (int j = 0; j < cores.length; j++) { cores[j].start(); } // checking cores boolean alive = false; try { do { alive = false; for (int j = 0; j < cores.length; j++) { if (cores[j] != null) { if (cores[j].isAlive()) { alive = true; } else { Exception exception = cores[j].getException(); if (exception != null) { if ((compileException == null) && (exception instanceof BuildException)) { compileException = (BuildException)exception; } else { log(cores[j].getName()+" "+exception+" ", Project.MSG_ERR); } if (!relentless) { cores[j] = null; alive = false; break; } } cores[j] = null; } } } if (alive) { // wait for a maximum of 5 seconds or #files*2 seconds. Thread.sleep(Math.min(5000, sourceFiles[0].size()*2000)); } } while (alive); } catch (InterruptedException e) { break; } // killing leftovers for (int j = 0; j < cores.length; j++) { if (cores[j] != null) { cores[j].interrupt(); log(cores[j].getName()+" interrupted "); } } if (!relentless) break; // ENDFREEHEP } // BEGINFREEHEP progress.exit(); try { progress.join(); } catch (InterruptedException ex) { } // ENDFREEHEP // // save the details of the object file compilation // settings to disk for dependency analysis // try { objHistory.commit(); } catch (IOException ex) { this.log("Error writing history.xml: " + ex.toString()); } // // if we threw a compile exception and // didn't throw it at the time because // we were relentless then // save the history and // throw the exception // if (compileException != null) { if (failOnError) { throw compileException; } else { log(compileException.getMessage(), Project.MSG_ERR); return; } } } // // if the dependency tree was not fully // evaluated, then throw an exception // since we really didn't do what we // should have done // // if (dependencyDepth >= 0) { throw new BuildException( "All files at depth " + Integer.toString(dependencyDepth) + " from changes successfully compiled.\n" + "Remove or change dependencyDepth to -1 to perform full compilation."); } // // if no link target then // commit the history for the object files // and leave the task if (linkTarget != null) { // // get the history for the link target (may be the same // as the object history) TargetHistoryTable linkHistory = getLinkHistory(objHistory); // // see if it needs to be rebuilt // linkHistory.markForRebuild(linkTarget); // // if it needs to be rebuilt, rebuild it // File output = linkTarget.getOutput(); if (linkTarget.getRebuild()) { LinkerConfiguration linkConfig = (LinkerConfiguration) linkTarget .getConfiguration(); // BEGINFREEHEP log("Linking..."); log("Starting link {" + linkConfig.getIdentifier() + "}"); // ENDFREEHEP if (failOnError) { linkConfig.link(this, linkTarget); } else { try { linkConfig.link(this, linkTarget); } catch (BuildException ex) { log(ex.getMessage(), Project.MSG_ERR); return; } } if (outputFileProperty != null) getProject().setProperty(outputFileProperty, output.getAbsolutePath()); linkHistory.update(linkTarget); try { linkHistory.commit(); } catch (IOException ex) { log("Error writing link history.xml: " + ex.toString()); } } else { if (outputFileProperty != null) getProject().setProperty(outputFileProperty, output.getAbsolutePath()); } } }
public void execute() throws BuildException { // // if link type allowed objdir to be defaulted // provide it from outfile if (_objDir == null) { if (_outfile != null) { _objDir = new File(_outfile.getParent()); } else { _objDir = new File("."); } } // // if the object directory does not exist // if (!_objDir.exists()) { throw new BuildException("Object directory does not exist"); } TargetHistoryTable objHistory = new TargetHistoryTable(this, _objDir); // // get the first active version info // VersionInfo versionInfo = null; Enumeration versionEnum = versionInfos.elements(); while (versionEnum.hasMoreElements()) { versionInfo = (VersionInfo) versionEnum.nextElement(); versionInfo = versionInfo.merge(); if (versionInfo.isActive()) { break; } else { versionInfo = null; } } // // determine the eventual linker configuration // (may be null) and collect any explicit // object files or libraries Vector objectFiles = new Vector(); Vector sysObjectFiles = new Vector(); LinkerConfiguration linkerConfig = collectExplicitObjectFiles( objectFiles, sysObjectFiles, versionInfo); // // Assemble hashtable of all files // that we know how to compile (keyed by output file name) // Hashtable targets = getTargets(linkerConfig, objectFiles, versionInfo, _outfile); TargetInfo linkTarget = null; // // if output file is not specified, // then skip link step // if (_outfile != null) { linkTarget = getLinkTarget(linkerConfig, objectFiles, sysObjectFiles, targets, versionInfo); } if (projects.size() > 0) { ArrayList files = new ArrayList(); ProjectFileCollector matcher = new ProjectFileCollector(files); for (int i = 0; i < _compilers.size(); i++) { CompilerDef currentCompilerDef = (CompilerDef) _compilers .elementAt(i); if (currentCompilerDef.isActive()) { if (currentCompilerDef.hasFileSets()) { currentCompilerDef.visitFiles(matcher); } } } compilerDef.visitFiles(matcher); Enumeration iter = projects.elements(); while (iter.hasMoreElements()) { ProjectDef projectDef = (ProjectDef) iter.nextElement(); if (projectDef.isActive()) { projectDef.execute(this, files, targets, linkTarget); } } } if (projectsOnly) return; // // mark targets that don't have a history record or // whose source last modification time is not // the same as the history to be rebuilt // objHistory.markForRebuild(targets); CCTaskProgressMonitor monitor = new CCTaskProgressMonitor(objHistory, versionInfo); // // check for changed include files // int rebuildCount = checkForChangedIncludeFiles(targets); if (rebuildCount > 0) { BuildException compileException = null; // // compile all targets with getRebuild() == true // Hashtable targetsByConfig = getTargetsToBuildByConfiguration(targets); // // build array containing Vectors with precompiled generation // steps going first // Vector[] targetVectors = new Vector[targetsByConfig.size()]; int index = 0; Enumeration targetVectorEnum = targetsByConfig.elements(); while (targetVectorEnum.hasMoreElements()) { Vector targetsForConfig = (Vector) targetVectorEnum .nextElement(); // // get the configuration from the first entry // CompilerConfiguration config = (CompilerConfiguration) ((TargetInfo) targetsForConfig .elementAt(0)).getConfiguration(); if (config.isPrecompileGeneration()) { targetVectors[index++] = targetsForConfig; } } targetVectorEnum = targetsByConfig.elements(); while (targetVectorEnum.hasMoreElements()) { Vector targetsForConfig = (Vector) targetVectorEnum .nextElement(); for (int i = 0; i < targetVectors.length; i++) { if (targetVectors[i] == targetsForConfig) { break; } if (targetVectors[i] == null) { targetVectors[i] = targetsForConfig; break; } } } // BEGINFREEHEP Progress progress = new Progress(getObjdir(), rebuildCount); progress.start(); for (int i = 0; i < targetVectors.length; i++) { // // get the targets for this configuration // Vector targetsForConfig = targetVectors[i]; // // get the configuration from the first entry // CompilerConfiguration config = (CompilerConfiguration) ((TargetInfo) targetsForConfig .elementAt(0)).getConfiguration(); // // prepare the list of source files // // BEGINFREEHEP int noOfCores = Runtime.getRuntime().availableProcessors(); if (maxCores > 0) { noOfCores = Math.min(maxCores, noOfCores); } int noOfFiles = targetsForConfig.size(); if (noOfFiles < noOfCores) noOfCores = targetsForConfig.size(); Set[] sourceFiles = new HashSet[noOfCores]; for (int j = 0; j < sourceFiles.length; j++) { sourceFiles[j] = new HashSet(targetsForConfig.size() / sourceFiles.length); } Enumeration targetsEnum = targetsForConfig.elements(); index = 0; while (targetsEnum.hasMoreElements()) { TargetInfo targetInfo = ((TargetInfo) targetsEnum .nextElement()); sourceFiles[index++].add(targetInfo.getSources()[0] .toString()); index %= sourceFiles.length; } // setup cores/cpus Core[] cores = new Core[noOfCores]; for (int j = 0; j < cores.length; j++) { cores[j] = new Core(this, j, config, _objDir, sourceFiles[j], relentless, monitor); log("\nStarting Core " + j + " with " + sourceFiles[j].size() + " source files..."); } // starting cores for (int j = 0; j < cores.length; j++) { cores[j].start(); } // checking cores boolean alive = false; try { do { alive = false; for (int j = 0; j < cores.length; j++) { if (cores[j] != null) { if (cores[j].isAlive()) { alive = true; } else { Exception exception = cores[j].getException(); if (exception != null) { if ((compileException == null) && (exception instanceof BuildException)) { compileException = (BuildException)exception; } else { log(cores[j].getName()+" "+exception+" ", Project.MSG_ERR); } if (!relentless) { cores[j] = null; alive = false; break; } } cores[j] = null; } } } if (alive) { // wait for a maximum of 5 seconds or #files*2 seconds. Thread.sleep(Math.min(5000, sourceFiles[0].size()*2000)); } } while (alive); } catch (InterruptedException e) { break; } // killing leftovers for (int j = 0; j < cores.length; j++) { if (cores[j] != null) { cores[j].interrupt(); log(cores[j].getName()+" interrupted "); } } if ((!relentless) && (compileException != null)) { break; } // ENDFREEHEP } // BEGINFREEHEP progress.exit(); try { progress.join(); } catch (InterruptedException ex) { } // ENDFREEHEP // // save the details of the object file compilation // settings to disk for dependency analysis // try { objHistory.commit(); } catch (IOException ex) { this.log("Error writing history.xml: " + ex.toString()); } // // if we threw a compile exception and // didn't throw it at the time because // we were relentless then // save the history and // throw the exception // if (compileException != null) { if (failOnError) { throw compileException; } else { log(compileException.getMessage(), Project.MSG_ERR); return; } } } // // if the dependency tree was not fully // evaluated, then throw an exception // since we really didn't do what we // should have done // // if (dependencyDepth >= 0) { throw new BuildException( "All files at depth " + Integer.toString(dependencyDepth) + " from changes successfully compiled.\n" + "Remove or change dependencyDepth to -1 to perform full compilation."); } // // if no link target then // commit the history for the object files // and leave the task if (linkTarget != null) { // // get the history for the link target (may be the same // as the object history) TargetHistoryTable linkHistory = getLinkHistory(objHistory); // // see if it needs to be rebuilt // linkHistory.markForRebuild(linkTarget); // // if it needs to be rebuilt, rebuild it // File output = linkTarget.getOutput(); if (linkTarget.getRebuild()) { LinkerConfiguration linkConfig = (LinkerConfiguration) linkTarget .getConfiguration(); // BEGINFREEHEP log("Linking..."); log("Starting link {" + linkConfig.getIdentifier() + "}"); // ENDFREEHEP if (failOnError) { linkConfig.link(this, linkTarget); } else { try { linkConfig.link(this, linkTarget); } catch (BuildException ex) { log(ex.getMessage(), Project.MSG_ERR); return; } } if (outputFileProperty != null) getProject().setProperty(outputFileProperty, output.getAbsolutePath()); linkHistory.update(linkTarget); try { linkHistory.commit(); } catch (IOException ex) { log("Error writing link history.xml: " + ex.toString()); } } else { if (outputFileProperty != null) getProject().setProperty(outputFileProperty, output.getAbsolutePath()); } } }
diff --git a/com.yoursway.utils/src/com/yoursway/utils/os/YsOSUtils.java b/com.yoursway.utils/src/com/yoursway/utils/os/YsOSUtils.java index 0a90676..0d23454 100644 --- a/com.yoursway.utils/src/com/yoursway/utils/os/YsOSUtils.java +++ b/com.yoursway.utils/src/com/yoursway/utils/os/YsOSUtils.java @@ -1,42 +1,43 @@ package com.yoursway.utils.os; import java.io.File; import java.io.IOException; public class YsOSUtils { private static OSUtils os; private static OSUtils os() { if (os == null) { String osName = System.getProperty("os.name"); + String lowercased = osName.toLowerCase(); - if (osName.equals("Mac OS X")) + if (lowercased.contains("mac")) os = new MacUtils(); - else if (osName.equals("Windows NT")) + else if (lowercased.contains("win")) os = new WinUtils(); if (os == null) throw new Error("Unknown OS " + osName); } return os; } public static boolean isMacOSX() { return os().isMacOSX(); } public static boolean isWindowsNT() { return os().isWindowsNT(); } public static void setExecAttribute(File file) throws IOException { os().setExecAttribute(file); } public static String javaRelativePath() { return os().javaRelativePath(); } }
false
true
private static OSUtils os() { if (os == null) { String osName = System.getProperty("os.name"); if (osName.equals("Mac OS X")) os = new MacUtils(); else if (osName.equals("Windows NT")) os = new WinUtils(); if (os == null) throw new Error("Unknown OS " + osName); } return os; }
private static OSUtils os() { if (os == null) { String osName = System.getProperty("os.name"); String lowercased = osName.toLowerCase(); if (lowercased.contains("mac")) os = new MacUtils(); else if (lowercased.contains("win")) os = new WinUtils(); if (os == null) throw new Error("Unknown OS " + osName); } return os; }
diff --git a/main/src/cgeo/geocaching/cgeocoords.java b/main/src/cgeo/geocaching/cgeocoords.java index 70ca164a7..972eba90b 100644 --- a/main/src/cgeo/geocaching/cgeocoords.java +++ b/main/src/cgeo/geocaching/cgeocoords.java @@ -1,488 +1,488 @@ package cgeo.geocaching; import cgeo.geocaching.cgSettings.coordInputFormatEnum; import cgeo.geocaching.activity.AbstractActivity; import cgeo.geocaching.geopoint.Geopoint; import cgeo.geocaching.geopoint.Geopoint.MalformedCoordinateException; import cgeo.geocaching.geopoint.GeopointFormatter; import cgeo.geocaching.geopoint.GeopointParser.ParseException; import org.apache.commons.lang3.StringUtils; import android.app.Dialog; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; public class cgeocoords extends Dialog { private AbstractActivity context = null; private cgSettings settings = null; private cgGeo geo = null; private Geopoint gp = null; private EditText eLat, eLon; private Button bLat, bLon; private EditText eLatDeg, eLatMin, eLatSec, eLatSub; private EditText eLonDeg, eLonMin, eLonSec, eLonSub; private TextView tLatSep1, tLatSep2, tLatSep3; private TextView tLonSep1, tLonSep2, tLonSep3; private Spinner spinner; CoordinateUpdate cuListener; coordInputFormatEnum currentFormat = null; public cgeocoords(final AbstractActivity contextIn, cgSettings settingsIn, final Geopoint gpIn, final cgGeo geoIn) { super(contextIn); context = contextIn; settings = settingsIn; geo = geoIn; if (gpIn != null) { gp = gpIn; } else if (geo != null && geo.coordsNow != null) { gp = geo.coordsNow; } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try { requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setLayout(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); } catch (Exception e) { // nothing } setContentView(R.layout.coords); spinner = (Spinner) findViewById(R.id.spinnerCoordinateFormats); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(context, R.array.waypoint_coordinate_formats, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); spinner.setSelection(settings.getCoordInputFormat().ordinal()); spinner.setOnItemSelectedListener(new CoordinateFormatListener()); bLat = (Button) findViewById(R.id.ButtonLat); eLat = (EditText) findViewById(R.id.latitude); eLatDeg = (EditText) findViewById(R.id.EditTextLatDeg); eLatMin = (EditText) findViewById(R.id.EditTextLatMin); eLatSec = (EditText) findViewById(R.id.EditTextLatSec); eLatSub = (EditText) findViewById(R.id.EditTextLatSecFrac); tLatSep1 = (TextView) findViewById(R.id.LatSeparator1); tLatSep2 = (TextView) findViewById(R.id.LatSeparator2); tLatSep3 = (TextView) findViewById(R.id.LatSeparator3); bLon = (Button) findViewById(R.id.ButtonLon); eLon = (EditText) findViewById(R.id.longitude); eLonDeg = (EditText) findViewById(R.id.EditTextLonDeg); eLonMin = (EditText) findViewById(R.id.EditTextLonMin); eLonSec = (EditText) findViewById(R.id.EditTextLonSec); eLonSub = (EditText) findViewById(R.id.EditTextLonSecFrac); tLonSep1 = (TextView) findViewById(R.id.LonSeparator1); tLonSep2 = (TextView) findViewById(R.id.LonSeparator2); tLonSep3 = (TextView) findViewById(R.id.LonSeparator3); eLatDeg.addTextChangedListener(new TextChanged(eLatDeg)); eLatMin.addTextChangedListener(new TextChanged(eLatMin)); eLatSec.addTextChangedListener(new TextChanged(eLatSec)); eLatSub.addTextChangedListener(new TextChanged(eLatSub)); eLonDeg.addTextChangedListener(new TextChanged(eLonDeg)); eLonMin.addTextChangedListener(new TextChanged(eLonMin)); eLonSec.addTextChangedListener(new TextChanged(eLonSec)); eLonSub.addTextChangedListener(new TextChanged(eLonSub)); bLat.setOnClickListener(new ButtonClickListener()); bLon.setOnClickListener(new ButtonClickListener()); Button buttonCurrent = (Button) findViewById(R.id.current); buttonCurrent.setOnClickListener(new CurrentListener()); Button buttonDone = (Button) findViewById(R.id.done); buttonDone.setOnClickListener(new InputDoneListener()); } private void updateGUI() { if (gp == null) return; Double lat = 0.0; if (gp.getLatitude() < 0) { bLat.setText("S"); } else { bLat.setText("N"); } lat = Math.abs(gp.getLatitude()); Double lon = 0.0; if (gp.getLongitude() < 0) { bLon.setText("W"); } else { bLon.setText("E"); } lon = Math.abs(gp.getLongitude()); int latDeg = (int) Math.floor(lat); int latDegFrac = (int) Math.round((lat - latDeg) * 100000); int latMin = (int) Math.floor((lat - latDeg) * 60); int latMinFrac = (int) Math.round(((lat - latDeg) * 60 - latMin) * 1000); int latSec = (int) Math.floor(((lat - latDeg) * 60 - latMin) * 60); int latSecFrac = (int) Math.round((((lat - latDeg) * 60 - latMin) * 60 - latSec) * 1000); int lonDeg = (int) Math.floor(lon); int lonDegFrac = (int) Math.round((lon - lonDeg) * 100000); int lonMin = (int) Math.floor((lon - lonDeg) * 60); int lonMinFrac = (int) Math.round(((lon - lonDeg) * 60 - lonMin) * 1000); int lonSec = (int) Math.floor(((lon - lonDeg) * 60 - lonMin) * 60); int lonSecFrac = (int) Math.round((((lon - lonDeg) * 60 - lonMin) * 60 - lonSec) * 1000); switch (currentFormat) { case Plain: findViewById(R.id.coordTable).setVisibility(View.GONE); eLat.setVisibility(View.VISIBLE); eLon.setVisibility(View.VISIBLE); eLat.setText(gp.format(GeopointFormatter.Format.LAT_DECMINUTE)); eLon.setText(gp.format(GeopointFormatter.Format.LON_DECMINUTE)); break; case Deg: // DDD.DDDDD° findViewById(R.id.coordTable).setVisibility(View.VISIBLE); eLat.setVisibility(View.GONE); eLon.setVisibility(View.GONE); eLatSec.setVisibility(View.GONE); eLonSec.setVisibility(View.GONE); tLatSep3.setVisibility(View.GONE); tLonSep3.setVisibility(View.GONE); eLatSub.setVisibility(View.GONE); eLonSub.setVisibility(View.GONE); tLatSep1.setText("."); tLonSep1.setText("."); tLatSep2.setText("°"); tLonSep2.setText("°"); eLatDeg.setText(addZeros(latDeg, 2)); eLatMin.setText(addZeros(latDegFrac, 5)); - eLonDeg.setText(addZeros(latDeg, 3)); + eLonDeg.setText(addZeros(lonDeg, 3)); eLonMin.setText(addZeros(lonDegFrac, 5)); break; case Min: // DDD° MM.MMM findViewById(R.id.coordTable).setVisibility(View.VISIBLE); eLat.setVisibility(View.GONE); eLon.setVisibility(View.GONE); eLatSec.setVisibility(View.VISIBLE); eLonSec.setVisibility(View.VISIBLE); tLatSep3.setVisibility(View.VISIBLE); tLonSep3.setVisibility(View.VISIBLE); eLatSub.setVisibility(View.GONE); eLonSub.setVisibility(View.GONE); tLatSep1.setText("°"); tLonSep1.setText("°"); tLatSep2.setText("."); tLonSep2.setText("."); tLatSep3.setText("'"); tLonSep3.setText("'"); eLatDeg.setText(addZeros(latDeg, 2)); eLatMin.setText(addZeros(latMin, 2)); eLatSec.setText(addZeros(latMinFrac, 3)); eLonDeg.setText(addZeros(lonDeg, 3)); eLonMin.setText(addZeros(lonMin, 2)); eLonSec.setText(addZeros(lonMinFrac, 3)); break; case Sec: // DDD° MM SS.SSS findViewById(R.id.coordTable).setVisibility(View.VISIBLE); eLat.setVisibility(View.GONE); eLon.setVisibility(View.GONE); eLatSec.setVisibility(View.VISIBLE); eLonSec.setVisibility(View.VISIBLE); tLatSep3.setVisibility(View.VISIBLE); tLonSep3.setVisibility(View.VISIBLE); eLatSub.setVisibility(View.VISIBLE); eLonSub.setVisibility(View.VISIBLE); tLatSep1.setText("°"); tLonSep1.setText("°"); tLatSep2.setText("'"); tLonSep2.setText("'"); tLatSep3.setText("."); tLonSep3.setText("."); eLatDeg.setText(addZeros(latDeg, 2)); eLatMin.setText(addZeros(latMin, 2)); eLatSec.setText(addZeros(latSec, 2)); eLatSub.setText(addZeros(latSecFrac, 3)); eLonDeg.setText(addZeros(lonDeg, 3)); eLonMin.setText(addZeros(lonMin, 2)); eLonSec.setText(addZeros(lonSec, 2)); eLonSub.setText(addZeros(lonSecFrac, 3)); break; } } private static String addZeros(final int value, final int len) { final String n = Integer.toString(value); return StringUtils.repeat('0', Math.max(0, len - n.length())) + n; } private class ButtonClickListener implements View.OnClickListener { @Override public void onClick(View v) { Button e = (Button) v; CharSequence text = e.getText(); if (StringUtils.isBlank(text)) { return; } switch (text.charAt(0)) { case 'N': e.setText("S"); break; case 'S': e.setText("N"); break; case 'E': e.setText("W"); break; case 'W': e.setText("E"); break; } calc(true); } } private class TextChanged implements TextWatcher { private EditText editText; public TextChanged(EditText editText) { this.editText = editText; } @Override public void afterTextChanged(Editable s) { /* * Max lengths, depending on currentFormat * * formatPlain = disabled * DEG MIN SEC SUB * formatDeg 2/3 5 - - * formatMin 2/3 2 3 - * formatSec 2/3 2 2 3 */ if (currentFormat == coordInputFormatEnum.Plain) return; int maxLength = 2; if (editText == eLonDeg || editText == eLatSub || editText == eLonSub) { maxLength = 3; } if ((editText == eLatMin || editText == eLonMin) && currentFormat == coordInputFormatEnum.Deg) { maxLength = 5; } if ((editText == eLatSec || editText == eLonSec) && currentFormat == coordInputFormatEnum.Min) { maxLength = 3; } if (s.length() == maxLength) { if (editText == eLatDeg) eLatMin.requestFocus(); else if (editText == eLatMin) if (eLatSec.getVisibility() == View.GONE) eLonDeg.requestFocus(); else eLatSec.requestFocus(); else if (editText == eLatSec) if (eLatSub.getVisibility() == View.GONE) eLonDeg.requestFocus(); else eLatSub.requestFocus(); else if (editText == eLatSub) eLonDeg.requestFocus(); else if (editText == eLonDeg) eLonMin.requestFocus(); else if (editText == eLonMin) if (eLonSec.getVisibility() == View.GONE) eLatDeg.requestFocus(); else eLonSec.requestFocus(); else if (editText == eLonSec) if (eLonSub.getVisibility() == View.GONE) eLatDeg.requestFocus(); else eLonSub.requestFocus(); else if (editText == eLonSub) eLatDeg.requestFocus(); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } } private boolean calc(final boolean signalError) { if (currentFormat == coordInputFormatEnum.Plain) { try { gp = new Geopoint(eLat.getText().toString(), eLon.getText().toString()); } catch (ParseException e) { if (signalError) { context.showToast(context.getResources().getString(R.string.err_parse_lat_lon)); } return false; } catch (MalformedCoordinateException e) { if (signalError) { context.showToast(context.getResources().getString(R.string.err_invalid_lat_lon)); } return false; } return true; } int latDeg = 0, latMin = 0, latSec = 0; int lonDeg = 0, lonMin = 0, lonSec = 0; Double latDegFrac = 0.0, latMinFrac = 0.0, latSecFrac = 0.0; Double lonDegFrac = 0.0, lonMinFrac = 0.0, lonSecFrac = 0.0; try { latDeg = Integer.parseInt(eLatDeg.getText().toString()); lonDeg = Integer.parseInt(eLonDeg.getText().toString()); latDegFrac = Double.parseDouble("0." + eLatMin.getText().toString()); lonDegFrac = Double.parseDouble("0." + eLonMin.getText().toString()); latMin = Integer.parseInt(eLatMin.getText().toString()); lonMin = Integer.parseInt(eLonMin.getText().toString()); latMinFrac = Double.parseDouble("0." + eLatSec.getText().toString()); lonMinFrac = Double.parseDouble("0." + eLonSec.getText().toString()); latSec = Integer.parseInt(eLatSec.getText().toString()); lonSec = Integer.parseInt(eLonSec.getText().toString()); latSecFrac = Double.parseDouble("0." + eLatSub.getText().toString()); lonSecFrac = Double.parseDouble("0." + eLonSub.getText().toString()); } catch (NumberFormatException e) { } double latitude = 0.0; double longitude = 0.0; switch (currentFormat) { case Deg: latitude = latDeg + latDegFrac; longitude = lonDeg + lonDegFrac; break; case Min: latitude = latDeg + latMin / 60.0 + latMinFrac / 60.0; longitude = lonDeg + lonMin / 60.0 + lonMinFrac / 60.0; break; case Sec: latitude = latDeg + latMin / 60.0 + latSec / 60.0 / 60.0 + latSecFrac / 60.0 / 60.0; longitude = lonDeg + lonMin / 60.0 + lonSec / 60.0 / 60.0 + lonSecFrac / 60.0 / 60.0; break; case Plain: // This case has been handled above } latitude *= (bLat.getText().toString().equalsIgnoreCase("S") ? -1 : 1); longitude *= (bLon.getText().toString().equalsIgnoreCase("W") ? -1 : 1); try { gp = new Geopoint(latitude, longitude); } catch (MalformedCoordinateException e) { if (signalError) { context.showToast(context.getResources().getString(R.string.err_invalid_lat_lon)); } return false; } return true; } private class CoordinateFormatListener implements OnItemSelectedListener { @Override public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { // Ignore first call, which comes from onCreate() if (currentFormat != null) { // Start new format with an acceptable value: either the current one // entered by the user, else our current coordinates, else (0,0). if (!calc(false)) { if (geo != null && geo.coordsNow != null) { gp = geo.coordsNow; } else { gp = new Geopoint(0, 0); } } } currentFormat = coordInputFormatEnum.fromInt(pos); settings.setCoordInputFormat(currentFormat); updateGUI(); } @Override public void onNothingSelected(AdapterView<?> arg0) { } } private class CurrentListener implements View.OnClickListener { @Override public void onClick(View v) { if (geo == null || geo.coordsNow == null) { context.showToast(context.getResources().getString(R.string.err_point_unknown_position)); return; } gp = geo.coordsNow; updateGUI(); } } private class InputDoneListener implements View.OnClickListener { @Override public void onClick(View v) { if (!calc(true)) return; if (gp != null) cuListener.update(gp); dismiss(); } } public void setOnCoordinateUpdate(CoordinateUpdate cu) { cuListener = cu; } public interface CoordinateUpdate { public void update(final Geopoint gp); } }
true
true
private void updateGUI() { if (gp == null) return; Double lat = 0.0; if (gp.getLatitude() < 0) { bLat.setText("S"); } else { bLat.setText("N"); } lat = Math.abs(gp.getLatitude()); Double lon = 0.0; if (gp.getLongitude() < 0) { bLon.setText("W"); } else { bLon.setText("E"); } lon = Math.abs(gp.getLongitude()); int latDeg = (int) Math.floor(lat); int latDegFrac = (int) Math.round((lat - latDeg) * 100000); int latMin = (int) Math.floor((lat - latDeg) * 60); int latMinFrac = (int) Math.round(((lat - latDeg) * 60 - latMin) * 1000); int latSec = (int) Math.floor(((lat - latDeg) * 60 - latMin) * 60); int latSecFrac = (int) Math.round((((lat - latDeg) * 60 - latMin) * 60 - latSec) * 1000); int lonDeg = (int) Math.floor(lon); int lonDegFrac = (int) Math.round((lon - lonDeg) * 100000); int lonMin = (int) Math.floor((lon - lonDeg) * 60); int lonMinFrac = (int) Math.round(((lon - lonDeg) * 60 - lonMin) * 1000); int lonSec = (int) Math.floor(((lon - lonDeg) * 60 - lonMin) * 60); int lonSecFrac = (int) Math.round((((lon - lonDeg) * 60 - lonMin) * 60 - lonSec) * 1000); switch (currentFormat) { case Plain: findViewById(R.id.coordTable).setVisibility(View.GONE); eLat.setVisibility(View.VISIBLE); eLon.setVisibility(View.VISIBLE); eLat.setText(gp.format(GeopointFormatter.Format.LAT_DECMINUTE)); eLon.setText(gp.format(GeopointFormatter.Format.LON_DECMINUTE)); break; case Deg: // DDD.DDDDD° findViewById(R.id.coordTable).setVisibility(View.VISIBLE); eLat.setVisibility(View.GONE); eLon.setVisibility(View.GONE); eLatSec.setVisibility(View.GONE); eLonSec.setVisibility(View.GONE); tLatSep3.setVisibility(View.GONE); tLonSep3.setVisibility(View.GONE); eLatSub.setVisibility(View.GONE); eLonSub.setVisibility(View.GONE); tLatSep1.setText("."); tLonSep1.setText("."); tLatSep2.setText("°"); tLonSep2.setText("°"); eLatDeg.setText(addZeros(latDeg, 2)); eLatMin.setText(addZeros(latDegFrac, 5)); eLonDeg.setText(addZeros(latDeg, 3)); eLonMin.setText(addZeros(lonDegFrac, 5)); break; case Min: // DDD° MM.MMM findViewById(R.id.coordTable).setVisibility(View.VISIBLE); eLat.setVisibility(View.GONE); eLon.setVisibility(View.GONE); eLatSec.setVisibility(View.VISIBLE); eLonSec.setVisibility(View.VISIBLE); tLatSep3.setVisibility(View.VISIBLE); tLonSep3.setVisibility(View.VISIBLE); eLatSub.setVisibility(View.GONE); eLonSub.setVisibility(View.GONE); tLatSep1.setText("°"); tLonSep1.setText("°"); tLatSep2.setText("."); tLonSep2.setText("."); tLatSep3.setText("'"); tLonSep3.setText("'"); eLatDeg.setText(addZeros(latDeg, 2)); eLatMin.setText(addZeros(latMin, 2)); eLatSec.setText(addZeros(latMinFrac, 3)); eLonDeg.setText(addZeros(lonDeg, 3)); eLonMin.setText(addZeros(lonMin, 2)); eLonSec.setText(addZeros(lonMinFrac, 3)); break; case Sec: // DDD° MM SS.SSS findViewById(R.id.coordTable).setVisibility(View.VISIBLE); eLat.setVisibility(View.GONE); eLon.setVisibility(View.GONE); eLatSec.setVisibility(View.VISIBLE); eLonSec.setVisibility(View.VISIBLE); tLatSep3.setVisibility(View.VISIBLE); tLonSep3.setVisibility(View.VISIBLE); eLatSub.setVisibility(View.VISIBLE); eLonSub.setVisibility(View.VISIBLE); tLatSep1.setText("°"); tLonSep1.setText("°"); tLatSep2.setText("'"); tLonSep2.setText("'"); tLatSep3.setText("."); tLonSep3.setText("."); eLatDeg.setText(addZeros(latDeg, 2)); eLatMin.setText(addZeros(latMin, 2)); eLatSec.setText(addZeros(latSec, 2)); eLatSub.setText(addZeros(latSecFrac, 3)); eLonDeg.setText(addZeros(lonDeg, 3)); eLonMin.setText(addZeros(lonMin, 2)); eLonSec.setText(addZeros(lonSec, 2)); eLonSub.setText(addZeros(lonSecFrac, 3)); break; } }
private void updateGUI() { if (gp == null) return; Double lat = 0.0; if (gp.getLatitude() < 0) { bLat.setText("S"); } else { bLat.setText("N"); } lat = Math.abs(gp.getLatitude()); Double lon = 0.0; if (gp.getLongitude() < 0) { bLon.setText("W"); } else { bLon.setText("E"); } lon = Math.abs(gp.getLongitude()); int latDeg = (int) Math.floor(lat); int latDegFrac = (int) Math.round((lat - latDeg) * 100000); int latMin = (int) Math.floor((lat - latDeg) * 60); int latMinFrac = (int) Math.round(((lat - latDeg) * 60 - latMin) * 1000); int latSec = (int) Math.floor(((lat - latDeg) * 60 - latMin) * 60); int latSecFrac = (int) Math.round((((lat - latDeg) * 60 - latMin) * 60 - latSec) * 1000); int lonDeg = (int) Math.floor(lon); int lonDegFrac = (int) Math.round((lon - lonDeg) * 100000); int lonMin = (int) Math.floor((lon - lonDeg) * 60); int lonMinFrac = (int) Math.round(((lon - lonDeg) * 60 - lonMin) * 1000); int lonSec = (int) Math.floor(((lon - lonDeg) * 60 - lonMin) * 60); int lonSecFrac = (int) Math.round((((lon - lonDeg) * 60 - lonMin) * 60 - lonSec) * 1000); switch (currentFormat) { case Plain: findViewById(R.id.coordTable).setVisibility(View.GONE); eLat.setVisibility(View.VISIBLE); eLon.setVisibility(View.VISIBLE); eLat.setText(gp.format(GeopointFormatter.Format.LAT_DECMINUTE)); eLon.setText(gp.format(GeopointFormatter.Format.LON_DECMINUTE)); break; case Deg: // DDD.DDDDD° findViewById(R.id.coordTable).setVisibility(View.VISIBLE); eLat.setVisibility(View.GONE); eLon.setVisibility(View.GONE); eLatSec.setVisibility(View.GONE); eLonSec.setVisibility(View.GONE); tLatSep3.setVisibility(View.GONE); tLonSep3.setVisibility(View.GONE); eLatSub.setVisibility(View.GONE); eLonSub.setVisibility(View.GONE); tLatSep1.setText("."); tLonSep1.setText("."); tLatSep2.setText("°"); tLonSep2.setText("°"); eLatDeg.setText(addZeros(latDeg, 2)); eLatMin.setText(addZeros(latDegFrac, 5)); eLonDeg.setText(addZeros(lonDeg, 3)); eLonMin.setText(addZeros(lonDegFrac, 5)); break; case Min: // DDD° MM.MMM findViewById(R.id.coordTable).setVisibility(View.VISIBLE); eLat.setVisibility(View.GONE); eLon.setVisibility(View.GONE); eLatSec.setVisibility(View.VISIBLE); eLonSec.setVisibility(View.VISIBLE); tLatSep3.setVisibility(View.VISIBLE); tLonSep3.setVisibility(View.VISIBLE); eLatSub.setVisibility(View.GONE); eLonSub.setVisibility(View.GONE); tLatSep1.setText("°"); tLonSep1.setText("°"); tLatSep2.setText("."); tLonSep2.setText("."); tLatSep3.setText("'"); tLonSep3.setText("'"); eLatDeg.setText(addZeros(latDeg, 2)); eLatMin.setText(addZeros(latMin, 2)); eLatSec.setText(addZeros(latMinFrac, 3)); eLonDeg.setText(addZeros(lonDeg, 3)); eLonMin.setText(addZeros(lonMin, 2)); eLonSec.setText(addZeros(lonMinFrac, 3)); break; case Sec: // DDD° MM SS.SSS findViewById(R.id.coordTable).setVisibility(View.VISIBLE); eLat.setVisibility(View.GONE); eLon.setVisibility(View.GONE); eLatSec.setVisibility(View.VISIBLE); eLonSec.setVisibility(View.VISIBLE); tLatSep3.setVisibility(View.VISIBLE); tLonSep3.setVisibility(View.VISIBLE); eLatSub.setVisibility(View.VISIBLE); eLonSub.setVisibility(View.VISIBLE); tLatSep1.setText("°"); tLonSep1.setText("°"); tLatSep2.setText("'"); tLonSep2.setText("'"); tLatSep3.setText("."); tLonSep3.setText("."); eLatDeg.setText(addZeros(latDeg, 2)); eLatMin.setText(addZeros(latMin, 2)); eLatSec.setText(addZeros(latSec, 2)); eLatSub.setText(addZeros(latSecFrac, 3)); eLonDeg.setText(addZeros(lonDeg, 3)); eLonMin.setText(addZeros(lonMin, 2)); eLonSec.setText(addZeros(lonSec, 2)); eLonSub.setText(addZeros(lonSecFrac, 3)); break; } }
diff --git a/src/org/openid4java/message/AuthSuccess.java b/src/org/openid4java/message/AuthSuccess.java index c9f6dd8..2f128c6 100644 --- a/src/org/openid4java/message/AuthSuccess.java +++ b/src/org/openid4java/message/AuthSuccess.java @@ -1,592 +1,592 @@ /* * Copyright 2006-2008 Sxip Identity Corporation */ package org.openid4java.message; import org.openid4java.discovery.DiscoveryException; import org.openid4java.util.InternetDateFormat; import org.openid4java.association.Association; import org.openid4java.association.AssociationException; import org.openid4java.OpenIDException; import java.util.*; import java.text.ParseException; import java.net.URL; import java.net.MalformedURLException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * @author Marius Scurtescu, Johnny Bufu */ public class AuthSuccess extends Message { private static Log _log = LogFactory.getLog(AuthSuccess.class); private static final boolean DEBUG = _log.isDebugEnabled(); protected final static List requiredFields = Arrays.asList( new String[] { "openid.mode", "openid.return_to", "openid.assoc_handle", "openid.signed", "openid.sig" }); protected final static List optionalFields = Arrays.asList( new String[] { "openid.ns", "openid.op_endpoint", "openid.claimed_id", "openid.identity", "openid.response_nonce", "openid.invalidate_handle" }); // required signed list in OpenID 1.x protected final static String signRequired1 = "return_to,identity"; // required signed list in OpenID 2.0 with claimed identifier protected final static String signRequired2 = "op_endpoint,claimed_id,identity,return_to,response_nonce,assoc_handle"; // required signed list in OpenID 2.0 with no claimed identifier protected final static String signRequired3 = "op_endpoint,return_to,response_nonce,assoc_handle"; protected List _signFields = new ArrayList(); protected List _signExtensions = new ArrayList(); protected AuthSuccess(String opEndpoint, String claimedId, String delegate, boolean compatibility, String returnTo, String nonce, String invalidateHandle, Association assoc, boolean signNow) throws AssociationException { if (! compatibility) { set("openid.ns", OPENID2_NS); setOpEndpoint(opEndpoint); setClaimed(claimedId); setNonce(nonce); } set("openid.mode", MODE_IDRES); setIdentity(delegate); setReturnTo(returnTo); if (invalidateHandle != null) setInvalidateHandle(invalidateHandle); setHandle(assoc.getHandle()); buildSignedList(); setSignature(signNow ? assoc.sign(getSignedText()) : ""); } protected AuthSuccess(ParameterList params) { super(params); } public static AuthSuccess createAuthSuccess( String opEndpoint, String claimedId, String delegate, boolean compatibility, String returnTo, String nonce, String invalidateHandle, Association assoc, boolean signNow) throws MessageException, AssociationException { AuthSuccess resp = new AuthSuccess(opEndpoint, claimedId, delegate, compatibility, returnTo, nonce, invalidateHandle, assoc, signNow); resp.validate(); if (DEBUG) _log.debug("Created positive auth response:\n" + resp.keyValueFormEncoding()); return resp; } public static AuthSuccess createAuthSuccess(ParameterList params) throws MessageException { AuthSuccess resp = new AuthSuccess(params); resp.validate(); if (DEBUG) _log.debug("Created positive auth response:\n" + resp.keyValueFormEncoding()); return resp; } public List getRequiredFields() { return requiredFields; } public boolean isVersion2() { return hasParameter("openid.ns") && OPENID2_NS.equals(getParameterValue("openid.ns")); } public void setMode(String mode) throws MessageException { if (! mode.equals(MODE_IDRES) && ! mode.equals(MODE_CANCEL)) throw new MessageException("Unknown authentication mode: " + mode); set("openid.mode", mode); } public String getMode() { return getParameterValue("openid.mode"); } public void setOpEndpoint(String opEndpoint) { set("openid.op_endpoint", opEndpoint); } public String getOpEndpoint() { return getParameterValue("openid.op_endpoint"); } public void setIdentity(String id) { set("openid.identity", id); } public String getIdentity() throws DiscoveryException { return getParameterValue("openid.identity"); } public void setClaimed(String claimed) { set("openid.claimed_id", claimed); } public String getClaimed() { return getParameterValue("openid.claimed_id"); } public void setReturnTo(String returnTo) { set("openid.return_to", returnTo); _destinationUrl = returnTo; } public String getReturnTo() { return getParameterValue("openid.return_to"); } public void setNonce(String nonce) { set("openid.response_nonce", nonce); } public String getNonce() { return getParameterValue("openid.response_nonce"); } public void setInvalidateHandle(String handle) { set("openid.invalidate_handle", handle); } public String getInvalidateHandle() { return getParameterValue("openid.invalidate_handle"); } public void setHandle(String handle) { set("openid.assoc_handle", handle); } public String getHandle() { return getParameterValue("openid.assoc_handle"); } /** * Builds the list of fields that will be signed. Three input sources are * considered for this: * <ul> * <li>fields required to be signed by the OpenID protocol</li> * <li>the user defined list of fields to be signed * {@link #setSignFields(String)}</li> * <li>fields belonging to extensions to be signed * {@link #setSignExtensions(String[])}</li> * </ul> * <p> * This method should be called after any field additions/deletions to/from * the message. */ public void buildSignedList() { StringBuffer toSign = ! isVersion2() ? new StringBuffer(signRequired1) : hasParameter("openid.identity") ? new StringBuffer(signRequired2) : new StringBuffer(signRequired3); List signList = new ArrayList(Arrays.asList(toSign.toString().split(","))); Iterator iter = _signFields.iterator(); while (iter.hasNext()) { String field = (String) iter.next(); if ( ! signList.contains(field) ) { toSign.append(",").append(field); signList.add(field); } } // build list of field prefixes belonging to extensions List extensionPrefixes = new ArrayList(); iter = _signExtensions.iterator(); while(iter.hasNext()) { String alias = getExtensionAlias((String) iter.next()); if (alias != null) { // openid.ns.<ext_alias> needs to be signed //String nsSign = "ns." + alias; //toSign.append(",").append(nsSign); //signList.add(nsSign); extensionPrefixes.add(alias); } } // add exension fields to the signed list iter = getParameters().iterator(); while(iter.hasNext()) { String paramName = ((Parameter) iter.next()).getKey(); if (! paramName.startsWith("openid.")) continue; String signName = paramName.substring(7); int dotIndex = signName.indexOf("."); if (dotIndex > 0 && extensionPrefixes.contains(signName.substring(0,dotIndex)) && ! signList.contains(signName) ) { toSign.append(",").append(signName); signList.add(signName); } } if (DEBUG) _log.debug("Setting fields to be signed: " + toSign); set("openid.signed", toSign.toString()); //todo: if signature is alread set, recompute it } /** * Sets the messages fields that will be signed, in addition to the ones * required by the protocol to be signed. The OpenID signature will * only be applied to OpenID fields, starting with the "openid." prefix. * * @param userSuppliedList Comma-separated list of fields to be signed, * without the "openid." prefix * @see #setSignExtensions(String[]) */ public void setSignFields(String userSuppliedList) { if (userSuppliedList != null) { _signFields = Arrays.asList(userSuppliedList.split(",")); buildSignedList(); } } /** * Sets the list of messages fields that will be signed, in addition to * the ones required by the protocol to be signed and any additional * fields already configured to be signed. The OpenID signature will * only be applied to OpenID fields, starting with the "openid." prefix. * Should be called <b>after</b> all relevant extension fields have been * added to the message. * * @param extensions Array of extension namespace URIs to be signed. * @see #setSignFields(String) #setSignExtension */ public void setSignExtensions(String[] extensions) { if (extensions != null) { _signExtensions = new ArrayList(Arrays.asList(extensions)); buildSignedList(); } } /** * Adds the list of messages fields that will be signed, in addition to * the ones required by the protocol to be signed and any additional * fields already configured to be signed. The OpenID signature will * only be applied to OpenID fields, starting with the "openid." prefix. * Should be called <b>after</b> all relevant extension fields have been * added to the message. * * @param extensionNamespace Extension namespace URI to be signed. * @see #setSignFields(String) #setSignExtensions */ public void addSignExtension(String extensionNamespace) { if (! _signExtensions.contains(extensionNamespace)) { _signExtensions.add(extensionNamespace); buildSignedList(); } } public List getSignExtensions() { return _signExtensions; } public void setSignature(String sig) { set("openid.sig", sig); if(DEBUG) _log.debug("Added signature: " + sig); } public String getSignature() { return getParameterValue("openid.sig"); } public String getSignList() { return getParameterValue("openid.signed"); } /** * Return the text on which the signature is applied. */ public String getSignedText() { StringBuffer signedText = new StringBuffer(""); String[] signedParams = getParameterValue("openid.signed").split(","); for (int i = 0; i < signedParams.length; i++) { signedText.append(signedParams[i]); signedText.append(':'); String value = getParameterValue("openid." + signedParams[i]); if (value != null) signedText.append(value); signedText.append('\n'); } return signedText.toString(); } public void validate() throws MessageException { super.validate(); boolean compatibility = ! isVersion2(); if ( ! compatibility && ! hasParameter("openid.op_endpoint")) { throw new MessageException( "openid.op_endpoint is required in OpenID auth responses", OpenIDException.AUTH_ERROR); } try { // return_to must be a valid URL, if present if (getReturnTo() != null) new URL(getReturnTo()); } catch (MalformedURLException e) { throw new MessageException( "Invalid return_to: " + getReturnTo(), OpenIDException.AUTH_ERROR, e); } try { // op_endpoint must be a valid URL, if present - if (getOpEndpoint() != null) + if (isVersion2() && getOpEndpoint() != null) new URL(getOpEndpoint()); } catch (MalformedURLException e) { throw new MessageException( "Invalid op_endpoint: " + getOpEndpoint(), OpenIDException.AUTH_ERROR, e); } if (! MODE_IDRES.equals(getMode())) { throw new MessageException( "Invalid openid.mode value in auth response: " + getMode(), OpenIDException.AUTH_ERROR); } // figure out if 'identity' is optional if ( ! hasParameter("openid.identity") ) { // not optional in v1 if (compatibility) { throw new MessageException( "openid.identity is required in OpenID1 auth responses", OpenIDException.AUTH_ERROR); } boolean hasAuthExt = false; Iterator iter = getExtensions().iterator(); while (iter.hasNext()) { String typeUri = iter.next().toString(); try { MessageExtension extension = getExtension(typeUri); if (extension.providesIdentifier()) { hasAuthExt = true; break; } } catch (MessageException ignore) { // do nothing } } if (! hasAuthExt) { // no extension provides authentication sevices, invalid message throw new MessageException( "no identifier specified in auth request", OpenIDException.AUTH_ERROR); } // claimed_id must be present if and only if identity is present if ( hasParameter("openid.claimed_id") ) { throw new MessageException( "openid.claimed_id must be present if and only if " + "openid.identity is present.", OpenIDException.AUTH_ERROR); } } else if ( ! compatibility && ! hasParameter("openid.claimed_id") ) { throw new MessageException( "openid.clamied_id must be present in OpenID2 auth responses", OpenIDException.AUTH_ERROR); } // nonce optional or not? String nonce = getNonce(); if ( !compatibility ) { if (nonce == null) { throw new MessageException( "openid.response_nonce is required in OpenID2 auth responses", OpenIDException.AUTH_ERROR); } // nonce format InternetDateFormat _dateFormat = new InternetDateFormat(); try { _dateFormat.parse(nonce.substring(0, 20)); } catch (ParseException e) { throw new MessageException( "Error parsing nonce in auth response.", OpenIDException.AUTH_ERROR, e); } if (nonce.length() >255) { throw new MessageException( "nonce length must not exceed 255 characters", OpenIDException.AUTH_ERROR); } } else if (nonce != null) { _log.warn("openid.response_nonce present in OpenID1 auth response"); // return false; } List signedFields = Arrays.asList( getParameterValue("openid.signed").split(",")); // return_to must be signed if (!signedFields.contains("return_to")) { throw new MessageException("return_to must be signed", OpenIDException.AUTH_ERROR); } // either compatibility mode or nonce signed if ( compatibility == signedFields.contains("response_nonce") ) { _log.warn("response_nonce must be present and signed only in OpenID2 auth responses"); // return false; } // either compatibility mode or op_endpoint signed if ( compatibility == signedFields.contains("op_endpoint") ) { _log.warn("op_endpoint must be present and signed only in OpenID2 auth responses"); // return false; } // assoc_handle must be signed in v2 if ( ! compatibility && ! signedFields.contains("assoc_handle") ) { throw new MessageException( "assoc_handle must be signed in OpenID2 auth responses", OpenIDException.AUTH_ERROR); } // 'identity' and 'claimed_id' must be signed if present if (hasParameter("openid.identity") && ! signedFields.contains("identity")) { throw new MessageException( "openid.identity must be signed if present", OpenIDException.AUTH_ERROR); } if (hasParameter("openid.claimed_id") && ! signedFields.contains("claimed_id")) { throw new MessageException( "openid.claimed_id must be signed if present", OpenIDException.AUTH_ERROR); } } }
true
true
public void validate() throws MessageException { super.validate(); boolean compatibility = ! isVersion2(); if ( ! compatibility && ! hasParameter("openid.op_endpoint")) { throw new MessageException( "openid.op_endpoint is required in OpenID auth responses", OpenIDException.AUTH_ERROR); } try { // return_to must be a valid URL, if present if (getReturnTo() != null) new URL(getReturnTo()); } catch (MalformedURLException e) { throw new MessageException( "Invalid return_to: " + getReturnTo(), OpenIDException.AUTH_ERROR, e); } try { // op_endpoint must be a valid URL, if present if (getOpEndpoint() != null) new URL(getOpEndpoint()); } catch (MalformedURLException e) { throw new MessageException( "Invalid op_endpoint: " + getOpEndpoint(), OpenIDException.AUTH_ERROR, e); } if (! MODE_IDRES.equals(getMode())) { throw new MessageException( "Invalid openid.mode value in auth response: " + getMode(), OpenIDException.AUTH_ERROR); } // figure out if 'identity' is optional if ( ! hasParameter("openid.identity") ) { // not optional in v1 if (compatibility) { throw new MessageException( "openid.identity is required in OpenID1 auth responses", OpenIDException.AUTH_ERROR); } boolean hasAuthExt = false; Iterator iter = getExtensions().iterator(); while (iter.hasNext()) { String typeUri = iter.next().toString(); try { MessageExtension extension = getExtension(typeUri); if (extension.providesIdentifier()) { hasAuthExt = true; break; } } catch (MessageException ignore) { // do nothing } } if (! hasAuthExt) { // no extension provides authentication sevices, invalid message throw new MessageException( "no identifier specified in auth request", OpenIDException.AUTH_ERROR); } // claimed_id must be present if and only if identity is present if ( hasParameter("openid.claimed_id") ) { throw new MessageException( "openid.claimed_id must be present if and only if " + "openid.identity is present.", OpenIDException.AUTH_ERROR); } } else if ( ! compatibility && ! hasParameter("openid.claimed_id") ) { throw new MessageException( "openid.clamied_id must be present in OpenID2 auth responses", OpenIDException.AUTH_ERROR); } // nonce optional or not? String nonce = getNonce(); if ( !compatibility ) { if (nonce == null) { throw new MessageException( "openid.response_nonce is required in OpenID2 auth responses", OpenIDException.AUTH_ERROR); } // nonce format InternetDateFormat _dateFormat = new InternetDateFormat(); try { _dateFormat.parse(nonce.substring(0, 20)); } catch (ParseException e) { throw new MessageException( "Error parsing nonce in auth response.", OpenIDException.AUTH_ERROR, e); } if (nonce.length() >255) { throw new MessageException( "nonce length must not exceed 255 characters", OpenIDException.AUTH_ERROR); } } else if (nonce != null) { _log.warn("openid.response_nonce present in OpenID1 auth response"); // return false; } List signedFields = Arrays.asList( getParameterValue("openid.signed").split(",")); // return_to must be signed if (!signedFields.contains("return_to")) { throw new MessageException("return_to must be signed", OpenIDException.AUTH_ERROR); } // either compatibility mode or nonce signed if ( compatibility == signedFields.contains("response_nonce") ) { _log.warn("response_nonce must be present and signed only in OpenID2 auth responses"); // return false; } // either compatibility mode or op_endpoint signed if ( compatibility == signedFields.contains("op_endpoint") ) { _log.warn("op_endpoint must be present and signed only in OpenID2 auth responses"); // return false; } // assoc_handle must be signed in v2 if ( ! compatibility && ! signedFields.contains("assoc_handle") ) { throw new MessageException( "assoc_handle must be signed in OpenID2 auth responses", OpenIDException.AUTH_ERROR); } // 'identity' and 'claimed_id' must be signed if present if (hasParameter("openid.identity") && ! signedFields.contains("identity")) { throw new MessageException( "openid.identity must be signed if present", OpenIDException.AUTH_ERROR); } if (hasParameter("openid.claimed_id") && ! signedFields.contains("claimed_id")) { throw new MessageException( "openid.claimed_id must be signed if present", OpenIDException.AUTH_ERROR); } }
public void validate() throws MessageException { super.validate(); boolean compatibility = ! isVersion2(); if ( ! compatibility && ! hasParameter("openid.op_endpoint")) { throw new MessageException( "openid.op_endpoint is required in OpenID auth responses", OpenIDException.AUTH_ERROR); } try { // return_to must be a valid URL, if present if (getReturnTo() != null) new URL(getReturnTo()); } catch (MalformedURLException e) { throw new MessageException( "Invalid return_to: " + getReturnTo(), OpenIDException.AUTH_ERROR, e); } try { // op_endpoint must be a valid URL, if present if (isVersion2() && getOpEndpoint() != null) new URL(getOpEndpoint()); } catch (MalformedURLException e) { throw new MessageException( "Invalid op_endpoint: " + getOpEndpoint(), OpenIDException.AUTH_ERROR, e); } if (! MODE_IDRES.equals(getMode())) { throw new MessageException( "Invalid openid.mode value in auth response: " + getMode(), OpenIDException.AUTH_ERROR); } // figure out if 'identity' is optional if ( ! hasParameter("openid.identity") ) { // not optional in v1 if (compatibility) { throw new MessageException( "openid.identity is required in OpenID1 auth responses", OpenIDException.AUTH_ERROR); } boolean hasAuthExt = false; Iterator iter = getExtensions().iterator(); while (iter.hasNext()) { String typeUri = iter.next().toString(); try { MessageExtension extension = getExtension(typeUri); if (extension.providesIdentifier()) { hasAuthExt = true; break; } } catch (MessageException ignore) { // do nothing } } if (! hasAuthExt) { // no extension provides authentication sevices, invalid message throw new MessageException( "no identifier specified in auth request", OpenIDException.AUTH_ERROR); } // claimed_id must be present if and only if identity is present if ( hasParameter("openid.claimed_id") ) { throw new MessageException( "openid.claimed_id must be present if and only if " + "openid.identity is present.", OpenIDException.AUTH_ERROR); } } else if ( ! compatibility && ! hasParameter("openid.claimed_id") ) { throw new MessageException( "openid.clamied_id must be present in OpenID2 auth responses", OpenIDException.AUTH_ERROR); } // nonce optional or not? String nonce = getNonce(); if ( !compatibility ) { if (nonce == null) { throw new MessageException( "openid.response_nonce is required in OpenID2 auth responses", OpenIDException.AUTH_ERROR); } // nonce format InternetDateFormat _dateFormat = new InternetDateFormat(); try { _dateFormat.parse(nonce.substring(0, 20)); } catch (ParseException e) { throw new MessageException( "Error parsing nonce in auth response.", OpenIDException.AUTH_ERROR, e); } if (nonce.length() >255) { throw new MessageException( "nonce length must not exceed 255 characters", OpenIDException.AUTH_ERROR); } } else if (nonce != null) { _log.warn("openid.response_nonce present in OpenID1 auth response"); // return false; } List signedFields = Arrays.asList( getParameterValue("openid.signed").split(",")); // return_to must be signed if (!signedFields.contains("return_to")) { throw new MessageException("return_to must be signed", OpenIDException.AUTH_ERROR); } // either compatibility mode or nonce signed if ( compatibility == signedFields.contains("response_nonce") ) { _log.warn("response_nonce must be present and signed only in OpenID2 auth responses"); // return false; } // either compatibility mode or op_endpoint signed if ( compatibility == signedFields.contains("op_endpoint") ) { _log.warn("op_endpoint must be present and signed only in OpenID2 auth responses"); // return false; } // assoc_handle must be signed in v2 if ( ! compatibility && ! signedFields.contains("assoc_handle") ) { throw new MessageException( "assoc_handle must be signed in OpenID2 auth responses", OpenIDException.AUTH_ERROR); } // 'identity' and 'claimed_id' must be signed if present if (hasParameter("openid.identity") && ! signedFields.contains("identity")) { throw new MessageException( "openid.identity must be signed if present", OpenIDException.AUTH_ERROR); } if (hasParameter("openid.claimed_id") && ! signedFields.contains("claimed_id")) { throw new MessageException( "openid.claimed_id must be signed if present", OpenIDException.AUTH_ERROR); } }
diff --git a/src/main/java/net/h31ix/anticheat/manage/Backend.java b/src/main/java/net/h31ix/anticheat/manage/Backend.java index 63c880d..aa02e75 100644 --- a/src/main/java/net/h31ix/anticheat/manage/Backend.java +++ b/src/main/java/net/h31ix/anticheat/manage/Backend.java @@ -1,805 +1,804 @@ /* * AntiCheat for Bukkit. * Copyright (C) 2012 H31IX http://h31ix.net * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package net.h31ix.anticheat.manage; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.bukkit.ChatColor; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.event.player.PlayerToggleSprintEvent; public class Backend { private static final int ENTERED_EXTITED_TIME = 20; private static final int SNEAK_TIME = 5; private static final int TELEPORT_TIME = 50; private static final int EXIT_FLY_TIME = 40; private static final int INSTANT_BREAK_TIME = 100; private static final int JOIN_TIME = 40; private static final int DROPPED_ITEM_TIME = 2; private static final int DAMAGE_TIME = 50; private static final int KNOCKBACK_DAMAGE_TIME = 50; private static final int FASTBREAK_LIMIT = 3; private static final int FASTBREAK_TIMEMAX = 500; private static final int FASTBREAK_MAXVIOLATIONS = 2; private static final int FASTBREAK_MAXVIOLATIONS_CREATIVE = 3; private static final int FASTBREAK_MAXVIOLATIONTIME = 10000; private static final int FASTPLACE_ZEROLIMIT = 3; private static final int FASTPLACE_TIMEMAX = 100; private static final int FASTPLACE_MAXVIOLATIONS = 2; private static final int FASTPLACE_MAXVIOLATIONS_CREATIVE = 3; private static final int FASTPLACE_MAXVIOLATIONTIME = 10000; private static final int BLOCK_PUNCH_MIN = 5; private static final int CHAT_WARN_LEVEL = 7; private static final int CHAT_KICK_LEVEL = 10; private static final int CHAT_BAN_LEVEL = 3; private static final int FLIGHT_LIMIT = 4; private static final int Y_MAXVIOLATIONS = 1; private static final int Y_MAXVIOTIME = 5000; private static final int NOFALL_LIMIT = 5; private static final int SPRINT_FOOD_MIN = 6; private static final int EAT_MIN = 20; private static final int HEAL_MIN = 35; private static final int ANIMATION_MIN = 60; private static final int CHAT_MIN = 100; private static final int BOW_MIN = 2; private static final int SPRINT_MIN = 2; private static final int BLOCK_BREAK_MIN = 1; private static final long BLOCK_PLACE_MIN = 1/3; private static final double BLOCK_MAX_DISTANCE = 6.0; private static final double ENTITY_MAX_DISTANCE = 5.5; private static final double LADDER_Y_MAX = 0.11761; private static final double LADDER_Y_MIN = 0.11759; private static final double Y_SPEED_MAX = 0.5; private static final double Y_MAXDIFF = 5; private static final double Y_TIME = 1000; private static final double XZ_SPEED_MAX = 0.4; private static final double XZ_SPEED_MAX_SPRINT = 0.65; private static final double XZ_SPEED_MAX_FLY = 0.56; private static final double XZ_SPEED_MAX_SNEAK = 0.2; private static final double XZ_SPEED_MAX_WATER = 0.19; private static final double XZ_SPEED_MAX_WATER_SPRINT = 0.3; private static final int FLY_LOOP = 5; private AnticheatManager micromanage = null; private List<String> droppedItem = new ArrayList<String>(); private List<String> animated = new ArrayList<String>(); private List<String> movingExempt = new ArrayList<String>(); private List<String> brokenBlock = new ArrayList<String>(); private List<String> placedBlock = new ArrayList<String>(); private List<String> bowWindUp = new ArrayList<String>(); private List<String> startEat = new ArrayList<String>(); private List<String> healed = new ArrayList<String>(); private List<String> sprinted = new ArrayList<String>(); private List<String> isInWater = new ArrayList<String>(); private List<String> isInWaterCache = new ArrayList<String>(); private List<String> instantBreakExempt = new ArrayList<String>(); private Map<String,String> oldMessage = new HashMap<String,String>(); private Map<String,String> lastMessage = new HashMap<String,String>(); private Map<String,Integer> flightViolation = new HashMap<String,Integer>(); private Map<String,Integer> chatLevel = new HashMap<String,Integer>(); private Map<String,Integer> chatKicks = new HashMap<String,Integer>(); private Map<String,Integer> nofallViolation = new HashMap<String,Integer>(); private Map<String,Integer> fastBreakViolation = new HashMap<String,Integer>(); private Map<String,Integer> yAxisViolations = new HashMap<String,Integer>(); private Map<String,Long> yAxisLastViolation = new HashMap<String,Long>(); private Map<String,Double> lastYcoord = new HashMap<String,Double>(); private Map<String,Long> lastYtime = new HashMap<String,Long>(); private Map<String,Integer> blocksBroken = new HashMap<String,Integer>(); private Map<String,Long> lastBlockBroken = new HashMap<String,Long>(); private Map<String,Integer> fastPlaceViolation = new HashMap<String,Integer>(); private Map<String,Integer> lastZeroHitPlace = new HashMap<String,Integer>(); private Map<String,Long> lastBlockPlaced = new HashMap<String,Long>(); private Map<String,Long> lastBlockPlaceTime = new HashMap<String,Long>(); private Map<String,Integer> blockPunches = new HashMap<String,Integer>(); public Backend(AnticheatManager instance) { micromanage = instance; } public boolean checkLongReachBlock(double x,double y,double z) { return x >= BLOCK_MAX_DISTANCE || y > BLOCK_MAX_DISTANCE || z > BLOCK_MAX_DISTANCE; } public boolean checkLongReachDamage(double x,double y,double z) { return x >= ENTITY_MAX_DISTANCE || y > ENTITY_MAX_DISTANCE || z > ENTITY_MAX_DISTANCE; } public boolean checkSpider(Player player,double y) { if(y <= LADDER_Y_MAX && y >= LADDER_Y_MIN && player.getLocation().getBlock().getType() != Material.VINE && player.getLocation().getBlock().getType() != Material.LADDER) { return true; } return false; } public boolean checkYSpeed(Player player,double y) { if(/*!player.isFlying() &&*/ player.getVehicle() == null && y > Y_SPEED_MAX) { return true; } return false; } public boolean checkNoFall(Player player, double y) { String name = player.getName(); if(player.getGameMode() != GameMode.CREATIVE && player.getVehicle() == null && !isMovingExempt(player)) { if(player.getFallDistance() == 0) { if(nofallViolation.get(name) == null) { nofallViolation.put(name,1); } else { nofallViolation.put(name,nofallViolation.get(player.getName())+1); } if(nofallViolation.get(name) >= NOFALL_LIMIT) { nofallViolation.put(player.getName(),1); return true; } else { return false; } } else { nofallViolation.put(name,0); return false; } } return false; } public boolean checkXZSpeed(Player player,double x,double z) { if(!isSpeedExempt(player) && player.getVehicle() == null) { if(player.isFlying()) { return x > XZ_SPEED_MAX_FLY || z > XZ_SPEED_MAX_FLY; } if(!player.isSprinting()) { return x > XZ_SPEED_MAX || z > XZ_SPEED_MAX; } else { return x > XZ_SPEED_MAX_SPRINT || z > XZ_SPEED_MAX_SPRINT; } } else { return false; } } public boolean checkSneak(Player player,double x,double z) { if(player.isSneaking() && !player.isFlying() && !isMovingExempt(player)) { return x > XZ_SPEED_MAX_SNEAK || z > XZ_SPEED_MAX_SNEAK; } else { return false; } } public boolean checkSprint(PlayerToggleSprintEvent event) { Player player = event.getPlayer(); if(event.isSprinting()) { return player.getFoodLevel() <= SPRINT_FOOD_MIN && player.getGameMode() != GameMode.CREATIVE; } else { return false; } } public boolean checkWaterWalk(Player player, double x, double z) { Block block = player.getLocation().getBlock(); if(block.isLiquid() && player.getVehicle() == null) { if(isInWater.contains(player.getName())) { if(isInWaterCache.contains(player.getName())) { if(x > XZ_SPEED_MAX_WATER || z > XZ_SPEED_MAX_WATER && !Utilities.sprintFly(player) && player.getNearbyEntities(1, 1, 1).isEmpty()) { return true; } else if(x > XZ_SPEED_MAX_WATER_SPRINT || z > XZ_SPEED_MAX_WATER_SPRINT) { return true; } } else { isInWaterCache.add(player.getName()); return false; } } else { isInWater.add(player.getName()); return false; } } isInWater.remove(player.getName()); isInWaterCache.remove(player.getName()); return false; } public boolean checkYAxis(Player player, Distance distance) { //Arrow to the knee check if(distance.getYDifference() > 400) { //teleport. so just cancel. return false; } - //Arrow to the knee check - if(!player.isFlying()) + if(!isMovingExempt(player)) { double y1 = player.getLocation().getY(); String name = player.getName(); //Fix Y axis spam. if(!lastYcoord.containsKey(name) || !lastYtime.containsKey(name) || !yAxisLastViolation.containsKey(name) || !yAxisLastViolation.containsKey(name)) { lastYcoord.put(name, y1); yAxisViolations.put(name, 0); yAxisLastViolation.put(name, 0L); lastYtime.put(name, System.currentTimeMillis()); } else { if(y1 > lastYcoord.get(name) && yAxisViolations.get(name) > Y_MAXVIOLATIONS && (System.currentTimeMillis() - yAxisLastViolation.get(name)) < Y_MAXVIOTIME) { Location g = player.getLocation(); g.setY(lastYcoord.get(name)); player.sendMessage(ChatColor.RED + "[AntiCheat] Fly hacking on the y-axis detected. Please wait 5 seconds to prevent getting damage."); yAxisViolations.put(name, yAxisViolations.get(name)+1); yAxisLastViolation.put(name, System.currentTimeMillis()); if(g.getBlock().getTypeId() == 0) { player.teleport(g); } return true; } else { if(yAxisViolations.get(name) > Y_MAXVIOLATIONS && (System.currentTimeMillis() - yAxisLastViolation.get(name)) > Y_MAXVIOTIME) { yAxisViolations.put(name, 0); yAxisLastViolation.put(name, 0L); } } if((y1 - lastYcoord.get(name)) > Y_MAXDIFF && (System.currentTimeMillis() - lastYtime.get(name)) < Y_TIME) { Location g = player.getLocation(); g.setY(lastYcoord.get(name)); yAxisViolations.put(name, yAxisViolations.get(name)+1); yAxisLastViolation.put(name, System.currentTimeMillis()); if(g.getBlock().getTypeId() == 0) { player.teleport(g); } return true; } else { if((y1 - lastYcoord.get(name)) > Y_MAXDIFF + 1 || (System.currentTimeMillis() - lastYtime.get(name)) > Y_TIME) { lastYtime.put(name, System.currentTimeMillis()); lastYcoord.put(name, y1); } } } } //Fix Y axis spam return false; } public boolean checkFlight(Player player, Distance distance) { //Arrow to the knee check if(distance.getYDifference() > 400) { //teleport. so just cancel. return false; } //Arrow to the knee check double y1 = distance.fromY(); double y2 = distance.toY(); Block block = player.getLocation().getBlock().getRelative(BlockFace.DOWN); if(y1 == y2 && !isMovingExempt(player) && player.getVehicle() == null && player.getFallDistance() == 0 && !Utilities.isOnLilyPad(player)) { String name = player.getName(); if(Utilities.cantStandAt(block) && !Utilities.isOnLilyPad(player) && !Utilities.canStand(player.getLocation().getBlock())) { int violation = 1; if(!flightViolation.containsKey(name)) { flightViolation.put(name, violation); } else { violation = flightViolation.get(name)+1; flightViolation.put(name, violation); } if(violation >= FLIGHT_LIMIT) { flightViolation.put(name, 1); return true; } //Start Fly bypass patch. if(flightViolation.containsKey(name) && flightViolation.get(name) > 0) { for(int i=FLY_LOOP;i>0;i--) { Location newLocation = new Location(player.getWorld(), player.getLocation().getX(), player.getLocation().getY()-i, player.getLocation().getZ()); Block lower = newLocation.getBlock(); if(lower.getTypeId() == 0) { player.teleport(newLocation); break; } } } //End Fly bypass patch. } } return false; } public boolean checkSwing(Player player, Block block) { return !player.getInventory().getItemInHand().containsEnchantment(Enchantment.DIG_SPEED) && !Utilities.isInstantBreak(block.getType()) && !justAnimated(player); } public boolean checkFastBreak(Player player, Block block) { int violations = FASTBREAK_MAXVIOLATIONS; if(player.getGameMode() == GameMode.CREATIVE) { violations = FASTBREAK_MAXVIOLATIONS_CREATIVE; } String name = player.getName(); if(!player.getInventory().getItemInHand().containsEnchantment(Enchantment.DIG_SPEED) && !Utilities.isInstantBreak(block.getType()) && !isInstantBreakExempt(player) && !(player.getInventory().getItemInHand().getType() == Material.SHEARS && block.getType() == Material.LEAVES && player.getGameMode() != GameMode.CREATIVE)) { if(blockPunches.get(name) != null) { int i = blockPunches.get(name); if(i < BLOCK_PUNCH_MIN) { return true; } } if (!fastBreakViolation.containsKey(name)) { fastBreakViolation.put(name, 0); } else { Long math = System.currentTimeMillis() - lastBlockBroken.get(name); if(fastBreakViolation.get(name) > violations && math < FASTBREAK_MAXVIOLATIONTIME) { lastBlockBroken.put(name, System.currentTimeMillis()); player.sendMessage(ChatColor.RED + "[AntiCheat] Fastbreaking detected. Please wait 10 seconds before breaking blocks."); return true; } else if(fastBreakViolation.get(name) > 0 && math > FASTBREAK_MAXVIOLATIONTIME) { fastBreakViolation.put(name, 0); } } if (!blocksBroken.containsKey(name) || !lastBlockBroken.containsKey(name)) { if(!lastBlockBroken.containsKey(name)) { lastBlockBroken.put(name, System.currentTimeMillis()); } blocksBroken.put(name, 0); } else { blocksBroken.put(name, blocksBroken.get(name)+1); Long math = System.currentTimeMillis() - lastBlockBroken.get(name); if(blocksBroken.get(name) > FASTBREAK_LIMIT && math < FASTBREAK_TIMEMAX) { blocksBroken.put(name, 0); lastBlockBroken.put(name, System.currentTimeMillis()); fastBreakViolation.put(name, fastBreakViolation.get(name)+1); return true; } else if(blocksBroken.get(name) > FASTBREAK_LIMIT) { lastBlockBroken.put(name, System.currentTimeMillis()); blocksBroken.put(name, 0); } } } return false; } public boolean checkFastPlace(Player player) { int violations = FASTPLACE_MAXVIOLATIONS; if(player.getGameMode() == GameMode.CREATIVE) { violations = FASTPLACE_MAXVIOLATIONS_CREATIVE; } long time = System.currentTimeMillis(); String name = player.getName(); if(!lastBlockPlaceTime.containsKey(name) || !fastPlaceViolation.containsKey(name)) { lastBlockPlaceTime.put(name, Long.parseLong("0")); if(!fastPlaceViolation.containsKey(name)) { fastPlaceViolation.put(name, 0); } } else if(fastPlaceViolation.containsKey(name) && fastPlaceViolation.get(name) > violations) { Long math = System.currentTimeMillis() - lastBlockPlaced.get(name); if(lastBlockPlaced.get(name) > 0 && math < FASTPLACE_MAXVIOLATIONTIME) { lastBlockPlaced.put(name, time); player.sendMessage(ChatColor.RED + "[AntiCheat] Fastplacing detected. Please wait 10 seconds before placing blocks."); return true; } else if (lastBlockPlaced.get(name) > 0 && math > FASTPLACE_MAXVIOLATIONTIME) { fastPlaceViolation.put(name, 0); } } else if(lastBlockPlaced.containsKey(name)) { long last = lastBlockPlaced.get(name); long lastTime = lastBlockPlaceTime.get(name); long thisTime = time-last; boolean nocheck = thisTime < 1 || lastTime < 1; if(!lastZeroHitPlace.containsKey(name)) { lastZeroHitPlace.put(name, 0); } if(nocheck) { if(!lastZeroHitPlace.containsKey(name)) { lastZeroHitPlace.put(name, 1); } else { lastZeroHitPlace.put(name, lastZeroHitPlace.get(name)+1); } } if(thisTime < FASTPLACE_TIMEMAX && lastTime < FASTPLACE_TIMEMAX && nocheck && lastZeroHitPlace.get(name) > FASTPLACE_ZEROLIMIT) { lastBlockPlaceTime.put(name, (time-last)); lastBlockPlaced.put(name, time); fastPlaceViolation.put(name, fastPlaceViolation.get(name)+1); return true; } lastBlockPlaceTime.put(name, (time-last)); } lastBlockPlaced.put(name, time); return false; } public void logBowWindUp(Player player) { logEvent(bowWindUp,player,BOW_MIN); } public boolean justWoundUp(Player player) { return bowWindUp.contains(player.getName()); } public void logEatingStart(Player player) { logEvent(startEat,player,EAT_MIN); } public boolean justStartedEating(Player player) { return startEat.contains(player.getName()); } public void logHeal(Player player) { logEvent(healed,player,HEAL_MIN); } public boolean justHealed(Player player) { return healed.contains(player.getName()); } public void logChat(Player player) { String name = player.getName(); if(chatLevel.get(name) == null) { logEvent(chatLevel,player,1,CHAT_MIN); } else { int amount = chatLevel.get(name)+1; chatLevel.put(name, amount); checkChatLevel(player, amount); } } public boolean checkSpam(Player player, String msg) { String name = player.getName(); if(lastMessage.get(name) == null) { lastMessage.put(name, msg); } else { if(oldMessage.get(name) != null && lastMessage.get(name).equals(msg) && oldMessage.get(name).equals(msg)) { return true; } else { oldMessage.put(name, lastMessage.get(name)); lastMessage.put(name, msg); return false; } } return false; } public void clearChatLevel(Player player) { chatLevel.remove(player.getName()); } public void logInstantBreak(final Player player) { logEvent(instantBreakExempt,player,INSTANT_BREAK_TIME); } public boolean isInstantBreakExempt(Player player) { return instantBreakExempt.contains(player.getName()); } public void logSprint(final Player player) { logEvent(sprinted,player,SPRINT_MIN); } public boolean justSprinted(Player player) { return sprinted.contains(player.getName()); } public void logBlockBreak(final Player player) { logEvent(brokenBlock,player,BLOCK_BREAK_MIN); resetAnimation(player); } public boolean justBroke(Player player) { return brokenBlock.contains(player.getName()); } public void logBlockPlace(final Player player) { logEvent(placedBlock,player,BLOCK_PLACE_MIN); } public boolean justPlaced(Player player) { return placedBlock.contains(player.getName()); } public void logAnimation(final Player player) { logEvent(animated,player,ANIMATION_MIN); increment(player,blockPunches); } public void resetAnimation(final Player player) { animated.remove(player.getName()); blockPunches.put(player.getName(), 0); } public boolean justAnimated(Player player) { return animated.contains(player.getName()); } public void logDamage(final Player player) { int time = DAMAGE_TIME; if(player.getInventory().getItemInHand().getEnchantments().containsKey(Enchantment.KNOCKBACK)) { time = KNOCKBACK_DAMAGE_TIME; } logEvent(movingExempt,player,time); } public void logEnterExit(final Player player) { logEvent(movingExempt,player,ENTERED_EXTITED_TIME); } public void logToggleSneak(final Player player) { logEvent(movingExempt,player,SNEAK_TIME); } public void logTeleport(final Player player) { logEvent(movingExempt,player,TELEPORT_TIME); } public void logExitFly(final Player player) { logEvent(movingExempt,player,EXIT_FLY_TIME); } public void logJoin(final Player player) { logEvent(movingExempt,player,JOIN_TIME); } public boolean isMovingExempt(Player player) { return movingExempt.contains(player.getName()) || player.isFlying(); } public boolean isSpeedExempt(Player player) { return movingExempt.contains(player.getName()); } public void logDroppedItem(final Player player) { logEvent(droppedItem,player,DROPPED_ITEM_TIME); } public boolean justDroppedItem(Player player) { return droppedItem.contains(player.getName()); } @SuppressWarnings("unchecked") private void logEvent(@SuppressWarnings("rawtypes") final List list, final Player player, long time) { list.add(player.getName()); micromanage.getPlugin().getServer().getScheduler().scheduleSyncDelayedTask(micromanage.getPlugin(), new Runnable() { @Override public void run() { list.remove(player.getName()); } }, time); } @SuppressWarnings("unchecked") private void logEvent(@SuppressWarnings("rawtypes") final Map map, final Player player, final Object obj, long time) { map.put(player,obj); micromanage.getPlugin().getServer().getScheduler().scheduleSyncDelayedTask(micromanage.getPlugin(), new Runnable() { @Override public void run() { map.remove(player); } }, time); } private void checkChatLevel(Player player, int amount) { if(amount >= CHAT_WARN_LEVEL) { player.sendMessage(ChatColor.RED+"Please stop flooding the server!"); } if (amount >= CHAT_KICK_LEVEL) { String name = player.getName(); int kick = 0; if(chatKicks.get(name) == null || chatKicks.get(name) == 0) { kick = 1; chatKicks.put(name, 1); } else { kick = (int)chatKicks.get(name)+1; chatKicks.put(name, kick); } if(chatKicks.get(name) <= CHAT_BAN_LEVEL) { player.kickPlayer(ChatColor.RED+"Spamming, kick "+kick+"/3"); micromanage.getPlugin().getServer().broadcastMessage(ChatColor.RED+player.getName()+" was kicked for spamming."); } else { player.kickPlayer(ChatColor.RED+"Banned for spamming."); player.setBanned(true); micromanage.getPlugin().getServer().broadcastMessage(ChatColor.RED+player.getName()+" was banned for spamming."); } } } public void increment(Player player, Map<String,Integer> map) { String name = player.getName(); if(map.get(name) == null) { map.put(name, 1); } else { int amount = map.get(name)+1; if(amount < BLOCK_PUNCH_MIN+1) { map.put(name, amount); } else { map.put(name, BLOCK_PUNCH_MIN); } } } }
true
true
public boolean checkYAxis(Player player, Distance distance) { //Arrow to the knee check if(distance.getYDifference() > 400) { //teleport. so just cancel. return false; } //Arrow to the knee check if(!player.isFlying()) { double y1 = player.getLocation().getY(); String name = player.getName(); //Fix Y axis spam. if(!lastYcoord.containsKey(name) || !lastYtime.containsKey(name) || !yAxisLastViolation.containsKey(name) || !yAxisLastViolation.containsKey(name)) { lastYcoord.put(name, y1); yAxisViolations.put(name, 0); yAxisLastViolation.put(name, 0L); lastYtime.put(name, System.currentTimeMillis()); } else { if(y1 > lastYcoord.get(name) && yAxisViolations.get(name) > Y_MAXVIOLATIONS && (System.currentTimeMillis() - yAxisLastViolation.get(name)) < Y_MAXVIOTIME) { Location g = player.getLocation(); g.setY(lastYcoord.get(name)); player.sendMessage(ChatColor.RED + "[AntiCheat] Fly hacking on the y-axis detected. Please wait 5 seconds to prevent getting damage."); yAxisViolations.put(name, yAxisViolations.get(name)+1); yAxisLastViolation.put(name, System.currentTimeMillis()); if(g.getBlock().getTypeId() == 0) { player.teleport(g); } return true; } else { if(yAxisViolations.get(name) > Y_MAXVIOLATIONS && (System.currentTimeMillis() - yAxisLastViolation.get(name)) > Y_MAXVIOTIME) { yAxisViolations.put(name, 0); yAxisLastViolation.put(name, 0L); } } if((y1 - lastYcoord.get(name)) > Y_MAXDIFF && (System.currentTimeMillis() - lastYtime.get(name)) < Y_TIME) { Location g = player.getLocation(); g.setY(lastYcoord.get(name)); yAxisViolations.put(name, yAxisViolations.get(name)+1); yAxisLastViolation.put(name, System.currentTimeMillis()); if(g.getBlock().getTypeId() == 0) { player.teleport(g); } return true; } else { if((y1 - lastYcoord.get(name)) > Y_MAXDIFF + 1 || (System.currentTimeMillis() - lastYtime.get(name)) > Y_TIME) { lastYtime.put(name, System.currentTimeMillis()); lastYcoord.put(name, y1); } } } } //Fix Y axis spam return false; }
public boolean checkYAxis(Player player, Distance distance) { //Arrow to the knee check if(distance.getYDifference() > 400) { //teleport. so just cancel. return false; } if(!isMovingExempt(player)) { double y1 = player.getLocation().getY(); String name = player.getName(); //Fix Y axis spam. if(!lastYcoord.containsKey(name) || !lastYtime.containsKey(name) || !yAxisLastViolation.containsKey(name) || !yAxisLastViolation.containsKey(name)) { lastYcoord.put(name, y1); yAxisViolations.put(name, 0); yAxisLastViolation.put(name, 0L); lastYtime.put(name, System.currentTimeMillis()); } else { if(y1 > lastYcoord.get(name) && yAxisViolations.get(name) > Y_MAXVIOLATIONS && (System.currentTimeMillis() - yAxisLastViolation.get(name)) < Y_MAXVIOTIME) { Location g = player.getLocation(); g.setY(lastYcoord.get(name)); player.sendMessage(ChatColor.RED + "[AntiCheat] Fly hacking on the y-axis detected. Please wait 5 seconds to prevent getting damage."); yAxisViolations.put(name, yAxisViolations.get(name)+1); yAxisLastViolation.put(name, System.currentTimeMillis()); if(g.getBlock().getTypeId() == 0) { player.teleport(g); } return true; } else { if(yAxisViolations.get(name) > Y_MAXVIOLATIONS && (System.currentTimeMillis() - yAxisLastViolation.get(name)) > Y_MAXVIOTIME) { yAxisViolations.put(name, 0); yAxisLastViolation.put(name, 0L); } } if((y1 - lastYcoord.get(name)) > Y_MAXDIFF && (System.currentTimeMillis() - lastYtime.get(name)) < Y_TIME) { Location g = player.getLocation(); g.setY(lastYcoord.get(name)); yAxisViolations.put(name, yAxisViolations.get(name)+1); yAxisLastViolation.put(name, System.currentTimeMillis()); if(g.getBlock().getTypeId() == 0) { player.teleport(g); } return true; } else { if((y1 - lastYcoord.get(name)) > Y_MAXDIFF + 1 || (System.currentTimeMillis() - lastYtime.get(name)) > Y_TIME) { lastYtime.put(name, System.currentTimeMillis()); lastYcoord.put(name, y1); } } } } //Fix Y axis spam return false; }
diff --git a/src/br/com/thiagopagonha/psnapi/GCMIntentService.java b/src/br/com/thiagopagonha/psnapi/GCMIntentService.java index 61543a5..a34b953 100644 --- a/src/br/com/thiagopagonha/psnapi/GCMIntentService.java +++ b/src/br/com/thiagopagonha/psnapi/GCMIntentService.java @@ -1,124 +1,126 @@ package br.com.thiagopagonha.psnapi; import static br.com.thiagopagonha.psnapi.utils.CommonUtilities.SENDER_ID; import static br.com.thiagopagonha.psnapi.utils.CommonUtilities.displayMessage; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.util.Log; import br.com.thiagopagonha.psnapi.gcm.ServerUtilities; import br.com.thiagopagonha.psnapi.model.FriendsDBHelper; import com.google.android.gcm.GCMBaseIntentService; /** * IntentService responsible for handling GCM messages. * * AVISO: * * Essa merda de classe tem que ficar no mesmo pacote da permissão do CD2_MESSAGE * declarada no AndroidManifest.xml !!! * */ public class GCMIntentService extends GCMBaseIntentService { private static final String TAG = "GCMIntentService"; public GCMIntentService() { super(SENDER_ID); } @Override protected void onRegistered(Context context, String registrationId) { Log.i(TAG, "Device registered: regId = " + registrationId); displayMessage(context, getString(R.string.gcm_registered)); ServerUtilities.register(context, registrationId); } @Override protected void onUnregistered(Context context, String registrationId) { Log.i(TAG, "Device unregistered"); displayMessage(context, getString(R.string.gcm_unregistered)); ServerUtilities.unregister(context, registrationId); } @Override protected void onMessage(Context context, Intent intent) { Log.i(TAG, "Received message"); String playing = intent.getStringExtra("Playing"); String psnId = intent.getStringExtra("PsnId"); String avatarSmall = intent.getStringExtra("AvatarSmall"); String message = psnId + " is playing " + playing; // -- Mostra Mensagem no Log displayMessage(context, message); // -- Atualiza Informações do amigo if(!updateUserInfo(psnId,playing,avatarSmall)) { // -- Só gera notificação para o usuário caso não seja o mesmo jogo generateNotification(context, message); } } private boolean updateUserInfo(String psnId, String playing, String avatarSmall) { // -- Dicionário no SQLite Log.d(TAG, "updateUserInfo"); FriendsDBHelper friendsDBHelper = new FriendsDBHelper(getApplicationContext()); boolean sameGame = friendsDBHelper.saveFriend(psnId, playing, avatarSmall); friendsDBHelper.close(); return sameGame; } @Override protected void onDeletedMessages(Context context, int total) { Log.i(TAG, "Received deleted messages notification"); String message = getString(R.string.gcm_deleted, total); displayMessage(context, message); // notifies user generateNotification(context, message); } @Override public void onError(Context context, String errorId) { Log.i(TAG, "Received error: " + errorId); displayMessage(context, getString(R.string.gcm_error, errorId)); } @Override protected boolean onRecoverableError(Context context, String errorId) { // log message Log.i(TAG, "Received recoverable error: " + errorId); displayMessage(context, getString(R.string.gcm_recoverable_error, errorId)); return super.onRecoverableError(context, errorId); } /** * Issues a notification to inform the user that server has sent a message. */ private static void generateNotification(Context context, String message) { Log.d(TAG, "generateNotification"); int icon = R.drawable.ic_launcher; long when = System.currentTimeMillis(); NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); Notification notification = new Notification(icon, message, when); String title = context.getString(R.string.app_name); Intent notificationIntent = new Intent(context, MainActivity.class); // set intent so it does not start a new activity notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0); notification.setLatestEventInfo(context, title, message, intent); + notification.defaults |= Notification.DEFAULT_SOUND; + notification.defaults |= Notification.DEFAULT_VIBRATE; notification.flags |= Notification.FLAG_AUTO_CANCEL; notificationManager.notify(0, notification); } }
true
true
private static void generateNotification(Context context, String message) { Log.d(TAG, "generateNotification"); int icon = R.drawable.ic_launcher; long when = System.currentTimeMillis(); NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); Notification notification = new Notification(icon, message, when); String title = context.getString(R.string.app_name); Intent notificationIntent = new Intent(context, MainActivity.class); // set intent so it does not start a new activity notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0); notification.setLatestEventInfo(context, title, message, intent); notification.flags |= Notification.FLAG_AUTO_CANCEL; notificationManager.notify(0, notification); }
private static void generateNotification(Context context, String message) { Log.d(TAG, "generateNotification"); int icon = R.drawable.ic_launcher; long when = System.currentTimeMillis(); NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); Notification notification = new Notification(icon, message, when); String title = context.getString(R.string.app_name); Intent notificationIntent = new Intent(context, MainActivity.class); // set intent so it does not start a new activity notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0); notification.setLatestEventInfo(context, title, message, intent); notification.defaults |= Notification.DEFAULT_SOUND; notification.defaults |= Notification.DEFAULT_VIBRATE; notification.flags |= Notification.FLAG_AUTO_CANCEL; notificationManager.notify(0, notification); }
diff --git a/src/main/java/ru/shutoff/caralarm/TrackView.java b/src/main/java/ru/shutoff/caralarm/TrackView.java index 040ead9..09d6c5a 100644 --- a/src/main/java/ru/shutoff/caralarm/TrackView.java +++ b/src/main/java/ru/shutoff/caralarm/TrackView.java @@ -1,175 +1,179 @@ package ru.shutoff.caralarm; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.preference.PreferenceManager; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.webkit.JavascriptInterface; import android.widget.Toast; import org.joda.time.LocalDateTime; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; public class TrackView extends WebViewActivity { String track; class JsInterface { @JavascriptInterface public String getTrack() { return track; } @JavascriptInterface public void save(double min_lat, double max_lat, double min_lon, double max_lon) { saveTrack(min_lat, max_lat, min_lon, max_lon, true); } @JavascriptInterface public void share(double min_lat, double max_lat, double min_lon, double max_lon) { shareTrack(min_lat, max_lat, min_lon, max_lon); } } @Override String loadURL() { webView.addJavascriptInterface(new JsInterface(), "android"); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); return "file:///android_asset/html/track.html"; } @Override public void onCreate(Bundle savedInstanceState) { track = getIntent().getStringExtra(Names.TRACK); super.onCreate(savedInstanceState); setTitle(getIntent().getStringExtra(Names.TITLE)); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.track, menu); return super.onCreateOptionsMenu(menu); } public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.save: { webView.loadUrl("javascript:saveTrack()"); break; } case R.id.share: { webView.loadUrl("javascript:shareTrack()"); break; } } return false; } File saveTrack(double min_lat, double max_lat, double min_lon, double max_lon, boolean show_toast) { try { File path = Environment.getExternalStorageDirectory(); if (path == null) path = getFilesDir(); path = new File(path, "Tracks"); path.mkdirs(); String[] points = track.split("\\|"); long begin = 0; long end = 0; for (String point : points) { String[] data = point.split(","); + if (data.length != 4) + continue; double lat = Double.parseDouble(data[0]); double lon = Double.parseDouble(data[1]); long time = Long.parseLong(data[3]); if ((lat < min_lat) || (lat > max_lat) || (lon < min_lon) || (lon > max_lon)) continue; if (begin == 0) begin = time; end = time; } LocalDateTime d2 = new LocalDateTime(begin); LocalDateTime d1 = new LocalDateTime(end); String name = d1.toString("dd.MM.yy_HH.mm-") + d2.toString("HH.mm") + ".gpx"; File out = new File(path, name); out.createNewFile(); FileOutputStream f = new FileOutputStream(out); OutputStreamWriter ow = new OutputStreamWriter(f); BufferedWriter writer = new BufferedWriter(ow); writer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); writer.append("<gpx\n"); writer.append(" version=\"1.0\"\n"); writer.append(" creator=\"ExpertGPS 1.1 - http://www.topografix.com\"\n"); writer.append(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"); writer.append(" xmlns=\"http://www.topografix.com/GPX/1/0\"\n"); writer.append(" xsi:schemaLocation=\"http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd\">\n"); writer.append("<time>"); LocalDateTime now = new LocalDateTime(); writer.append(now.toString("yyyy-MM-dd'T'HH:mm:ss'Z")); writer.append("</time>\n"); writer.append("<trk>\n"); boolean trk = false; for (String point : points) { String[] data = point.split(","); + if (data.length != 4) + continue; double lat = Double.parseDouble(data[0]); double lon = Double.parseDouble(data[1]); long time = Long.parseLong(data[3]); if ((lat < min_lat) || (lat > max_lat) || (lon < min_lon) || (lon > max_lon)) { if (trk) { trk = false; writer.append("</trkseg>\n"); } continue; } if (!trk) { trk = true; writer.append("<trkseg>\n"); } writer.append("<trkpt lat=\"" + lat + "\" lon=\"" + lon + "\">\n"); LocalDateTime t = new LocalDateTime(time); writer.append("<time>" + t.toString("yyyy-MM-dd'T'HH:mm:ss'Z") + "</time>\n"); writer.append("</trkpt>\n"); } if (trk) writer.append("</trkseg>"); writer.append("</trk>\n"); writer.append("</gpx>"); writer.close(); if (show_toast) { Toast toast = Toast.makeText(this, getString(R.string.saved) + " " + out.toString(), Toast.LENGTH_LONG); toast.show(); } return out; } catch (Exception ex) { Toast toast = Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG); toast.show(); } return null; } void shareTrack(double min_lat, double max_lat, double min_lon, double max_lon) { File out = saveTrack(min_lat, max_lat, min_lon, max_lon, false); if (out == null) return; Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(out)); shareIntent.setType("application/gpx+xml"); startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.share))); } }
false
true
File saveTrack(double min_lat, double max_lat, double min_lon, double max_lon, boolean show_toast) { try { File path = Environment.getExternalStorageDirectory(); if (path == null) path = getFilesDir(); path = new File(path, "Tracks"); path.mkdirs(); String[] points = track.split("\\|"); long begin = 0; long end = 0; for (String point : points) { String[] data = point.split(","); double lat = Double.parseDouble(data[0]); double lon = Double.parseDouble(data[1]); long time = Long.parseLong(data[3]); if ((lat < min_lat) || (lat > max_lat) || (lon < min_lon) || (lon > max_lon)) continue; if (begin == 0) begin = time; end = time; } LocalDateTime d2 = new LocalDateTime(begin); LocalDateTime d1 = new LocalDateTime(end); String name = d1.toString("dd.MM.yy_HH.mm-") + d2.toString("HH.mm") + ".gpx"; File out = new File(path, name); out.createNewFile(); FileOutputStream f = new FileOutputStream(out); OutputStreamWriter ow = new OutputStreamWriter(f); BufferedWriter writer = new BufferedWriter(ow); writer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); writer.append("<gpx\n"); writer.append(" version=\"1.0\"\n"); writer.append(" creator=\"ExpertGPS 1.1 - http://www.topografix.com\"\n"); writer.append(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"); writer.append(" xmlns=\"http://www.topografix.com/GPX/1/0\"\n"); writer.append(" xsi:schemaLocation=\"http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd\">\n"); writer.append("<time>"); LocalDateTime now = new LocalDateTime(); writer.append(now.toString("yyyy-MM-dd'T'HH:mm:ss'Z")); writer.append("</time>\n"); writer.append("<trk>\n"); boolean trk = false; for (String point : points) { String[] data = point.split(","); double lat = Double.parseDouble(data[0]); double lon = Double.parseDouble(data[1]); long time = Long.parseLong(data[3]); if ((lat < min_lat) || (lat > max_lat) || (lon < min_lon) || (lon > max_lon)) { if (trk) { trk = false; writer.append("</trkseg>\n"); } continue; } if (!trk) { trk = true; writer.append("<trkseg>\n"); } writer.append("<trkpt lat=\"" + lat + "\" lon=\"" + lon + "\">\n"); LocalDateTime t = new LocalDateTime(time); writer.append("<time>" + t.toString("yyyy-MM-dd'T'HH:mm:ss'Z") + "</time>\n"); writer.append("</trkpt>\n"); } if (trk) writer.append("</trkseg>"); writer.append("</trk>\n"); writer.append("</gpx>"); writer.close(); if (show_toast) { Toast toast = Toast.makeText(this, getString(R.string.saved) + " " + out.toString(), Toast.LENGTH_LONG); toast.show(); } return out; } catch (Exception ex) { Toast toast = Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG); toast.show(); } return null; }
File saveTrack(double min_lat, double max_lat, double min_lon, double max_lon, boolean show_toast) { try { File path = Environment.getExternalStorageDirectory(); if (path == null) path = getFilesDir(); path = new File(path, "Tracks"); path.mkdirs(); String[] points = track.split("\\|"); long begin = 0; long end = 0; for (String point : points) { String[] data = point.split(","); if (data.length != 4) continue; double lat = Double.parseDouble(data[0]); double lon = Double.parseDouble(data[1]); long time = Long.parseLong(data[3]); if ((lat < min_lat) || (lat > max_lat) || (lon < min_lon) || (lon > max_lon)) continue; if (begin == 0) begin = time; end = time; } LocalDateTime d2 = new LocalDateTime(begin); LocalDateTime d1 = new LocalDateTime(end); String name = d1.toString("dd.MM.yy_HH.mm-") + d2.toString("HH.mm") + ".gpx"; File out = new File(path, name); out.createNewFile(); FileOutputStream f = new FileOutputStream(out); OutputStreamWriter ow = new OutputStreamWriter(f); BufferedWriter writer = new BufferedWriter(ow); writer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); writer.append("<gpx\n"); writer.append(" version=\"1.0\"\n"); writer.append(" creator=\"ExpertGPS 1.1 - http://www.topografix.com\"\n"); writer.append(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"); writer.append(" xmlns=\"http://www.topografix.com/GPX/1/0\"\n"); writer.append(" xsi:schemaLocation=\"http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd\">\n"); writer.append("<time>"); LocalDateTime now = new LocalDateTime(); writer.append(now.toString("yyyy-MM-dd'T'HH:mm:ss'Z")); writer.append("</time>\n"); writer.append("<trk>\n"); boolean trk = false; for (String point : points) { String[] data = point.split(","); if (data.length != 4) continue; double lat = Double.parseDouble(data[0]); double lon = Double.parseDouble(data[1]); long time = Long.parseLong(data[3]); if ((lat < min_lat) || (lat > max_lat) || (lon < min_lon) || (lon > max_lon)) { if (trk) { trk = false; writer.append("</trkseg>\n"); } continue; } if (!trk) { trk = true; writer.append("<trkseg>\n"); } writer.append("<trkpt lat=\"" + lat + "\" lon=\"" + lon + "\">\n"); LocalDateTime t = new LocalDateTime(time); writer.append("<time>" + t.toString("yyyy-MM-dd'T'HH:mm:ss'Z") + "</time>\n"); writer.append("</trkpt>\n"); } if (trk) writer.append("</trkseg>"); writer.append("</trk>\n"); writer.append("</gpx>"); writer.close(); if (show_toast) { Toast toast = Toast.makeText(this, getString(R.string.saved) + " " + out.toString(), Toast.LENGTH_LONG); toast.show(); } return out; } catch (Exception ex) { Toast toast = Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG); toast.show(); } return null; }
diff --git a/UnitTranslation/src/Measurement.java b/UnitTranslation/src/Measurement.java index ed13cf6..fdff18c 100644 --- a/UnitTranslation/src/Measurement.java +++ b/UnitTranslation/src/Measurement.java @@ -1,41 +1,41 @@ import lombok.EqualsAndHashCode; import lombok.Getter; @EqualsAndHashCode public class Measurement { @Getter protected Double count; @Getter MeasurementType measurementType; public Measurement(MeasurementType measurementType, double count) { this.measurementType = measurementType; this.count = count; } public Measurement expressedIn(MeasurementType measurementType) { - if (measurementType.measurementClass.equals(MeasurementClassification.Length)) { + if (measurementType.measurementClass.equals(measurementType.measurementClass)) { return new Measurement(measurementType, translateTo(measurementType)); } return new Measurement(MeasurementType.InvalidConversion, 0.0); } public Measurement plus(Measurement measurement) { return new Measurement(measurement.getMeasurementType(), combineCounts(measurement)); } double translateTo(MeasurementType outType) { return count * outType.toBaseMultiplier() / measurementType.toBaseMultiplier(); } public String toString() { return count + " " + measurementType.name(); } double combineCounts(Measurement measurement) { return expressedIn(measurement.getMeasurementType()).getCount() + count; } }
true
true
public Measurement expressedIn(MeasurementType measurementType) { if (measurementType.measurementClass.equals(MeasurementClassification.Length)) { return new Measurement(measurementType, translateTo(measurementType)); } return new Measurement(MeasurementType.InvalidConversion, 0.0); }
public Measurement expressedIn(MeasurementType measurementType) { if (measurementType.measurementClass.equals(measurementType.measurementClass)) { return new Measurement(measurementType, translateTo(measurementType)); } return new Measurement(MeasurementType.InvalidConversion, 0.0); }
diff --git a/src/org/apache/http/impl/client/DefaultRequestDirector.java b/src/org/apache/http/impl/client/DefaultRequestDirector.java index 511f8a0..a95c522 100644 --- a/src/org/apache/http/impl/client/DefaultRequestDirector.java +++ b/src/org/apache/http/impl/client/DefaultRequestDirector.java @@ -1,1088 +1,1099 @@ /* * $HeadURL: http://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk/module-client/src/main/java/org/apache/http/impl/client/DefaultRequestDirector.java $ * $Revision: 676023 $ * $Date: 2008-07-11 09:40:56 -0700 (Fri, 11 Jul 2008) $ * * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.impl.client; import java.io.IOException; import java.io.InterruptedIOException; import java.net.URI; import java.net.URISyntaxException; import java.util.Locale; import java.util.Map; import java.util.concurrent.TimeUnit; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.ConnectionReuseStrategy; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpException; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.ProtocolException; import org.apache.http.ProtocolVersion; import org.apache.http.auth.AuthScheme; import org.apache.http.auth.AuthScope; import org.apache.http.auth.AuthState; import org.apache.http.auth.AuthenticationException; import org.apache.http.auth.Credentials; import org.apache.http.auth.MalformedChallengeException; import org.apache.http.client.AuthenticationHandler; import org.apache.http.client.RequestDirector; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.HttpRequestRetryHandler; import org.apache.http.client.NonRepeatableRequestException; import org.apache.http.client.RedirectException; import org.apache.http.client.RedirectHandler; import org.apache.http.client.UserTokenHandler; import org.apache.http.client.methods.AbortableHttpRequest; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.params.ClientPNames; import org.apache.http.client.params.HttpClientParams; import org.apache.http.client.protocol.ClientContext; import org.apache.http.client.utils.URIUtils; import org.apache.http.conn.BasicManagedEntity; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.ClientConnectionRequest; import org.apache.http.conn.ConnectionKeepAliveStrategy; import org.apache.http.conn.ManagedClientConnection; import org.apache.http.conn.params.ConnManagerParams; import org.apache.http.conn.routing.BasicRouteDirector; import org.apache.http.conn.routing.HttpRoute; import org.apache.http.conn.routing.HttpRouteDirector; import org.apache.http.conn.routing.HttpRoutePlanner; import org.apache.http.conn.scheme.Scheme; import org.apache.http.entity.BufferedHttpEntity; import org.apache.http.message.BasicHttpRequest; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; import org.apache.http.protocol.ExecutionContext; import org.apache.http.protocol.HTTP; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpProcessor; import org.apache.http.protocol.HttpRequestExecutor; /** * Default implementation of {@link RequestDirector}. * <br/> * This class replaces the <code>HttpMethodDirector</code> in HttpClient 3. * * @author <a href="mailto:rolandw at apache.org">Roland Weber</a> * @author <a href="mailto:oleg at ural.ru">Oleg Kalnichevski</a> * * <!-- empty lines to avoid svn diff problems --> * @version $Revision: 676023 $ * * @since 4.0 */ public class DefaultRequestDirector implements RequestDirector { private final Log log = LogFactory.getLog(getClass()); /** The connection manager. */ protected final ClientConnectionManager connManager; /** The route planner. */ protected final HttpRoutePlanner routePlanner; /** The connection re-use strategy. */ protected final ConnectionReuseStrategy reuseStrategy; /** The keep-alive duration strategy. */ protected final ConnectionKeepAliveStrategy keepAliveStrategy; /** The request executor. */ protected final HttpRequestExecutor requestExec; /** The HTTP protocol processor. */ protected final HttpProcessor httpProcessor; /** The request retry handler. */ protected final HttpRequestRetryHandler retryHandler; /** The redirect handler. */ protected final RedirectHandler redirectHandler; /** The target authentication handler. */ private final AuthenticationHandler targetAuthHandler; /** The proxy authentication handler. */ private final AuthenticationHandler proxyAuthHandler; /** The user token handler. */ private final UserTokenHandler userTokenHandler; /** The HTTP parameters. */ protected final HttpParams params; /** The currently allocated connection. */ protected ManagedClientConnection managedConn; private int redirectCount; private int maxRedirects; private final AuthState targetAuthState; private final AuthState proxyAuthState; public DefaultRequestDirector( final HttpRequestExecutor requestExec, final ClientConnectionManager conman, final ConnectionReuseStrategy reustrat, final ConnectionKeepAliveStrategy kastrat, final HttpRoutePlanner rouplan, final HttpProcessor httpProcessor, final HttpRequestRetryHandler retryHandler, final RedirectHandler redirectHandler, final AuthenticationHandler targetAuthHandler, final AuthenticationHandler proxyAuthHandler, final UserTokenHandler userTokenHandler, final HttpParams params) { if (requestExec == null) { throw new IllegalArgumentException ("Request executor may not be null."); } if (conman == null) { throw new IllegalArgumentException ("Client connection manager may not be null."); } if (reustrat == null) { throw new IllegalArgumentException ("Connection reuse strategy may not be null."); } if (kastrat == null) { throw new IllegalArgumentException ("Connection keep alive strategy may not be null."); } if (rouplan == null) { throw new IllegalArgumentException ("Route planner may not be null."); } if (httpProcessor == null) { throw new IllegalArgumentException ("HTTP protocol processor may not be null."); } if (retryHandler == null) { throw new IllegalArgumentException ("HTTP request retry handler may not be null."); } if (redirectHandler == null) { throw new IllegalArgumentException ("Redirect handler may not be null."); } if (targetAuthHandler == null) { throw new IllegalArgumentException ("Target authentication handler may not be null."); } if (proxyAuthHandler == null) { throw new IllegalArgumentException ("Proxy authentication handler may not be null."); } if (userTokenHandler == null) { throw new IllegalArgumentException ("User token handler may not be null."); } if (params == null) { throw new IllegalArgumentException ("HTTP parameters may not be null"); } this.requestExec = requestExec; this.connManager = conman; this.reuseStrategy = reustrat; this.keepAliveStrategy = kastrat; this.routePlanner = rouplan; this.httpProcessor = httpProcessor; this.retryHandler = retryHandler; this.redirectHandler = redirectHandler; this.targetAuthHandler = targetAuthHandler; this.proxyAuthHandler = proxyAuthHandler; this.userTokenHandler = userTokenHandler; this.params = params; this.managedConn = null; this.redirectCount = 0; this.maxRedirects = this.params.getIntParameter(ClientPNames.MAX_REDIRECTS, 100); this.targetAuthState = new AuthState(); this.proxyAuthState = new AuthState(); } // constructor private RequestWrapper wrapRequest( final HttpRequest request) throws ProtocolException { if (request instanceof HttpEntityEnclosingRequest) { return new EntityEnclosingRequestWrapper( (HttpEntityEnclosingRequest) request); } else { return new RequestWrapper( request); } } protected void rewriteRequestURI( final RequestWrapper request, final HttpRoute route) throws ProtocolException { try { URI uri = request.getURI(); if (route.getProxyHost() != null && !route.isTunnelled()) { // Make sure the request URI is absolute if (!uri.isAbsolute()) { HttpHost target = route.getTargetHost(); uri = URIUtils.rewriteURI(uri, target); request.setURI(uri); } } else { // Make sure the request URI is relative if (uri.isAbsolute()) { uri = URIUtils.rewriteURI(uri, null); request.setURI(uri); } } } catch (URISyntaxException ex) { throw new ProtocolException("Invalid URI: " + request.getRequestLine().getUri(), ex); } } // non-javadoc, see interface ClientRequestDirector public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws HttpException, IOException { HttpRequest orig = request; RequestWrapper origWrapper = wrapRequest(orig); origWrapper.setParams(params); HttpRoute origRoute = determineRoute(target, origWrapper, context); RoutedRequest roureq = new RoutedRequest(origWrapper, origRoute); long timeout = ConnManagerParams.getTimeout(params); int execCount = 0; boolean reuse = false; HttpResponse response = null; boolean done = false; try { while (!done) { // In this loop, the RoutedRequest may be replaced by a // followup request and route. The request and route passed // in the method arguments will be replaced. The original // request is still available in 'orig'. RequestWrapper wrapper = roureq.getRequest(); HttpRoute route = roureq.getRoute(); // See if we have a user token bound to the execution context Object userToken = context.getAttribute(ClientContext.USER_TOKEN); // Allocate connection if needed if (managedConn == null) { ClientConnectionRequest connRequest = connManager.requestConnection( route, userToken); if (orig instanceof AbortableHttpRequest) { ((AbortableHttpRequest) orig).setConnectionRequest(connRequest); } try { managedConn = connRequest.getConnection(timeout, TimeUnit.MILLISECONDS); } catch(InterruptedException interrupted) { InterruptedIOException iox = new InterruptedIOException(); iox.initCause(interrupted); throw iox; } if (HttpConnectionParams.isStaleCheckingEnabled(params)) { // validate connection this.log.debug("Stale connection check"); if (managedConn.isStale()) { this.log.debug("Stale connection detected"); - managedConn.close(); + // BEGIN android-changed + try { + managedConn.close(); + } catch (IOException ignored) { + // SSLSocket's will throw IOException + // because they can't send a "close + // notify" protocol message to the + // server. Just supresss any + // exceptions related to closing the + // stale connection. + } + // END android-changed } } } if (orig instanceof AbortableHttpRequest) { ((AbortableHttpRequest) orig).setReleaseTrigger(managedConn); } // Reopen connection if needed if (!managedConn.isOpen()) { managedConn.open(route, context, params); } try { establishRoute(route, context); } catch (TunnelRefusedException ex) { if (this.log.isDebugEnabled()) { this.log.debug(ex.getMessage()); } response = ex.getResponse(); break; } // Reset headers on the request wrapper wrapper.resetHeaders(); // Re-write request URI if needed rewriteRequestURI(wrapper, route); // Use virtual host if set target = (HttpHost) wrapper.getParams().getParameter( ClientPNames.VIRTUAL_HOST); if (target == null) { target = route.getTargetHost(); } HttpHost proxy = route.getProxyHost(); // Populate the execution context context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, target); context.setAttribute(ExecutionContext.HTTP_PROXY_HOST, proxy); context.setAttribute(ExecutionContext.HTTP_CONNECTION, managedConn); context.setAttribute(ClientContext.TARGET_AUTH_STATE, targetAuthState); context.setAttribute(ClientContext.PROXY_AUTH_STATE, proxyAuthState); // Run request protocol interceptors requestExec.preProcess(wrapper, httpProcessor, context); context.setAttribute(ExecutionContext.HTTP_REQUEST, wrapper); boolean retrying = true; while (retrying) { // Increment total exec count (with redirects) execCount++; // Increment exec count for this particular request wrapper.incrementExecCount(); if (wrapper.getExecCount() > 1 && !wrapper.isRepeatable()) { throw new NonRepeatableRequestException("Cannot retry request " + "with a non-repeatable request entity"); } try { if (this.log.isDebugEnabled()) { this.log.debug("Attempt " + execCount + " to execute request"); } response = requestExec.execute(wrapper, managedConn, context); retrying = false; } catch (IOException ex) { this.log.debug("Closing the connection."); managedConn.close(); if (retryHandler.retryRequest(ex, execCount, context)) { if (this.log.isInfoEnabled()) { this.log.info("I/O exception ("+ ex.getClass().getName() + ") caught when processing request: " + ex.getMessage()); } if (this.log.isDebugEnabled()) { this.log.debug(ex.getMessage(), ex); } this.log.info("Retrying request"); } else { throw ex; } // If we have a direct route to the target host // just re-open connection and re-try the request if (route.getHopCount() == 1) { this.log.debug("Reopening the direct connection."); managedConn.open(route, context, params); } else { // otherwise give up retrying = false; } } } // Run response protocol interceptors response.setParams(params); requestExec.postProcess(response, httpProcessor, context); // The connection is in or can be brought to a re-usable state. reuse = reuseStrategy.keepAlive(response, context); if(reuse) { // Set the idle duration of this connection long duration = keepAliveStrategy.getKeepAliveDuration(response, context); managedConn.setIdleDuration(duration, TimeUnit.MILLISECONDS); } RoutedRequest followup = handleResponse(roureq, response, context); if (followup == null) { done = true; } else { if (reuse) { this.log.debug("Connection kept alive"); // Make sure the response body is fully consumed, if present HttpEntity entity = response.getEntity(); if (entity != null) { entity.consumeContent(); } // entity consumed above is not an auto-release entity, // need to mark the connection re-usable explicitly managedConn.markReusable(); } else { managedConn.close(); } // check if we can use the same connection for the followup if (!followup.getRoute().equals(roureq.getRoute())) { releaseConnection(); } roureq = followup; } userToken = this.userTokenHandler.getUserToken(context); context.setAttribute(ClientContext.USER_TOKEN, userToken); if (managedConn != null) { managedConn.setState(userToken); } } // while not done // check for entity, release connection if possible if ((response == null) || (response.getEntity() == null) || !response.getEntity().isStreaming()) { // connection not needed and (assumed to be) in re-usable state if (reuse) managedConn.markReusable(); releaseConnection(); } else { // install an auto-release entity HttpEntity entity = response.getEntity(); entity = new BasicManagedEntity(entity, managedConn, reuse); response.setEntity(entity); } return response; } catch (HttpException ex) { abortConnection(); throw ex; } catch (IOException ex) { abortConnection(); throw ex; } catch (RuntimeException ex) { abortConnection(); throw ex; } } // execute /** * Returns the connection back to the connection manager * and prepares for retrieving a new connection during * the next request. */ protected void releaseConnection() { // Release the connection through the ManagedConnection instead of the // ConnectionManager directly. This lets the connection control how // it is released. try { managedConn.releaseConnection(); } catch(IOException ignored) { this.log.debug("IOException releasing connection", ignored); } managedConn = null; } /** * Determines the route for a request. * Called by {@link #execute} * to determine the route for either the original or a followup request. * * @param target the target host for the request. * Implementations may accept <code>null</code> * if they can still determine a route, for example * to a default target or by inspecting the request. * @param request the request to execute * @param context the context to use for the execution, * never <code>null</code> * * @return the route the request should take * * @throws HttpException in case of a problem */ protected HttpRoute determineRoute(HttpHost target, HttpRequest request, HttpContext context) throws HttpException { if (target == null) { target = (HttpHost) request.getParams().getParameter( ClientPNames.DEFAULT_HOST); } if (target == null) { throw new IllegalStateException ("Target host must not be null, or set in parameters."); } return this.routePlanner.determineRoute(target, request, context); } /** * Establishes the target route. * * @param route the route to establish * @param context the context for the request execution * * @throws HttpException in case of a problem * @throws IOException in case of an IO problem */ protected void establishRoute(HttpRoute route, HttpContext context) throws HttpException, IOException { //@@@ how to handle CONNECT requests for tunnelling? //@@@ refuse to send external CONNECT via director? special handling? //@@@ should the request parameters already be used below? //@@@ probably yes, but they're not linked yet //@@@ will linking above cause problems with linking in reqExec? //@@@ probably not, because the parent is replaced //@@@ just make sure we don't link parameters to themselves HttpRouteDirector rowdy = new BasicRouteDirector(); int step; do { HttpRoute fact = managedConn.getRoute(); step = rowdy.nextStep(route, fact); switch (step) { case HttpRouteDirector.CONNECT_TARGET: case HttpRouteDirector.CONNECT_PROXY: managedConn.open(route, context, this.params); break; case HttpRouteDirector.TUNNEL_TARGET: { boolean secure = createTunnelToTarget(route, context); this.log.debug("Tunnel to target created."); managedConn.tunnelTarget(secure, this.params); } break; case HttpRouteDirector.TUNNEL_PROXY: { // The most simple example for this case is a proxy chain // of two proxies, where P1 must be tunnelled to P2. // route: Source -> P1 -> P2 -> Target (3 hops) // fact: Source -> P1 -> Target (2 hops) final int hop = fact.getHopCount()-1; // the hop to establish boolean secure = createTunnelToProxy(route, hop, context); this.log.debug("Tunnel to proxy created."); managedConn.tunnelProxy(route.getHopTarget(hop), secure, this.params); } break; case HttpRouteDirector.LAYER_PROTOCOL: managedConn.layerProtocol(context, this.params); break; case HttpRouteDirector.UNREACHABLE: throw new IllegalStateException ("Unable to establish route." + "\nplanned = " + route + "\ncurrent = " + fact); case HttpRouteDirector.COMPLETE: // do nothing break; default: throw new IllegalStateException ("Unknown step indicator "+step+" from RouteDirector."); } // switch } while (step > HttpRouteDirector.COMPLETE); } // establishConnection /** * Creates a tunnel to the target server. * The connection must be established to the (last) proxy. * A CONNECT request for tunnelling through the proxy will * be created and sent, the response received and checked. * This method does <i>not</i> update the connection with * information about the tunnel, that is left to the caller. * * @param route the route to establish * @param context the context for request execution * * @return <code>true</code> if the tunnelled route is secure, * <code>false</code> otherwise. * The implementation here always returns <code>false</code>, * but derived classes may override. * * @throws HttpException in case of a problem * @throws IOException in case of an IO problem */ protected boolean createTunnelToTarget(HttpRoute route, HttpContext context) throws HttpException, IOException { HttpHost proxy = route.getProxyHost(); HttpHost target = route.getTargetHost(); HttpResponse response = null; boolean done = false; while (!done) { done = true; if (!this.managedConn.isOpen()) { this.managedConn.open(route, context, this.params); } HttpRequest connect = createConnectRequest(route, context); String agent = HttpProtocolParams.getUserAgent(params); if (agent != null) { connect.addHeader(HTTP.USER_AGENT, agent); } connect.addHeader(HTTP.TARGET_HOST, target.toHostString()); AuthScheme authScheme = this.proxyAuthState.getAuthScheme(); AuthScope authScope = this.proxyAuthState.getAuthScope(); Credentials creds = this.proxyAuthState.getCredentials(); if (creds != null) { if (authScope != null || !authScheme.isConnectionBased()) { try { connect.addHeader(authScheme.authenticate(creds, connect)); } catch (AuthenticationException ex) { if (this.log.isErrorEnabled()) { this.log.error("Proxy authentication error: " + ex.getMessage()); } } } } response = requestExec.execute(connect, this.managedConn, context); int status = response.getStatusLine().getStatusCode(); if (status < 200) { throw new HttpException("Unexpected response to CONNECT request: " + response.getStatusLine()); } CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER); if (credsProvider != null && HttpClientParams.isAuthenticating(params)) { if (this.proxyAuthHandler.isAuthenticationRequested(response, context)) { this.log.debug("Proxy requested authentication"); Map<String, Header> challenges = this.proxyAuthHandler.getChallenges( response, context); try { processChallenges( challenges, this.proxyAuthState, this.proxyAuthHandler, response, context); } catch (AuthenticationException ex) { if (this.log.isWarnEnabled()) { this.log.warn("Authentication error: " + ex.getMessage()); break; } } updateAuthState(this.proxyAuthState, proxy, credsProvider); if (this.proxyAuthState.getCredentials() != null) { done = false; // Retry request if (this.reuseStrategy.keepAlive(response, context)) { this.log.debug("Connection kept alive"); // Consume response content HttpEntity entity = response.getEntity(); if (entity != null) { entity.consumeContent(); } } else { this.managedConn.close(); } } } else { // Reset proxy auth scope this.proxyAuthState.setAuthScope(null); } } } int status = response.getStatusLine().getStatusCode(); if (status > 299) { // Buffer response content HttpEntity entity = response.getEntity(); if (entity != null) { response.setEntity(new BufferedHttpEntity(entity)); } this.managedConn.close(); throw new TunnelRefusedException("CONNECT refused by proxy: " + response.getStatusLine(), response); } this.managedConn.markReusable(); // How to decide on security of the tunnelled connection? // The socket factory knows only about the segment to the proxy. // Even if that is secure, the hop to the target may be insecure. // Leave it to derived classes, consider insecure by default here. return false; } // createTunnelToTarget /** * Creates a tunnel to an intermediate proxy. * This method is <i>not</i> implemented in this class. * It just throws an exception here. * * @param route the route to establish * @param hop the hop in the route to establish now. * <code>route.getHopTarget(hop)</code> * will return the proxy to tunnel to. * @param context the context for request execution * * @return <code>true</code> if the partially tunnelled connection * is secure, <code>false</code> otherwise. * * @throws HttpException in case of a problem * @throws IOException in case of an IO problem */ protected boolean createTunnelToProxy(HttpRoute route, int hop, HttpContext context) throws HttpException, IOException { // Have a look at createTunnelToTarget and replicate the parts // you need in a custom derived class. If your proxies don't require // authentication, it is not too hard. But for the stock version of // HttpClient, we cannot make such simplifying assumptions and would // have to include proxy authentication code. The HttpComponents team // is currently not in a position to support rarely used code of this // complexity. Feel free to submit patches that refactor the code in // createTunnelToTarget to facilitate re-use for proxy tunnelling. throw new UnsupportedOperationException ("Proxy chains are not supported."); } /** * Creates the CONNECT request for tunnelling. * Called by {@link #createTunnelToTarget createTunnelToTarget}. * * @param route the route to establish * @param context the context for request execution * * @return the CONNECT request for tunnelling */ protected HttpRequest createConnectRequest(HttpRoute route, HttpContext context) { // see RFC 2817, section 5.2 and // INTERNET-DRAFT: Tunneling TCP based protocols through // Web proxy servers HttpHost target = route.getTargetHost(); String host = target.getHostName(); int port = target.getPort(); if (port < 0) { Scheme scheme = connManager.getSchemeRegistry(). getScheme(target.getSchemeName()); port = scheme.getDefaultPort(); } StringBuilder buffer = new StringBuilder(host.length() + 6); buffer.append(host); buffer.append(':'); buffer.append(Integer.toString(port)); String authority = buffer.toString(); ProtocolVersion ver = HttpProtocolParams.getVersion(params); HttpRequest req = new BasicHttpRequest ("CONNECT", authority, ver); return req; } /** * Analyzes a response to check need for a followup. * * @param roureq the request and route. * @param response the response to analayze * @param context the context used for the current request execution * * @return the followup request and route if there is a followup, or * <code>null</code> if the response should be returned as is * * @throws HttpException in case of a problem * @throws IOException in case of an IO problem */ protected RoutedRequest handleResponse(RoutedRequest roureq, HttpResponse response, HttpContext context) throws HttpException, IOException { HttpRoute route = roureq.getRoute(); HttpHost proxy = route.getProxyHost(); RequestWrapper request = roureq.getRequest(); HttpParams params = request.getParams(); if (HttpClientParams.isRedirecting(params) && this.redirectHandler.isRedirectRequested(response, context)) { if (redirectCount >= maxRedirects) { throw new RedirectException("Maximum redirects (" + maxRedirects + ") exceeded"); } redirectCount++; URI uri = this.redirectHandler.getLocationURI(response, context); HttpHost newTarget = new HttpHost( uri.getHost(), uri.getPort(), uri.getScheme()); HttpGet redirect = new HttpGet(uri); HttpRequest orig = request.getOriginal(); redirect.setHeaders(orig.getAllHeaders()); RequestWrapper wrapper = new RequestWrapper(redirect); wrapper.setParams(params); HttpRoute newRoute = determineRoute(newTarget, wrapper, context); RoutedRequest newRequest = new RoutedRequest(wrapper, newRoute); if (this.log.isDebugEnabled()) { this.log.debug("Redirecting to '" + uri + "' via " + newRoute); } return newRequest; } CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER); if (credsProvider != null && HttpClientParams.isAuthenticating(params)) { if (this.targetAuthHandler.isAuthenticationRequested(response, context)) { HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); if (target == null) { target = route.getTargetHost(); } this.log.debug("Target requested authentication"); Map<String, Header> challenges = this.targetAuthHandler.getChallenges( response, context); try { processChallenges(challenges, this.targetAuthState, this.targetAuthHandler, response, context); } catch (AuthenticationException ex) { if (this.log.isWarnEnabled()) { this.log.warn("Authentication error: " + ex.getMessage()); return null; } } updateAuthState(this.targetAuthState, target, credsProvider); if (this.targetAuthState.getCredentials() != null) { // Re-try the same request via the same route return roureq; } else { return null; } } else { // Reset target auth scope this.targetAuthState.setAuthScope(null); } if (this.proxyAuthHandler.isAuthenticationRequested(response, context)) { this.log.debug("Proxy requested authentication"); Map<String, Header> challenges = this.proxyAuthHandler.getChallenges( response, context); try { processChallenges(challenges, this.proxyAuthState, this.proxyAuthHandler, response, context); } catch (AuthenticationException ex) { if (this.log.isWarnEnabled()) { this.log.warn("Authentication error: " + ex.getMessage()); return null; } } updateAuthState(this.proxyAuthState, proxy, credsProvider); if (this.proxyAuthState.getCredentials() != null) { // Re-try the same request via the same route return roureq; } else { return null; } } else { // Reset proxy auth scope this.proxyAuthState.setAuthScope(null); } } return null; } // handleResponse /** * Shuts down the connection. * This method is called from a <code>catch</code> block in * {@link #execute execute} during exception handling. */ private void abortConnection() { ManagedClientConnection mcc = managedConn; if (mcc != null) { // we got here as the result of an exception // no response will be returned, release the connection managedConn = null; try { mcc.abortConnection(); } catch (IOException ex) { if (this.log.isDebugEnabled()) { this.log.debug(ex.getMessage(), ex); } } // ensure the connection manager properly releases this connection try { mcc.releaseConnection(); } catch(IOException ignored) { this.log.debug("Error releasing connection", ignored); } } } // abortConnection private void processChallenges( final Map<String, Header> challenges, final AuthState authState, final AuthenticationHandler authHandler, final HttpResponse response, final HttpContext context) throws MalformedChallengeException, AuthenticationException { AuthScheme authScheme = authState.getAuthScheme(); if (authScheme == null) { // Authentication not attempted before authScheme = authHandler.selectScheme(challenges, response, context); authState.setAuthScheme(authScheme); } String id = authScheme.getSchemeName(); Header challenge = challenges.get(id.toLowerCase(Locale.ENGLISH)); if (challenge == null) { throw new AuthenticationException(id + " authorization challenge expected, but not found"); } authScheme.processChallenge(challenge); this.log.debug("Authorization challenge processed"); } private void updateAuthState( final AuthState authState, final HttpHost host, final CredentialsProvider credsProvider) { if (!authState.isValid()) { return; } String hostname = host.getHostName(); int port = host.getPort(); if (port < 0) { Scheme scheme = connManager.getSchemeRegistry().getScheme(host); port = scheme.getDefaultPort(); } AuthScheme authScheme = authState.getAuthScheme(); AuthScope authScope = new AuthScope( hostname, port, authScheme.getRealm(), authScheme.getSchemeName()); if (this.log.isDebugEnabled()) { this.log.debug("Authentication scope: " + authScope); } Credentials creds = authState.getCredentials(); if (creds == null) { creds = credsProvider.getCredentials(authScope); if (this.log.isDebugEnabled()) { if (creds != null) { this.log.debug("Found credentials"); } else { this.log.debug("Credentials not found"); } } } else { if (authScheme.isComplete()) { this.log.debug("Authentication failed"); creds = null; } } authState.setAuthScope(authScope); authState.setCredentials(creds); } } // class DefaultClientRequestDirector
true
true
public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws HttpException, IOException { HttpRequest orig = request; RequestWrapper origWrapper = wrapRequest(orig); origWrapper.setParams(params); HttpRoute origRoute = determineRoute(target, origWrapper, context); RoutedRequest roureq = new RoutedRequest(origWrapper, origRoute); long timeout = ConnManagerParams.getTimeout(params); int execCount = 0; boolean reuse = false; HttpResponse response = null; boolean done = false; try { while (!done) { // In this loop, the RoutedRequest may be replaced by a // followup request and route. The request and route passed // in the method arguments will be replaced. The original // request is still available in 'orig'. RequestWrapper wrapper = roureq.getRequest(); HttpRoute route = roureq.getRoute(); // See if we have a user token bound to the execution context Object userToken = context.getAttribute(ClientContext.USER_TOKEN); // Allocate connection if needed if (managedConn == null) { ClientConnectionRequest connRequest = connManager.requestConnection( route, userToken); if (orig instanceof AbortableHttpRequest) { ((AbortableHttpRequest) orig).setConnectionRequest(connRequest); } try { managedConn = connRequest.getConnection(timeout, TimeUnit.MILLISECONDS); } catch(InterruptedException interrupted) { InterruptedIOException iox = new InterruptedIOException(); iox.initCause(interrupted); throw iox; } if (HttpConnectionParams.isStaleCheckingEnabled(params)) { // validate connection this.log.debug("Stale connection check"); if (managedConn.isStale()) { this.log.debug("Stale connection detected"); managedConn.close(); } } } if (orig instanceof AbortableHttpRequest) { ((AbortableHttpRequest) orig).setReleaseTrigger(managedConn); } // Reopen connection if needed if (!managedConn.isOpen()) { managedConn.open(route, context, params); } try { establishRoute(route, context); } catch (TunnelRefusedException ex) { if (this.log.isDebugEnabled()) { this.log.debug(ex.getMessage()); } response = ex.getResponse(); break; } // Reset headers on the request wrapper wrapper.resetHeaders(); // Re-write request URI if needed rewriteRequestURI(wrapper, route); // Use virtual host if set target = (HttpHost) wrapper.getParams().getParameter( ClientPNames.VIRTUAL_HOST); if (target == null) { target = route.getTargetHost(); } HttpHost proxy = route.getProxyHost(); // Populate the execution context context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, target); context.setAttribute(ExecutionContext.HTTP_PROXY_HOST, proxy); context.setAttribute(ExecutionContext.HTTP_CONNECTION, managedConn); context.setAttribute(ClientContext.TARGET_AUTH_STATE, targetAuthState); context.setAttribute(ClientContext.PROXY_AUTH_STATE, proxyAuthState); // Run request protocol interceptors requestExec.preProcess(wrapper, httpProcessor, context); context.setAttribute(ExecutionContext.HTTP_REQUEST, wrapper); boolean retrying = true; while (retrying) { // Increment total exec count (with redirects) execCount++; // Increment exec count for this particular request wrapper.incrementExecCount(); if (wrapper.getExecCount() > 1 && !wrapper.isRepeatable()) { throw new NonRepeatableRequestException("Cannot retry request " + "with a non-repeatable request entity"); } try { if (this.log.isDebugEnabled()) { this.log.debug("Attempt " + execCount + " to execute request"); } response = requestExec.execute(wrapper, managedConn, context); retrying = false; } catch (IOException ex) { this.log.debug("Closing the connection."); managedConn.close(); if (retryHandler.retryRequest(ex, execCount, context)) { if (this.log.isInfoEnabled()) { this.log.info("I/O exception ("+ ex.getClass().getName() + ") caught when processing request: " + ex.getMessage()); } if (this.log.isDebugEnabled()) { this.log.debug(ex.getMessage(), ex); } this.log.info("Retrying request"); } else { throw ex; } // If we have a direct route to the target host // just re-open connection and re-try the request if (route.getHopCount() == 1) { this.log.debug("Reopening the direct connection."); managedConn.open(route, context, params); } else { // otherwise give up retrying = false; } } } // Run response protocol interceptors response.setParams(params); requestExec.postProcess(response, httpProcessor, context); // The connection is in or can be brought to a re-usable state. reuse = reuseStrategy.keepAlive(response, context); if(reuse) { // Set the idle duration of this connection long duration = keepAliveStrategy.getKeepAliveDuration(response, context); managedConn.setIdleDuration(duration, TimeUnit.MILLISECONDS); } RoutedRequest followup = handleResponse(roureq, response, context); if (followup == null) { done = true; } else { if (reuse) { this.log.debug("Connection kept alive"); // Make sure the response body is fully consumed, if present HttpEntity entity = response.getEntity(); if (entity != null) { entity.consumeContent(); } // entity consumed above is not an auto-release entity, // need to mark the connection re-usable explicitly managedConn.markReusable(); } else { managedConn.close(); } // check if we can use the same connection for the followup if (!followup.getRoute().equals(roureq.getRoute())) { releaseConnection(); } roureq = followup; } userToken = this.userTokenHandler.getUserToken(context); context.setAttribute(ClientContext.USER_TOKEN, userToken); if (managedConn != null) { managedConn.setState(userToken); } } // while not done // check for entity, release connection if possible if ((response == null) || (response.getEntity() == null) || !response.getEntity().isStreaming()) { // connection not needed and (assumed to be) in re-usable state if (reuse) managedConn.markReusable(); releaseConnection(); } else { // install an auto-release entity HttpEntity entity = response.getEntity(); entity = new BasicManagedEntity(entity, managedConn, reuse); response.setEntity(entity); } return response; } catch (HttpException ex) { abortConnection(); throw ex; } catch (IOException ex) { abortConnection(); throw ex; } catch (RuntimeException ex) { abortConnection(); throw ex; } } // execute
public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws HttpException, IOException { HttpRequest orig = request; RequestWrapper origWrapper = wrapRequest(orig); origWrapper.setParams(params); HttpRoute origRoute = determineRoute(target, origWrapper, context); RoutedRequest roureq = new RoutedRequest(origWrapper, origRoute); long timeout = ConnManagerParams.getTimeout(params); int execCount = 0; boolean reuse = false; HttpResponse response = null; boolean done = false; try { while (!done) { // In this loop, the RoutedRequest may be replaced by a // followup request and route. The request and route passed // in the method arguments will be replaced. The original // request is still available in 'orig'. RequestWrapper wrapper = roureq.getRequest(); HttpRoute route = roureq.getRoute(); // See if we have a user token bound to the execution context Object userToken = context.getAttribute(ClientContext.USER_TOKEN); // Allocate connection if needed if (managedConn == null) { ClientConnectionRequest connRequest = connManager.requestConnection( route, userToken); if (orig instanceof AbortableHttpRequest) { ((AbortableHttpRequest) orig).setConnectionRequest(connRequest); } try { managedConn = connRequest.getConnection(timeout, TimeUnit.MILLISECONDS); } catch(InterruptedException interrupted) { InterruptedIOException iox = new InterruptedIOException(); iox.initCause(interrupted); throw iox; } if (HttpConnectionParams.isStaleCheckingEnabled(params)) { // validate connection this.log.debug("Stale connection check"); if (managedConn.isStale()) { this.log.debug("Stale connection detected"); // BEGIN android-changed try { managedConn.close(); } catch (IOException ignored) { // SSLSocket's will throw IOException // because they can't send a "close // notify" protocol message to the // server. Just supresss any // exceptions related to closing the // stale connection. } // END android-changed } } } if (orig instanceof AbortableHttpRequest) { ((AbortableHttpRequest) orig).setReleaseTrigger(managedConn); } // Reopen connection if needed if (!managedConn.isOpen()) { managedConn.open(route, context, params); } try { establishRoute(route, context); } catch (TunnelRefusedException ex) { if (this.log.isDebugEnabled()) { this.log.debug(ex.getMessage()); } response = ex.getResponse(); break; } // Reset headers on the request wrapper wrapper.resetHeaders(); // Re-write request URI if needed rewriteRequestURI(wrapper, route); // Use virtual host if set target = (HttpHost) wrapper.getParams().getParameter( ClientPNames.VIRTUAL_HOST); if (target == null) { target = route.getTargetHost(); } HttpHost proxy = route.getProxyHost(); // Populate the execution context context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, target); context.setAttribute(ExecutionContext.HTTP_PROXY_HOST, proxy); context.setAttribute(ExecutionContext.HTTP_CONNECTION, managedConn); context.setAttribute(ClientContext.TARGET_AUTH_STATE, targetAuthState); context.setAttribute(ClientContext.PROXY_AUTH_STATE, proxyAuthState); // Run request protocol interceptors requestExec.preProcess(wrapper, httpProcessor, context); context.setAttribute(ExecutionContext.HTTP_REQUEST, wrapper); boolean retrying = true; while (retrying) { // Increment total exec count (with redirects) execCount++; // Increment exec count for this particular request wrapper.incrementExecCount(); if (wrapper.getExecCount() > 1 && !wrapper.isRepeatable()) { throw new NonRepeatableRequestException("Cannot retry request " + "with a non-repeatable request entity"); } try { if (this.log.isDebugEnabled()) { this.log.debug("Attempt " + execCount + " to execute request"); } response = requestExec.execute(wrapper, managedConn, context); retrying = false; } catch (IOException ex) { this.log.debug("Closing the connection."); managedConn.close(); if (retryHandler.retryRequest(ex, execCount, context)) { if (this.log.isInfoEnabled()) { this.log.info("I/O exception ("+ ex.getClass().getName() + ") caught when processing request: " + ex.getMessage()); } if (this.log.isDebugEnabled()) { this.log.debug(ex.getMessage(), ex); } this.log.info("Retrying request"); } else { throw ex; } // If we have a direct route to the target host // just re-open connection and re-try the request if (route.getHopCount() == 1) { this.log.debug("Reopening the direct connection."); managedConn.open(route, context, params); } else { // otherwise give up retrying = false; } } } // Run response protocol interceptors response.setParams(params); requestExec.postProcess(response, httpProcessor, context); // The connection is in or can be brought to a re-usable state. reuse = reuseStrategy.keepAlive(response, context); if(reuse) { // Set the idle duration of this connection long duration = keepAliveStrategy.getKeepAliveDuration(response, context); managedConn.setIdleDuration(duration, TimeUnit.MILLISECONDS); } RoutedRequest followup = handleResponse(roureq, response, context); if (followup == null) { done = true; } else { if (reuse) { this.log.debug("Connection kept alive"); // Make sure the response body is fully consumed, if present HttpEntity entity = response.getEntity(); if (entity != null) { entity.consumeContent(); } // entity consumed above is not an auto-release entity, // need to mark the connection re-usable explicitly managedConn.markReusable(); } else { managedConn.close(); } // check if we can use the same connection for the followup if (!followup.getRoute().equals(roureq.getRoute())) { releaseConnection(); } roureq = followup; } userToken = this.userTokenHandler.getUserToken(context); context.setAttribute(ClientContext.USER_TOKEN, userToken); if (managedConn != null) { managedConn.setState(userToken); } } // while not done // check for entity, release connection if possible if ((response == null) || (response.getEntity() == null) || !response.getEntity().isStreaming()) { // connection not needed and (assumed to be) in re-usable state if (reuse) managedConn.markReusable(); releaseConnection(); } else { // install an auto-release entity HttpEntity entity = response.getEntity(); entity = new BasicManagedEntity(entity, managedConn, reuse); response.setEntity(entity); } return response; } catch (HttpException ex) { abortConnection(); throw ex; } catch (IOException ex) { abortConnection(); throw ex; } catch (RuntimeException ex) { abortConnection(); throw ex; } } // execute
diff --git a/src/com/seanmadden/deepthought/responders/SaluteResponder.java b/src/com/seanmadden/deepthought/responders/SaluteResponder.java index e6f0b3e..c9af3f6 100644 --- a/src/com/seanmadden/deepthought/responders/SaluteResponder.java +++ b/src/com/seanmadden/deepthought/responders/SaluteResponder.java @@ -1,55 +1,59 @@ /* * SaluteResponder.java * * $Id $ * Author: smadden * * Copyright (C) 2010 Sean Madden * * Please see the pertinent documents for licensing information. * */ package com.seanmadden.deepthought.responders; import com.seanmadden.deepthought.IRCClient; import com.seanmadden.deepthought.Message; import com.seanmadden.deepthought.MessageHandler; /** * [Insert class description here] * * @author Sean P Madden */ public class SaluteResponder implements MessageHandler { private static String[] ranks = { "major", "general", "private", "corporal", "chief", "kernel" }; /** * [Place method description here] * * @see com.seanmadden.deepthought.MessageHandler#handleMessage(com.seanmadden.deepthought.IRCClient, com.seanmadden.deepthought.Message) * @param irc * @param m * @return */ @Override public boolean handleMessage(IRCClient irc, Message m) { String message = m.getMessage(); for(String rank : ranks){ if(!message.toLowerCase().contains(rank)){ continue; } int startpos = message.toLowerCase().indexOf(rank) + rank.length(); - String response = message.substring(startpos, message.indexOf(' ', startpos + 1)); + int offset = message.indexOf(' ', startpos + 1); + if(offset < 0){ + offset = message.length(); + } + String response = message.substring(startpos, offset); response = "\u0001ACTION salutes " + rank + " " + response + "\u0001"; Message msg = new Message(response, m.getTarget()); irc.sendMessage(msg); return true; } return false; } }
true
true
public boolean handleMessage(IRCClient irc, Message m) { String message = m.getMessage(); for(String rank : ranks){ if(!message.toLowerCase().contains(rank)){ continue; } int startpos = message.toLowerCase().indexOf(rank) + rank.length(); String response = message.substring(startpos, message.indexOf(' ', startpos + 1)); response = "\u0001ACTION salutes " + rank + " " + response + "\u0001"; Message msg = new Message(response, m.getTarget()); irc.sendMessage(msg); return true; } return false; }
public boolean handleMessage(IRCClient irc, Message m) { String message = m.getMessage(); for(String rank : ranks){ if(!message.toLowerCase().contains(rank)){ continue; } int startpos = message.toLowerCase().indexOf(rank) + rank.length(); int offset = message.indexOf(' ', startpos + 1); if(offset < 0){ offset = message.length(); } String response = message.substring(startpos, offset); response = "\u0001ACTION salutes " + rank + " " + response + "\u0001"; Message msg = new Message(response, m.getTarget()); irc.sendMessage(msg); return true; } return false; }
diff --git a/org.eclipse.gemini.jpa/src/org/eclipse/gemini/jpa/proxy/EMFBuilderServiceProxyHandler.java b/org.eclipse.gemini.jpa/src/org/eclipse/gemini/jpa/proxy/EMFBuilderServiceProxyHandler.java index 4307ffb..529edc8 100644 --- a/org.eclipse.gemini.jpa/src/org/eclipse/gemini/jpa/proxy/EMFBuilderServiceProxyHandler.java +++ b/org.eclipse.gemini.jpa/src/org/eclipse/gemini/jpa/proxy/EMFBuilderServiceProxyHandler.java @@ -1,126 +1,128 @@ /******************************************************************************* * Copyright (c) 2010 Oracle. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * and the Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php. * You may elect to redistribute this code under either of these licenses. * * Contributors: * mkeith - Gemini JPA work ******************************************************************************/ package org.eclipse.gemini.jpa.proxy; import static org.eclipse.gemini.jpa.GeminiUtil.JPA_JDBC_DRIVER_PROPERTY; import static org.eclipse.gemini.jpa.GeminiUtil.JPA_JDBC_URL_PROPERTY; import static org.eclipse.gemini.jpa.GeminiUtil.debug; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import javax.persistence.EntityManagerFactory; import org.eclipse.gemini.jpa.PUnitInfo; /** * Dynamic proxy class to proxy the EMFBuilder service */ @SuppressWarnings({"unchecked"}) public class EMFBuilderServiceProxyHandler extends EMFServiceProxyHandler implements InvocationHandler { // Keep around a copy of the props used to create an EMF through the EMF builder Map<String,Object> emfProps = new HashMap<String,Object>(); public EMFBuilderServiceProxyHandler(PUnitInfo pUnitInfo, EMFServiceProxyHandler emfService) { super(pUnitInfo); } /*=========================*/ /* InvocationProxy methods */ /*=========================*/ // Will only get calls for the method on the EntityManagerFactoryBuilder interface @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { debug("EMFBuilderProxy invocation on method ", method.getName()); if (method.getName().equals("hashCode")) return this.hashCode(); + if (method.getName().equals("equals")) + return this.equals(args[0]); if (method.getName().equals("toString")) return this.toString(); // Must be a createEntityManagerFactory(String, Map) call // The first arg must be the properties Map Map<String,Object> props = (Map<String,Object>)args[0]; // If we have an EMF and it has already been closed, discard it EntityManagerFactory emf; synchronized (pUnitInfo) { emf = pUnitInfo.getEmf(); if ((emf != null) && (!emf.isOpen())) { syncUnsetEMF(); emfProps.clear(); emf = null; } } // Check if an EMF already exists if (emf != null) { // Verify the JDBC properties match the ones that may have been previously passed in verifyJDBCProperties((String) emfProps.get(JPA_JDBC_DRIVER_PROPERTY), (String) emfProps.get(JPA_JDBC_URL_PROPERTY), props); // If it was created using the builder service then just return it if (pUnitInfo.isEmfSetByBuilderService()) { return emf; } // It was created using the EMF service. // Verify the JDBC properties match the ones in the descriptor. verifyJDBCProperties(pUnitInfo.getDriverClassName(), pUnitInfo.getDriverUrl(), props); return emf; } else { // No EMF service existed; create another return syncGetEMFAndSetIfAbsent(true, props); } } /*================*/ /* Helper methods */ /*================*/ public EntityManagerFactory createEMF(Map<String,Object> props) { emfProps = props; return super.createEMF(props); } // Local method to compare properties passed in Map to ones in persistence descriptor or in previously set props protected void verifyJDBCProperties(String driver, String driverUrl, Map<String,Object> props) { if (driver != null) { String propDriver = (String) props.get(JPA_JDBC_DRIVER_PROPERTY); if ((propDriver != null) && !driver.equals(propDriver)) { throw new IllegalArgumentException(); } } if (driverUrl != null) { String propUrl = (String) props.get(JPA_JDBC_URL_PROPERTY); if ((propUrl != null) && !driverUrl.equals(propUrl)) { throw new IllegalArgumentException(); } } } }
true
true
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { debug("EMFBuilderProxy invocation on method ", method.getName()); if (method.getName().equals("hashCode")) return this.hashCode(); if (method.getName().equals("toString")) return this.toString(); // Must be a createEntityManagerFactory(String, Map) call // The first arg must be the properties Map Map<String,Object> props = (Map<String,Object>)args[0]; // If we have an EMF and it has already been closed, discard it EntityManagerFactory emf; synchronized (pUnitInfo) { emf = pUnitInfo.getEmf(); if ((emf != null) && (!emf.isOpen())) { syncUnsetEMF(); emfProps.clear(); emf = null; } } // Check if an EMF already exists if (emf != null) { // Verify the JDBC properties match the ones that may have been previously passed in verifyJDBCProperties((String) emfProps.get(JPA_JDBC_DRIVER_PROPERTY), (String) emfProps.get(JPA_JDBC_URL_PROPERTY), props); // If it was created using the builder service then just return it if (pUnitInfo.isEmfSetByBuilderService()) { return emf; } // It was created using the EMF service. // Verify the JDBC properties match the ones in the descriptor. verifyJDBCProperties(pUnitInfo.getDriverClassName(), pUnitInfo.getDriverUrl(), props); return emf; } else { // No EMF service existed; create another return syncGetEMFAndSetIfAbsent(true, props); } }
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { debug("EMFBuilderProxy invocation on method ", method.getName()); if (method.getName().equals("hashCode")) return this.hashCode(); if (method.getName().equals("equals")) return this.equals(args[0]); if (method.getName().equals("toString")) return this.toString(); // Must be a createEntityManagerFactory(String, Map) call // The first arg must be the properties Map Map<String,Object> props = (Map<String,Object>)args[0]; // If we have an EMF and it has already been closed, discard it EntityManagerFactory emf; synchronized (pUnitInfo) { emf = pUnitInfo.getEmf(); if ((emf != null) && (!emf.isOpen())) { syncUnsetEMF(); emfProps.clear(); emf = null; } } // Check if an EMF already exists if (emf != null) { // Verify the JDBC properties match the ones that may have been previously passed in verifyJDBCProperties((String) emfProps.get(JPA_JDBC_DRIVER_PROPERTY), (String) emfProps.get(JPA_JDBC_URL_PROPERTY), props); // If it was created using the builder service then just return it if (pUnitInfo.isEmfSetByBuilderService()) { return emf; } // It was created using the EMF service. // Verify the JDBC properties match the ones in the descriptor. verifyJDBCProperties(pUnitInfo.getDriverClassName(), pUnitInfo.getDriverUrl(), props); return emf; } else { // No EMF service existed; create another return syncGetEMFAndSetIfAbsent(true, props); } }
diff --git a/src/main/java/de/lemo/dms/connectors/moodleNumericId/ExtractAndMap.java b/src/main/java/de/lemo/dms/connectors/moodleNumericId/ExtractAndMap.java index b88d4607..de56013a 100644 --- a/src/main/java/de/lemo/dms/connectors/moodleNumericId/ExtractAndMap.java +++ b/src/main/java/de/lemo/dms/connectors/moodleNumericId/ExtractAndMap.java @@ -1,1170 +1,1170 @@ /** * File ./main/java/de/lemo/dms/connectors/moodleNumericId/ExtractAndMap.java * Date 2013-01-24 * Project Lemo Learning Analytics */ package de.lemo.dms.connectors.moodleNumericId; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.List; import org.apache.log4j.Logger; import org.hibernate.Query; import org.hibernate.Session; import de.lemo.dms.connectors.IConnector; import de.lemo.dms.core.Clock; import de.lemo.dms.core.config.ServerConfiguration; import de.lemo.dms.db.DBConfigObject; import de.lemo.dms.db.EQueryType; import de.lemo.dms.db.IDBHandler; import de.lemo.dms.db.miningDBclass.AssignmentLogMining; import de.lemo.dms.db.miningDBclass.AssignmentMining; import de.lemo.dms.db.miningDBclass.ChatLogMining; import de.lemo.dms.db.miningDBclass.ChatMining; import de.lemo.dms.db.miningDBclass.ConfigMining; import de.lemo.dms.db.miningDBclass.CourseAssignmentMining; import de.lemo.dms.db.miningDBclass.CourseForumMining; import de.lemo.dms.db.miningDBclass.CourseGroupMining; import de.lemo.dms.db.miningDBclass.CourseLogMining; import de.lemo.dms.db.miningDBclass.CourseMining; import de.lemo.dms.db.miningDBclass.CourseQuizMining; import de.lemo.dms.db.miningDBclass.CourseResourceMining; import de.lemo.dms.db.miningDBclass.CourseScormMining; import de.lemo.dms.db.miningDBclass.CourseUserMining; import de.lemo.dms.db.miningDBclass.CourseWikiMining; import de.lemo.dms.db.miningDBclass.ForumLogMining; import de.lemo.dms.db.miningDBclass.ForumMining; import de.lemo.dms.db.miningDBclass.GroupMining; import de.lemo.dms.db.miningDBclass.GroupUserMining; import de.lemo.dms.db.miningDBclass.LevelAssociationMining; import de.lemo.dms.db.miningDBclass.LevelCourseMining; import de.lemo.dms.db.miningDBclass.LevelMining; import de.lemo.dms.db.miningDBclass.PlatformMining; import de.lemo.dms.db.miningDBclass.QuestionLogMining; import de.lemo.dms.db.miningDBclass.QuestionMining; import de.lemo.dms.db.miningDBclass.QuizLogMining; import de.lemo.dms.db.miningDBclass.QuizMining; import de.lemo.dms.db.miningDBclass.QuizQuestionMining; import de.lemo.dms.db.miningDBclass.QuizUserMining; import de.lemo.dms.db.miningDBclass.ResourceLogMining; import de.lemo.dms.db.miningDBclass.ResourceMining; import de.lemo.dms.db.miningDBclass.RoleMining; import de.lemo.dms.db.miningDBclass.ScormLogMining; import de.lemo.dms.db.miningDBclass.ScormMining; import de.lemo.dms.db.miningDBclass.UserMining; import de.lemo.dms.db.miningDBclass.WikiLogMining; import de.lemo.dms.db.miningDBclass.WikiMining; /** * The main class of the extraction process. * Inherit from this class to make an extract class for a specific LMS. * Contains bundle of fields as container for LMS objects, * which are used for linking the tables. * * @author Benjamin Wolf * @author Sebastian Schwarzrock */ public abstract class ExtractAndMap { // lists of object tables which are new found in LMS DB /** A map containing all CourseMining entries found in the database */ protected Map<Long, CourseMining> courseMining; /** A map containing all PlatformMining entries found in the database */ protected Map<Long, PlatformMining> platformMining; /** A map containing all QuizQuestionMining entries found in the database */ protected Map<Long, QuizQuestionMining> quizQuestionMining; /** A map containing all CourseQuizMining entries found in the database */ protected Map<Long, CourseQuizMining> courseQuizMining; /** A map containing all QuizMining entries found in the database */ protected Map<Long, QuizMining> quizMining; /** A map containing all AssignmentMining entries found in the database */ protected Map<Long, AssignmentMining> assignmentMining; /** A map containing all ScormMining entries found in the database */ protected Map<Long, ScormMining> scormMining; /** A map containing all ForumMining entries found in the database */ protected Map<Long, ForumMining> forumMining; /** A map containing all ResourceMining entries found in the database */ protected Map<Long, ResourceMining> resourceMining; /** A map containing all UserMining entries found in the database */ protected Map<Long, UserMining> userMining; /** A map containing all WikiMining entries found in the database */ protected Map<Long, WikiMining> wikiMining; /** A map containing all GroupMining entries found in the database */ protected Map<Long, GroupMining> groupMining; /** A map containing all QuestionMining entries found in the database */ protected Map<Long, QuestionMining> questionMining; /** A map containing all RoleMining entries found in the database */ protected Map<Long, RoleMining> roleMining; /** A map containing all LevelMining entries found in the database */ protected Map<Long, LevelMining> levelMining; /** A map containing all ChatMining entries found in the database */ protected Map<Long, ChatMining> chatMining; /** A map containing all ChatLogMining entries found in the database */ protected Map<Long, ChatLogMining> chatLogMining; /** A map containing all PlatformMining entries found in the mining-database */ protected Map<Long, PlatformMining> oldPlatformMining; /** A map containing all CourseMining entries found in the mining-database */ protected Map<Long, CourseMining> oldCourseMining; /** A map containing all QuizMining entries found in the mining-database */ protected Map<Long, QuizMining> oldQuizMining; /** A map containing all AssignmentMining entries found in the mining-database */ protected Map<Long, AssignmentMining> oldAssignmentMining; /** A map containing all ScormMining entries found in the mining-database */ protected Map<Long, ScormMining> oldScormMining; /** A map containing all ForumMining entries found in the mining-database */ protected Map<Long, ForumMining> oldForumMining; /** A map containing all ResourceMining entries found in the mining-database */ protected Map<Long, ResourceMining> oldResourceMining; /** A map containing all UserMining entries found in the mining-database */ protected Map<Long, UserMining> oldUserMining; /** A map containing all WikiMining entries found in the mining-database */ protected Map<Long, WikiMining> oldWikiMining; /** A map containing all GroupMining entries found in the mining-database */ protected Map<Long, GroupMining> oldGroupMining; /** A map containing all QuestionMining entries found in the mining-database */ protected Map<Long, QuestionMining> oldQuestionMining; /** A map containing all RoleMining entries found in the mining-database */ protected Map<Long, RoleMining> oldRoleMining; /** A map containing all QuizQuestionMining entries found in the mining-database */ protected Map<Long, QuizQuestionMining> oldQuizQuestionMining; /** A map containing all CourseQuizMining entries found in the mining-database */ protected Map<Long, CourseQuizMining> oldCourseQuizMining; /** A map containing all LevelMining entries found in the mining-database */ protected Map<Long, LevelMining> oldLevelMining; /** A map containing all ChatMining entries found in the mining-database */ protected Map<Long, ChatMining> oldChatMining; /** A map containing all ChatLogMining entries found in the mining-database */ protected Map<Long, ChatLogMining> oldChatLogMining; /** A list of objects used for submitting them to the DB. */ protected List<Collection<?>> updates; /** A list of time stamps of the previous runs of the extractor. */ protected List<Timestamp> configMiningTimestamp; /** value of the highest user-id in the data set. Used for creating new numeric ids **/ protected long largestId; /** Designates which entries should be read from the LMS Database during the process. */ private long starttime; private IDBHandler dbHandler; private final Logger logger = Logger.getLogger(this.getClass()); private Clock c; protected Long resourceLogMax; protected Long chatLogMax; protected Long assignmentLogMax; protected Long courseLogMax; protected Long forumLogMax; protected Long questionLogMax; protected Long quizLogMax; protected Long scormLogMax; protected Long wikiLogMax; private final IConnector connector; public ExtractAndMap(final IConnector connector) { this.connector = connector; } /** * Starts the extraction process by calling getLMS_tables() and saveMining_tables(). * A time stamp can be given as optional argument. * When the argument is used the extraction begins after that time stamp. * When no argument is given the program starts with the time stamp of the last run. * * @param args * Optional arguments for the process. Used for the selection of the ExtractAndMap Implementation and * time stamp when the extraction should start. **/ public void start(final String[] args, final DBConfigObject sourceDBConf) { this.dbHandler = ServerConfiguration.getInstance().getMiningDbHandler(); this.c = new Clock(); this.starttime = System.currentTimeMillis() / 1000; final Session session = this.dbHandler.getMiningSession(); // get the status of the mining DB; load timestamp of last update and objects needed for associations long readingtimestamp = this.getMiningInitial(); this.dbHandler.saveToDB(session, new PlatformMining(this.connector.getPlatformId(), this.connector.getName(), this.connector.getPlattformType().toString(), this.connector.getPrefix())); logger.info("Initialized database in " + this.c.getAndReset()); // default call without parameter if (args.length == 1) { // get the needed tables from LMS DB this.c.reset(); this.getLMStables(sourceDBConf, readingtimestamp); logger.info("Loaded data from source in " + this.c.getAndReset()); // create and write the mining database tables this.saveMiningTables(); } // call with parameter timestamp else { if (args[1].matches("[0-9]+")) { readingtimestamp = Long.parseLong(args[1]); long readingtimestamp2 = Long.parseLong(args[1]) + 172800; final long currenttimestamp = this.starttime; this.logger.info("starttime:" + currenttimestamp); this.logger.info("parameter:" + readingtimestamp); // first read & save LMS DB tables from 0 to starttime for timestamps which are not set(which are 0) if (this.configMiningTimestamp.get(0) == null) { this.c.reset(); this.getLMStables(sourceDBConf, 0, readingtimestamp); logger.info("Loaded data from source in " + this.c.getAndReset()); // create and write the mining database tables this.saveMiningTables(); } // read & save LMS DB in steps of 2 days for (long looptimestamp = readingtimestamp - 1; looptimestamp < currenttimestamp;) { this.logger.info("looptimestamp:" + looptimestamp); this.c.reset(); this.getLMStables(sourceDBConf, looptimestamp + 1, readingtimestamp2); logger.info("Loaded data from source in " + this.c.getAndReset()); looptimestamp += 172800; readingtimestamp2 += 172800; this.logger.info("currenttimestamp:" + currenttimestamp); this.saveMiningTables(); this.prepareMiningData(); this.clearMiningTables(); } } else { // Fehlermeldung Datenformat this.logger.info("wrong data format in parameter:" + args[1]); } } // calculate running time of extract process final long endtime = System.currentTimeMillis() / 1000; final ConfigMining config = new ConfigMining(); config.setLastModifiedLong(System.currentTimeMillis()); config.setElapsedTime((endtime) - (this.starttime)); config.setDatabaseModel("1.2"); config.setPlatform(this.connector.getPlatformId()); this.dbHandler.saveToDB(session, config); this.logger.info("Elapsed time: " + (endtime - this.starttime) + "s"); this.dbHandler.closeSession(session); } /** * Reads the Mining Database. * Initial informations needed to start the process of updating are collected here. * The time stamp of the last run of the extractor is read from the config table * and the objects which might been needed to associate are read and saved here. * * @return The time stamp of the last run of the extractor. If this is the first run it will be set 0. **/ @SuppressWarnings("unchecked") public long getMiningInitial() { // open a DB connection final Session session = this.dbHandler.getMiningSession(); List<?> t; t = this.dbHandler.performQuery(session, EQueryType.HQL, "from PlatformMining x order by x.id asc"); this.oldPlatformMining = new HashMap<Long, PlatformMining>(); if (t != null) { for (int i = 0; i < t.size(); i++) { this.oldPlatformMining.put(((PlatformMining) (t.get(i))).getId(), (PlatformMining) t.get(i)); } } logger.info("Loaded " + this.oldPlatformMining.size() + " PlatformMining objects from the mining database."); this.platformMining = new HashMap<Long, PlatformMining>(); this.configMiningTimestamp = this.dbHandler.getMiningSession() - .createQuery("select max(lastModified) from ConfigMining x order by x.id asc").list(); + .createQuery("select max(lastModified) from ConfigMining x where x.platform="+ this.connector.getPlatformId() + " order by x.id asc").list(); if (this.configMiningTimestamp.get(0) == null) { this.configMiningTimestamp.set(0, new Timestamp(0)); } final long readingtimestamp = this.configMiningTimestamp.get(0).getTime(); // load objects which are already in Mining DB for associations Query logCount = session.createQuery("select max(id) from ResourceLogMining where platform=" + this.connector.getPlatformId()); this.resourceLogMax = ((ArrayList<Long>) logCount.list()).get(0); if (this.resourceLogMax == null) { this.resourceLogMax = 0L; } logCount = session.createSQLQuery("select max(id) from chat_log where platform=" + this.connector.getPlatformId()); this.chatLogMax = ((ArrayList<Long>) logCount.list()).get(0); if (this.chatLogMax == null) { this.chatLogMax = 0L; } logCount = session.createSQLQuery("select max(id) from assignment_log where platform=" + this.connector.getPlatformId()); this.assignmentLogMax = ((ArrayList<Long>) logCount.list()).get(0); if (this.assignmentLogMax == null) { this.assignmentLogMax = 0L; } logCount = session.createSQLQuery("select max(id) from course_log where platform=" + this.connector.getPlatformId()); this.courseLogMax = ((ArrayList<Long>) logCount.list()).get(0); if (this.courseLogMax == null) { this.courseLogMax = 0L; } logCount = session.createSQLQuery("select max(id) from forum_log where platform=" + this.connector.getPlatformId()); this.forumLogMax = ((ArrayList<Long>) logCount.list()).get(0); if (this.forumLogMax == null) { this.forumLogMax = 0L; } logCount = session.createSQLQuery("select max(id) from question_log where platform=" + this.connector.getPlatformId()); this.questionLogMax = ((ArrayList<Long>) logCount.list()).get(0); if (this.questionLogMax == null) { this.questionLogMax = 0L; } logCount = session.createSQLQuery("select max(id) from quiz_log where platform=" + this.connector.getPlatformId()); this.quizLogMax = ((ArrayList<Long>) logCount.list()).get(0); if (this.quizLogMax == null) { this.quizLogMax = 0L; } logCount = session.createSQLQuery("select max(id) from scorm_log where platform=" + this.connector.getPlatformId()); this.scormLogMax = ((ArrayList<Long>) logCount.list()).get(0); if (this.scormLogMax == null) { this.scormLogMax = 0L; } logCount = session.createSQLQuery("select max(id) from wiki_log where platform=" + this.connector.getPlatformId()); this.wikiLogMax = ((ArrayList<Long>) logCount.list()).get(0); if (this.wikiLogMax == null) { this.wikiLogMax = 0L; } t = this.dbHandler.performQuery(session, EQueryType.HQL, "from CourseMining x where x.platform=" + this.connector.getPlatformId() + " order by x.id asc"); this.oldCourseMining = new HashMap<Long, CourseMining>(); for (int i = 0; i < t.size(); i++) { this.oldCourseMining.put(((CourseMining) (t.get(i))).getId(), (CourseMining) t.get(i)); } logger.info("Loaded " + this.oldCourseMining.size() + " CourseMining objects from the mining database."); t = this.dbHandler.performQuery(session, EQueryType.HQL, "from QuizMining x where x.platform=" + this.connector.getPlatformId() + " order by x.id asc"); this.oldQuizMining = new HashMap<Long, QuizMining>(); for (int i = 0; i < t.size(); i++) { this.oldQuizMining.put(((QuizMining) (t.get(i))).getId(), (QuizMining) t.get(i)); } logger.info("Loaded " + this.oldQuizMining.size() + " QuizMining objects from the mining database."); t = this.dbHandler.performQuery(session, EQueryType.HQL, "from AssignmentMining x where x.platform=" + this.connector.getPlatformId() + " order by x.id asc"); this.oldAssignmentMining = new HashMap<Long, AssignmentMining>(); for (int i = 0; i < t.size(); i++) { this.oldAssignmentMining.put(((AssignmentMining) (t.get(i))).getId(), (AssignmentMining) t.get(i)); } logger.info("Loaded " + this.oldAssignmentMining.size() + " AssignmentMining objects from the mining database."); t = this.dbHandler.performQuery(session, EQueryType.HQL, "from ScormMining x where x.platform=" + this.connector.getPlatformId() + " order by x.id asc"); this.oldScormMining = new HashMap<Long, ScormMining>(); for (int i = 0; i < t.size(); i++) { this.oldScormMining.put(((ScormMining) (t.get(i))).getId(), (ScormMining) t.get(i)); } logger.info("Loaded " + this.oldScormMining.size() + " ScormMining objects from the mining database."); t = this.dbHandler.performQuery(session, EQueryType.HQL, "from ForumMining x where x.platform=" + this.connector.getPlatformId() + " order by x.id asc"); this.oldForumMining = new HashMap<Long, ForumMining>(); for (int i = 0; i < t.size(); i++) { this.oldForumMining.put(((ForumMining) (t.get(i))).getId(), (ForumMining) t.get(i)); } logger.info("Loaded " + this.oldForumMining.size() + " ForumMining objects from the mining database."); t = this.dbHandler.performQuery(session, EQueryType.HQL, "from ResourceMining x where x.platform=" + this.connector.getPlatformId() + " order by x.id asc"); this.oldResourceMining = new HashMap<Long, ResourceMining>(); for (int i = 0; i < t.size(); i++) { this.oldResourceMining.put(((ResourceMining) (t.get(i))).getId(), (ResourceMining) t.get(i)); } logger.info("Loaded " + this.oldResourceMining.size() + " ResourceMining objects from the mining database."); t = this.dbHandler.performQuery(session, EQueryType.HQL, "from UserMining x where x.platform=" + this.connector.getPlatformId() + " order by x.id asc"); this.oldUserMining = new HashMap<Long, UserMining>(); for (int i = 0; i < t.size(); i++) { this.oldUserMining.put(((UserMining) (t.get(i))).getId(), (UserMining) t.get(i)); } logger.info("Loaded " + this.oldUserMining.size() + " UserMining objects from the mining database."); t = this.dbHandler.performQuery(session, EQueryType.HQL, "from WikiMining x where x.platform=" + this.connector.getPlatformId() + " order by x.id asc"); this.oldWikiMining = new HashMap<Long, WikiMining>(); for (int i = 0; i < t.size(); i++) { this.oldWikiMining.put(((WikiMining) (t.get(i))).getId(), (WikiMining) t.get(i)); } logger.info("Loaded " + this.oldWikiMining.size() + " WikiMining objects from the mining database."); t = this.dbHandler.performQuery(session, EQueryType.HQL, "from GroupMining x where x.platform=" + this.connector.getPlatformId() + " order by x.id asc"); this.oldGroupMining = new HashMap<Long, GroupMining>(); for (int i = 0; i < t.size(); i++) { this.oldGroupMining.put(((GroupMining) (t.get(i))).getId(), (GroupMining) t.get(i)); } logger.info("Loaded " + this.oldGroupMining.size() + " GroupMining objects from the mining database."); t = this.dbHandler.performQuery(session, EQueryType.HQL, "from QuestionMining x where x.platform=" + this.connector.getPlatformId() + " order by x.id asc"); this.oldQuestionMining = new HashMap<Long, QuestionMining>(); for (int i = 0; i < t.size(); i++) { this.oldQuestionMining.put(((QuestionMining) (t.get(i))).getId(), (QuestionMining) t.get(i)); } logger.info("Loaded " + this.oldQuizMining.size() + " QuestionMining objects from the mining database."); t = this.dbHandler.performQuery(session, EQueryType.HQL, "from RoleMining x where x.platform=" + this.connector.getPlatformId() + " order by x.id asc"); this.oldRoleMining = new HashMap<Long, RoleMining>(); for (int i = 0; i < t.size(); i++) { this.oldRoleMining.put(((RoleMining) (t.get(i))).getId(), (RoleMining) t.get(i)); } logger.info("Loaded " + this.oldRoleMining.size() + " RoleMining objects from the mining database."); t = this.dbHandler.performQuery(session, EQueryType.HQL, "from QuizQuestionMining x where x.platform=" + this.connector.getPlatformId() + " order by x.id asc"); this.oldQuizQuestionMining = new HashMap<Long, QuizQuestionMining>(); for (int i = 0; i < t.size(); i++) { this.oldQuizQuestionMining.put(((QuizQuestionMining) (t.get(i))).getId(), (QuizQuestionMining) t.get(i)); } logger.info("Loaded " + this.oldQuizQuestionMining.size() + " QuizQuestionMining objects from the mining database."); t = this.dbHandler.performQuery(session, EQueryType.HQL, "from LevelMining x where x.platform=" + this.connector.getPlatformId() + " order by x.id asc"); this.oldLevelMining = new HashMap<Long, LevelMining>(); for (int i = 0; i < t.size(); i++) { this.oldLevelMining.put(((LevelMining) (t.get(i))).getId(), (LevelMining) t.get(i)); } logger.info("Loaded " + this.oldLevelMining.size() + " LevelMining objects from the mining database."); t = this.dbHandler.performQuery(session, EQueryType.HQL, "from ChatMining x where x.platform=" + this.connector.getPlatformId() + " order by x.id asc"); this.oldChatMining = new HashMap<Long, ChatMining>(); for (int i = 0; i < t.size(); i++) { this.oldChatMining.put(((ChatMining) (t.get(i))).getId(), (ChatMining) t.get(i)); } logger.info("Loaded " + this.oldChatMining.size() + " ChatMining objects from the mining database."); this.dbHandler.closeSession(session); return readingtimestamp; } /** * Has to read the LMS Database. * It starts reading elements with time stamp readingtimestamp and higher. * It is supposed to be used for frequently and small updates. * For a greater Mass of Data it is suggested to use getLMS_tables(long, long); * If Hibernate is used to access the LMS DB too, * it is suggested to write the found tables into lists of * Hibernate object model classes, which have to * be created as global variables in this class. * So they can be used in the generate methods of this class. * * @param readingfromtimestamp * Only elements with time stamp readingtimestamp and higher are read here. * * * @return the lM stables */ public abstract void getLMStables(DBConfigObject dbConf, long readingfromtimestamp); /** * Has to read the LMS Database. * It reads elements with time stamp between readingfromtimestamp and readingtotimestamp. * This method is used to read great DB in a step by step procedure. * That is necessary for a great mass of Data when handling an existing DB for example. * If Hibernate is used to access the LMS DB too, * it is suggested to write the found tables into lists of * Hibernate object model classes, which have to * be created as global variables in this class. * So they can be used in the generate methods of this class. * * @param readingfromtimestamp * Only elements with time stamp readingfromtimestamp and higher are read here. * @param readingtotimestamp * Only elements with time stamp readingtotimestamp and lower are read here. * * * @return the lM stables */ public abstract void getLMStables(DBConfigObject dbConf, long readingfromtimestamp, long readingtotimestamp); /** * Has to clear the lists of LMS tables*. */ public abstract void clearLMStables(); /** * Clears the lists of mining tables. **/ public void clearMiningTables() { this.courseMining.clear(); this.quizMining.clear(); this.assignmentMining.clear(); this.scormMining.clear(); this.forumMining.clear(); this.resourceMining.clear(); this.userMining.clear(); this.wikiMining.clear(); this.groupMining.clear(); this.questionMining.clear(); this.roleMining.clear(); this.levelMining.clear(); this.chatMining.clear(); this.chatMining.clear(); } /** * Only for successive readings. This is meant to be done, when the gathered mining data has already * been saved and before the mining tables are cleared for the next iteration. */ public void prepareMiningData() { this.oldCourseMining.putAll(this.courseMining); this.oldQuizMining.putAll(this.quizMining); this.oldAssignmentMining.putAll(this.assignmentMining); this.oldScormMining.putAll(this.scormMining); this.oldForumMining.putAll(this.forumMining); this.oldResourceMining.putAll(this.resourceMining); this.oldUserMining.putAll(this.userMining); this.oldWikiMining.putAll(this.wikiMining); this.oldGroupMining.putAll(this.groupMining); this.oldQuestionMining.putAll(this.questionMining); this.oldRoleMining.putAll(this.roleMining); this.oldLevelMining.putAll(this.levelMining); this.oldChatMining.putAll(this.chatMining); this.oldQuizQuestionMining.putAll(this.quizQuestionMining); this.oldCourseQuizMining.putAll(this.courseQuizMining); } /** * Generates and save the new tables for the mining DB. * We call the generate-methods for each mining table to get the new entries. * At last we create a Transaction and save the new entries to the DB. **/ public void saveMiningTables() { // generate & save new mining tables this.updates = new ArrayList<Collection<?>>(); Long objects = 0L; // generate mining tables if (this.userMining == null) { this.c.reset(); logger.info("\nObject tables:\n"); this.assignmentMining = this.generateAssignmentMining(); objects += this.assignmentMining.size(); logger.info("Generated " + this.assignmentMining.size() + " AssignmentMining entries in " + this.c.getAndReset() + " s. "); this.updates.add(this.assignmentMining.values()); // Screwing up the alphabetical order, CourseMinings have to be calculated BEFORE ChatMinings due to the // temporal foreign key "course" in ChatMining this.courseMining = this.generateCourseMining(); objects += this.courseMining.size(); logger.info("Generated " + this.courseMining.size() + " CourseMining entries in " + this.c.getAndReset() + " s. "); this.updates.add(this.courseMining.values()); this.chatMining = this.generateChatMining(); objects += this.chatMining.size(); this.updates.add(this.chatMining.values()); logger.info("Generated " + this.chatMining.size() + " ChatMining entries in " + this.c.getAndReset() + " s. "); this.levelMining = this.generateLevelMining(); objects += this.levelMining.size(); logger.info("Generated " + this.levelMining.size() + " LevelMining entries in " + this.c.getAndReset() + " s. "); this.updates.add(this.levelMining.values()); this.forumMining = this.generateForumMining(); objects += this.forumMining.size(); logger.info("Generated " + this.forumMining.size() + " ForumMining entries in " + this.c.getAndReset() + " s. "); this.updates.add(this.forumMining.values()); this.groupMining = this.generateGroupMining(); objects += this.groupMining.size(); logger.info("Generated " + this.groupMining.size() + " GroupMining entries in " + this.c.getAndReset() + " s. "); this.updates.add(this.groupMining.values()); this.questionMining = this.generateQuestionMining(); objects += this.questionMining.size(); logger.info("Generated " + this.questionMining.size() + " QuestionMining entries in " + this.c.getAndReset() + " s. "); this.updates.add(this.questionMining.values()); this.quizMining = this.generateQuizMining(); objects += this.quizMining.size(); this.updates.add(this.quizMining.values()); logger.info("Generated " + this.quizMining.size() + " QuizMining entries in " + this.c.getAndReset() + " s. "); this.resourceMining = this.generateResourceMining(); objects += this.resourceMining.size(); logger.info("Generated " + this.resourceMining.size() + " ResourceMining entries in " + this.c.getAndReset() + " s. "); this.updates.add(this.resourceMining.values()); this.roleMining = this.generateRoleMining(); objects += this.roleMining.size(); logger.info("Generated " + this.roleMining.size() + " RoleMining entries in " + this.c.getAndReset() + " s. "); this.updates.add(this.roleMining.values()); this.scormMining = this.generateScormMining(); objects += this.scormMining.size(); logger.info("Generated " + this.scormMining.size() + " ScormMining entries in " + this.c.getAndReset() + " s. "); this.updates.add(this.scormMining.values()); this.userMining = this.generateUserMining(); objects += this.userMining.size(); logger.info("Generated " + this.userMining.size() + " UserMining entries in " + this.c.getAndReset() + " s. "); this.updates.add(this.userMining.values()); this.wikiMining = this.generateWikiMining(); objects += this.wikiMining.size(); logger.info("Generated " + this.wikiMining.size() + " WikiMining entries in " + this.c.getAndReset() + " s. "); this.updates.add(this.wikiMining.values()); this.updates.add(this.generateCourseAssignmentMining().values()); objects += this.updates.get(this.updates.size() - 1).size(); logger.info("Generated " + this.updates.get(this.updates.size() - 1).size() + " CourseAssignmentMining entries in " + this.c.getAndReset() + " s. "); this.updates.add(this.generateCourseScormMining().values()); objects += this.updates.get(this.updates.size() - 1).size(); logger.info("Generated " + this.updates.get(this.updates.size() - 1).size() + " CourseScormMining entries in " + this.c.getAndReset() + " s. "); this.updates.add(this.generateLevelAssociationMining().values()); objects += this.updates.get(this.updates.size() - 1).size(); logger.info("Generated " + this.updates.get(this.updates.size() - 1).size() + " LevelAssociationMining entries in " + this.c.getAndReset() + " s. "); this.updates.add(this.generateLevelCourseMining().values()); objects += this.updates.get(this.updates.size() - 1).size(); logger.info("Generated " + this.updates.get(this.updates.size() - 1).size() + " LevelCourseMining entries in " + this.c.getAndReset() + " s. "); this.quizQuestionMining = this.generateQuizQuestionMining(); objects += this.quizQuestionMining.size(); logger.info("Generated " + this.updates.get(this.updates.size() - 1).size() + " QuizQuestionMining entries in " + this.c.getAndReset() + " s. "); this.updates.add(this.quizQuestionMining.values()); this.updates.add(this.generateCourseGroupMining().values()); objects += this.updates.get(this.updates.size() - 1).size(); logger.info("Generated " + this.updates.get(this.updates.size() - 1).size() + " CourseGroupMining entries in " + this.c.getAndReset() + " s. "); this.courseQuizMining = this.generateCourseQuizMining(); objects += this.courseQuizMining.size(); logger.info("Generated " + this.updates.get(this.updates.size() - 1).size() + " CourseQuizMining entries in " + this.c.getAndReset() + " s. "); this.updates.add(this.courseQuizMining.values()); this.updates.add(this.generateCourseResourceMining().values()); objects += this.updates.get(this.updates.size() - 1).size(); logger.info("Generated " + this.updates.get(this.updates.size() - 1).size() + " CourseResourceMining entries in " + this.c.getAndReset() + " s. "); this.updates.add(this.generateCourseWikiMining().values()); objects += this.updates.get(this.updates.size() - 1).size(); logger.info("Generated " + this.updates.get(this.updates.size() - 1).size() + " CourseWikiMining entries in " + this.c.getAndReset() + " s. "); } this.updates.add(this.generateGroupUserMining().values()); objects += this.updates.get(this.updates.size() - 1).size(); logger.info("Generated " + this.updates.get(this.updates.size() - 1).size() + " GroupUserMining entries in " + this.c.getAndReset() + " s. "); this.updates.add(this.generateQuizUserMining().values()); objects += this.updates.get(this.updates.size() - 1).size(); logger.info("Generated " + this.updates.get(this.updates.size() - 1).size() + " QuizUserMining entries in " + this.c.getAndReset() + " s. "); this.updates.add(this.generateCourseUserMining().values()); objects += this.updates.get(this.updates.size() - 1).size(); logger.info("Generated " + this.updates.get(this.updates.size() - 1).size() + " CourseUserMining entries in " + this.c.getAndReset() + " s. "); logger.info("\nLog tables:\n"); this.updates.add(this.generateAssignmentLogMining().values()); objects += this.updates.get(this.updates.size() - 1).size(); logger.info("Generated " + this.updates.get(this.updates.size() - 1).size() + " AssignmentLogMining entries in " + this.c.getAndReset() + " s. "); this.updates.add(this.generateChatLogMining().values()); objects += this.updates.get(this.updates.size() - 1).size(); logger.info("Generated " + this.updates.get(this.updates.size() - 1).size() + " ChatLogMining entries in " + this.c.getAndReset() + " s. "); this.updates.add(this.generateCourseLogMining().values()); objects += this.updates.get(this.updates.size() - 1).size(); logger.info("Generated " + this.updates.get(this.updates.size() - 1).size() + " CourseLogMining entries in " + this.c.getAndReset() + " s. "); this.updates.add(this.generateForumLogMining().values()); objects += this.updates.get(this.updates.size() - 1).size(); logger.info("Generated " + this.updates.get(this.updates.size() - 1).size() + " ForumLogMining entries in " + this.c.getAndReset() + " s. "); this.updates.add(this.generateQuestionLogMining().values()); objects += this.updates.get(this.updates.size() - 1).size(); logger.info("Generated " + this.updates.get(this.updates.size() - 1).size() + " QuestionLogMining entries in " + this.c.getAndReset() + " s. "); this.updates.add(this.generateQuizLogMining().values()); objects += this.updates.get(this.updates.size() - 1).size(); logger.info("Generated " + this.updates.get(this.updates.size() - 1).size() + " QuizLogMining entries in " + this.c.getAndReset() + " s. "); this.updates.add(this.generateResourceLogMining().values()); objects += this.updates.get(this.updates.size() - 1).size(); logger.info("Generated " + this.updates.get(this.updates.size() - 1).size() + " ResourceLogMining entries in " + this.c.getAndReset() + " s. "); this.updates.add(this.generateScormLogMining().values()); objects += this.updates.get(this.updates.size() - 1).size(); logger.info("Generated " + this.updates.get(this.updates.size() - 1).size() + " ScormLogMining entries in " + this.c.getAndReset() + " s. "); this.updates.add(this.generateWikiLogMining().values()); objects += this.updates.get(this.updates.size() - 1).size(); logger.info("Generated " + this.updates.get(this.updates.size() - 1).size() + " WikiLogMining entries in " + this.c.getAndReset() + " s. "); if (objects > 0) { final Session session = this.dbHandler.getMiningSession(); logger.info("Writing to DB"); this.dbHandler.saveCollectionToDB(session, this.updates); } this.clearLMStables(); this.updates.clear(); } // methods for create and fill the mining-table instances /** * Has to create and fill the course_user table. * This table describes which user is enrolled in which course in which time span. * The attributes are described in the documentation of the course_user_mining class. * Please use the getter and setter predefined in the course_user_mining class to fill the tables within this * method. * * @return A list of instances of the course_user table representing class. **/ abstract Map<Long, CourseUserMining> generateCourseUserMining(); /** * Has to create and fill the course_forum table. * This table describes which forum is used in which course. * The attributes are described in the documentation of the course_forum_mining class. * Please use the getter and setter predefined in the course_forum_mining class to fill the tables within this * method. * * @return A list of instances of the course_forum table representing class. **/ abstract Map<Long, CourseForumMining> generateCourseForumMining(); /** * Has to create and fill the course table. * This table describes the courses in the LMS. * The attributes are described in the documentation of the course_mining class. * Please use the getter and setter predefined in the course_mining class to fill the tables within this method. * * @return A list of instances of the course table representing class. **/ abstract Map<Long, CourseMining> generateCourseMining(); /** * Has to create and fill the course_group table. * This table describes which groups are used in which courses. * The attributes are described in the documentation of the course_group_mining class. * Please use the getter and setter predefined in the course_group_mining class to fill the tables within this * method. * * @return A list of instances of the course_group table representing class. **/ abstract Map<Long, CourseGroupMining> generateCourseGroupMining(); /** * Has to create and fill the course_quiz table. * This table describes which quiz are used in which courses. * The attributes are described in the documentation of the course_quiz_mining class. * Please use the getter and setter predefined in the course_quiz_mining class to fill the tables within this * method. * * @return A list of instances of the course_quiz table representing class. **/ abstract Map<Long, CourseQuizMining> generateCourseQuizMining(); /** * Has to create and fill the course_assignment table. * This table describes which assignment are used in which courses. * The attributes are described in the documentation of the course_assignment_mining class. * Please use the getter and setter predefined in the course_assignment_mining class to fill the tables within this * method. * * @return A list of instances of the course_assignment table representing class. **/ abstract Map<Long, CourseAssignmentMining> generateCourseAssignmentMining(); /** * Has to create and fill the course_scorm table. * This table describes which scorm packages are used in which courses. * The attributes are described in the documentation of the course_scorm_mining class. * Please use the getter and setter predefined in the course_scorm_mining class to fill the tables within this * method. * * @return A list of instances of the course_scorm table representing class. **/ abstract Map<Long, CourseScormMining> generateCourseScormMining(); /** * Has to create and fill the course_resource table. * This table describes which resources are used in which courses. * The attributes are described in the documentation of the course_resource_mining class. * Please use the getter and setter predefined in the course_resource_mining class to fill the tables within this * method. * * @return A list of instances of the course_resource table representing class. **/ abstract Map<Long, CourseResourceMining> generateCourseResourceMining(); /** * Has to create and fill the course_log table. * This table contains the actions which are done on courses. * The attributes are described in the documentation of the course_log_mining class. * Please use the getter and setter predefined in the course_log_mining class to fill the tables within this method. * * @return A list of instances of the course_log table representing class. **/ abstract Map<Long, CourseLogMining> generateCourseLogMining(); /** * Has to create and fill the course_wiki table. * This table describes which wikis are used in which courses. * The attributes are described in the documentation of the course_wiki_mining class. * Please use the getter and setter predefined in the course_wiki_mining class to fill the tables within this * method. * * @return A list of instances of the course_wiki table representing class. **/ abstract Map<Long, CourseWikiMining> generateCourseWikiMining(); /** * Has to create and fill the forum_log table. * This table contains the actions which are done on forums. * The attributes are described in the documentation of the forum_log_mining class. * Please use the getter and setter predefined in the forum_log_mining class to fill the tables within this method. * * @return A list of instances of the forum_log table representing class. **/ abstract Map<Long, ForumLogMining> generateForumLogMining(); /** * Has to create and fill the forum table. * This table describes the forums in the LMS. * The attributes are described in the documentation of the forum_mining class. * Please use the getter and setter predefined in the forum_mining class to fill the tables within this method. * * @return A list of instances of the forum table representing class. **/ abstract Map<Long, ForumMining> generateForumMining(); /** * Has to create and fill the group_user table. * This table describes which user are in which groups. * The attributes are described in the documentation of the group_user_mining class. * Please use the getter and setter predefined in the group_user_mining class to fill the tables within this method. * * @return A list of instances of the group_user table representing class. **/ abstract Map<Long, GroupUserMining> generateGroupUserMining(); /** * Has to create and fill the group table. * This table describes the groups in the LMS. * The attributes are described in the documentation of the group_mining class. * Please use the getter and setter predefined in the group_mining class to fill the tables within this method. * * @return A list of instances of the group table representing class. **/ abstract Map<Long, GroupMining> generateGroupMining(); /** * Has to create and fill the question_log table. * This table contains the actions which are done on questions. * The attributes are described in the documentation of the question_log_mining class. * Please use the getter and setter predefined in the question_log_mining class to fill the tables within this * method. * * @return A list of instances of the question_log table representing class. **/ abstract Map<Long, QuestionLogMining> generateQuestionLogMining(); /** * Has to create and fill the quiz_log table. * This table contains the actions which are done on quiz. * The attributes are described in the documentation of the quiz_log_mining class. * Please use the getter and setter predefined in the quiz_log_mining class to fill the tables within this method. * * @return A list of instances of the quiz_log table representing class. **/ abstract Map<Long, QuizLogMining> generateQuizLogMining(); /** * Has to create and fill the assignment_log table. * This table contains the actions which are done on assignment. * The attributes are described in the documentation of the assignment_log_mining class. * Please use the getter and setter predefined in the assignment_log_mining class to fill the tables within this * method. * * @return A list of instances of the assignment_log table representing class. **/ abstract Map<Long, AssignmentLogMining> generateAssignmentLogMining(); /** * Has to create and fill the scorm_log table. * This table contains the actions which are done on scorm. * The attributes are described in the documentation of the scorm_log_mining class. * Please use the getter and setter predefined in the scorm_log_mining class to fill the tables within this method. * * @return A list of instances of the scorm_log table representing class. **/ abstract Map<Long, ScormLogMining> generateScormLogMining(); /** * Has to create and fill the quiz_user table. * This table describes which user gets which grade in which quiz. * The attributes are described in the documentation of the quiz_user_mining class. * Please use the getter and setter predefined in the quiz_user_mining class to fill the tables within this method. * * @return A list of instances of the quiz_user table representing class. **/ abstract Map<Long, QuizUserMining> generateQuizUserMining(); /** * Has to create and fill the quiz table. * This table describes the quiz in the LMS. * The attributes are described in the documentation of the quiz_mining class. * Please use the getter and setter predefined in the quiz_mining class to fill the tables within this method. * * @return A list of instances of the quiz table representing class. **/ abstract Map<Long, QuizMining> generateQuizMining(); /** * Has to create and fill the assignment table. * This table describes the assignment in the LMS. * The attributes are described in the documentation of the assignment_mining class. * Please use the getter and setter predefined in the assignment_mining class to fill the tables within this method. * * @return A list of instances of the assignment table representing class. **/ abstract Map<Long, AssignmentMining> generateAssignmentMining(); /** * Has to create and fill the scorm table. * This table describes the scorm packages in the LMS. * The attributes are described in the documentation of the scorm_mining class. * Please use the getter and setter predefined in the scorm_mining class to fill the tables within this method. * * @return A list of instances of the scorm table representing class. **/ abstract Map<Long, ScormMining> generateScormMining(); /** * Has to create and fill the quiz_question table. * This table describes which question is used in which quiz. * The attributes are described in the documentation of the quiz_question_mining class. * Please use the getter and setter predefined in the quiz_question_mining class to fill the tables within this * method. * * @return A list of instances of the quiz_question table representing class. **/ abstract Map<Long, QuizQuestionMining> generateQuizQuestionMining(); /** * Has to create and fill the question table. * This table describes the question in the LMS. * The attributes are described in the documentation of the question_mining class. * Please use the getter and setter predefined in the question_mining class to fill the tables within this method. * * @return A list of instances of the question table representing class. **/ abstract Map<Long, QuestionMining> generateQuestionMining(); /** * Has to create and fill the resource table. * This table describes the resource in the LMS. * The attributes are described in the documentation of the resource_mining class. * Please use the getter and setter predefined in the resource_mining class to fill the tables within this method. * * @return A list of instances of the resource table representing class. **/ abstract Map<Long, ResourceMining> generateResourceMining(); /** * Has to create and fill the resource_log table. * This table contains the actions which are done on resource. * The attributes are described in the documentation of the resource_log_mining class. * Please use the getter and setter predefined in the resource_log_mining class to fill the tables within this * method. * * @return A list of instances of the resource_log table representing class. **/ abstract Map<Long, ResourceLogMining> generateResourceLogMining(); /** * Has to create and fill the user table. * This table describes the user in the LMS. * The attributes are described in the documentation of the user_mining class. * Please use the getter and setter predefined in the user_mining class to fill the tables within this method. * * @return A list of instances of the user table representing class. **/ abstract Map<Long, UserMining> generateUserMining(); /** * Has to create and fill the wiki_log table. * This table contains the actions which are done on wiki. * The attributes are described in the documentation of the wiki_log_mining class. * Please use the getter and setter predefined in the wiki_log_mining class to fill the tables within this method. * * @return A list of instances of the wiki_log table representing class. **/ abstract Map<Long, WikiLogMining> generateWikiLogMining(); /** * Has to create and fill the wiki table. * This table describes the wiki in the LMS. * The attributes are described in the documentation of the wiki_mining class. * Please use the getter and setter predefined in the wiki_mining class to fill the tables within this method. * * @return A list of instances of the wiki table representing class. **/ abstract Map<Long, WikiMining> generateWikiMining(); /** * Has to create and fill the role table. * This table describes the roles of users in the LMS. * The attributes are described in the documentation of the role_mining class. * Please use the getter and setter predefined in the role_mining class to fill the tables within this method. * * @return A list of instances of the role table representing class. **/ abstract Map<Long, RoleMining> generateRoleMining(); /** * Generate level mining. * * @return the list */ abstract Map<Long, LevelMining> generateLevelMining(); /** * Generate level association mining. * * @return the list */ abstract Map<Long, LevelAssociationMining> generateLevelAssociationMining(); /** * Generate level course mining. * * @return the list */ abstract Map<Long, LevelCourseMining> generateLevelCourseMining(); /** * Generate chat mining. * * @return the list */ abstract Map<Long, ChatMining> generateChatMining(); /** * Generate chat log mining. * * @return the list */ abstract Map<Long, ChatLogMining> generateChatLogMining(); }
true
true
public long getMiningInitial() { // open a DB connection final Session session = this.dbHandler.getMiningSession(); List<?> t; t = this.dbHandler.performQuery(session, EQueryType.HQL, "from PlatformMining x order by x.id asc"); this.oldPlatformMining = new HashMap<Long, PlatformMining>(); if (t != null) { for (int i = 0; i < t.size(); i++) { this.oldPlatformMining.put(((PlatformMining) (t.get(i))).getId(), (PlatformMining) t.get(i)); } } logger.info("Loaded " + this.oldPlatformMining.size() + " PlatformMining objects from the mining database."); this.platformMining = new HashMap<Long, PlatformMining>(); this.configMiningTimestamp = this.dbHandler.getMiningSession() .createQuery("select max(lastModified) from ConfigMining x order by x.id asc").list(); if (this.configMiningTimestamp.get(0) == null) { this.configMiningTimestamp.set(0, new Timestamp(0)); } final long readingtimestamp = this.configMiningTimestamp.get(0).getTime(); // load objects which are already in Mining DB for associations Query logCount = session.createQuery("select max(id) from ResourceLogMining where platform=" + this.connector.getPlatformId()); this.resourceLogMax = ((ArrayList<Long>) logCount.list()).get(0); if (this.resourceLogMax == null) { this.resourceLogMax = 0L; } logCount = session.createSQLQuery("select max(id) from chat_log where platform=" + this.connector.getPlatformId()); this.chatLogMax = ((ArrayList<Long>) logCount.list()).get(0); if (this.chatLogMax == null) { this.chatLogMax = 0L; } logCount = session.createSQLQuery("select max(id) from assignment_log where platform=" + this.connector.getPlatformId()); this.assignmentLogMax = ((ArrayList<Long>) logCount.list()).get(0); if (this.assignmentLogMax == null) { this.assignmentLogMax = 0L; } logCount = session.createSQLQuery("select max(id) from course_log where platform=" + this.connector.getPlatformId()); this.courseLogMax = ((ArrayList<Long>) logCount.list()).get(0); if (this.courseLogMax == null) { this.courseLogMax = 0L; } logCount = session.createSQLQuery("select max(id) from forum_log where platform=" + this.connector.getPlatformId()); this.forumLogMax = ((ArrayList<Long>) logCount.list()).get(0); if (this.forumLogMax == null) { this.forumLogMax = 0L; } logCount = session.createSQLQuery("select max(id) from question_log where platform=" + this.connector.getPlatformId()); this.questionLogMax = ((ArrayList<Long>) logCount.list()).get(0); if (this.questionLogMax == null) { this.questionLogMax = 0L; } logCount = session.createSQLQuery("select max(id) from quiz_log where platform=" + this.connector.getPlatformId()); this.quizLogMax = ((ArrayList<Long>) logCount.list()).get(0); if (this.quizLogMax == null) { this.quizLogMax = 0L; } logCount = session.createSQLQuery("select max(id) from scorm_log where platform=" + this.connector.getPlatformId()); this.scormLogMax = ((ArrayList<Long>) logCount.list()).get(0); if (this.scormLogMax == null) { this.scormLogMax = 0L; } logCount = session.createSQLQuery("select max(id) from wiki_log where platform=" + this.connector.getPlatformId()); this.wikiLogMax = ((ArrayList<Long>) logCount.list()).get(0); if (this.wikiLogMax == null) { this.wikiLogMax = 0L; } t = this.dbHandler.performQuery(session, EQueryType.HQL, "from CourseMining x where x.platform=" + this.connector.getPlatformId() + " order by x.id asc"); this.oldCourseMining = new HashMap<Long, CourseMining>(); for (int i = 0; i < t.size(); i++) { this.oldCourseMining.put(((CourseMining) (t.get(i))).getId(), (CourseMining) t.get(i)); } logger.info("Loaded " + this.oldCourseMining.size() + " CourseMining objects from the mining database."); t = this.dbHandler.performQuery(session, EQueryType.HQL, "from QuizMining x where x.platform=" + this.connector.getPlatformId() + " order by x.id asc"); this.oldQuizMining = new HashMap<Long, QuizMining>(); for (int i = 0; i < t.size(); i++) { this.oldQuizMining.put(((QuizMining) (t.get(i))).getId(), (QuizMining) t.get(i)); } logger.info("Loaded " + this.oldQuizMining.size() + " QuizMining objects from the mining database."); t = this.dbHandler.performQuery(session, EQueryType.HQL, "from AssignmentMining x where x.platform=" + this.connector.getPlatformId() + " order by x.id asc"); this.oldAssignmentMining = new HashMap<Long, AssignmentMining>(); for (int i = 0; i < t.size(); i++) { this.oldAssignmentMining.put(((AssignmentMining) (t.get(i))).getId(), (AssignmentMining) t.get(i)); } logger.info("Loaded " + this.oldAssignmentMining.size() + " AssignmentMining objects from the mining database."); t = this.dbHandler.performQuery(session, EQueryType.HQL, "from ScormMining x where x.platform=" + this.connector.getPlatformId() + " order by x.id asc"); this.oldScormMining = new HashMap<Long, ScormMining>(); for (int i = 0; i < t.size(); i++) { this.oldScormMining.put(((ScormMining) (t.get(i))).getId(), (ScormMining) t.get(i)); } logger.info("Loaded " + this.oldScormMining.size() + " ScormMining objects from the mining database."); t = this.dbHandler.performQuery(session, EQueryType.HQL, "from ForumMining x where x.platform=" + this.connector.getPlatformId() + " order by x.id asc"); this.oldForumMining = new HashMap<Long, ForumMining>(); for (int i = 0; i < t.size(); i++) { this.oldForumMining.put(((ForumMining) (t.get(i))).getId(), (ForumMining) t.get(i)); } logger.info("Loaded " + this.oldForumMining.size() + " ForumMining objects from the mining database."); t = this.dbHandler.performQuery(session, EQueryType.HQL, "from ResourceMining x where x.platform=" + this.connector.getPlatformId() + " order by x.id asc"); this.oldResourceMining = new HashMap<Long, ResourceMining>(); for (int i = 0; i < t.size(); i++) { this.oldResourceMining.put(((ResourceMining) (t.get(i))).getId(), (ResourceMining) t.get(i)); } logger.info("Loaded " + this.oldResourceMining.size() + " ResourceMining objects from the mining database."); t = this.dbHandler.performQuery(session, EQueryType.HQL, "from UserMining x where x.platform=" + this.connector.getPlatformId() + " order by x.id asc"); this.oldUserMining = new HashMap<Long, UserMining>(); for (int i = 0; i < t.size(); i++) { this.oldUserMining.put(((UserMining) (t.get(i))).getId(), (UserMining) t.get(i)); } logger.info("Loaded " + this.oldUserMining.size() + " UserMining objects from the mining database."); t = this.dbHandler.performQuery(session, EQueryType.HQL, "from WikiMining x where x.platform=" + this.connector.getPlatformId() + " order by x.id asc"); this.oldWikiMining = new HashMap<Long, WikiMining>(); for (int i = 0; i < t.size(); i++) { this.oldWikiMining.put(((WikiMining) (t.get(i))).getId(), (WikiMining) t.get(i)); } logger.info("Loaded " + this.oldWikiMining.size() + " WikiMining objects from the mining database."); t = this.dbHandler.performQuery(session, EQueryType.HQL, "from GroupMining x where x.platform=" + this.connector.getPlatformId() + " order by x.id asc"); this.oldGroupMining = new HashMap<Long, GroupMining>(); for (int i = 0; i < t.size(); i++) { this.oldGroupMining.put(((GroupMining) (t.get(i))).getId(), (GroupMining) t.get(i)); } logger.info("Loaded " + this.oldGroupMining.size() + " GroupMining objects from the mining database."); t = this.dbHandler.performQuery(session, EQueryType.HQL, "from QuestionMining x where x.platform=" + this.connector.getPlatformId() + " order by x.id asc"); this.oldQuestionMining = new HashMap<Long, QuestionMining>(); for (int i = 0; i < t.size(); i++) { this.oldQuestionMining.put(((QuestionMining) (t.get(i))).getId(), (QuestionMining) t.get(i)); } logger.info("Loaded " + this.oldQuizMining.size() + " QuestionMining objects from the mining database."); t = this.dbHandler.performQuery(session, EQueryType.HQL, "from RoleMining x where x.platform=" + this.connector.getPlatformId() + " order by x.id asc"); this.oldRoleMining = new HashMap<Long, RoleMining>(); for (int i = 0; i < t.size(); i++) { this.oldRoleMining.put(((RoleMining) (t.get(i))).getId(), (RoleMining) t.get(i)); } logger.info("Loaded " + this.oldRoleMining.size() + " RoleMining objects from the mining database."); t = this.dbHandler.performQuery(session, EQueryType.HQL, "from QuizQuestionMining x where x.platform=" + this.connector.getPlatformId() + " order by x.id asc"); this.oldQuizQuestionMining = new HashMap<Long, QuizQuestionMining>(); for (int i = 0; i < t.size(); i++) { this.oldQuizQuestionMining.put(((QuizQuestionMining) (t.get(i))).getId(), (QuizQuestionMining) t.get(i)); } logger.info("Loaded " + this.oldQuizQuestionMining.size() + " QuizQuestionMining objects from the mining database."); t = this.dbHandler.performQuery(session, EQueryType.HQL, "from LevelMining x where x.platform=" + this.connector.getPlatformId() + " order by x.id asc"); this.oldLevelMining = new HashMap<Long, LevelMining>(); for (int i = 0; i < t.size(); i++) { this.oldLevelMining.put(((LevelMining) (t.get(i))).getId(), (LevelMining) t.get(i)); } logger.info("Loaded " + this.oldLevelMining.size() + " LevelMining objects from the mining database."); t = this.dbHandler.performQuery(session, EQueryType.HQL, "from ChatMining x where x.platform=" + this.connector.getPlatformId() + " order by x.id asc"); this.oldChatMining = new HashMap<Long, ChatMining>(); for (int i = 0; i < t.size(); i++) { this.oldChatMining.put(((ChatMining) (t.get(i))).getId(), (ChatMining) t.get(i)); } logger.info("Loaded " + this.oldChatMining.size() + " ChatMining objects from the mining database."); this.dbHandler.closeSession(session); return readingtimestamp; }
public long getMiningInitial() { // open a DB connection final Session session = this.dbHandler.getMiningSession(); List<?> t; t = this.dbHandler.performQuery(session, EQueryType.HQL, "from PlatformMining x order by x.id asc"); this.oldPlatformMining = new HashMap<Long, PlatformMining>(); if (t != null) { for (int i = 0; i < t.size(); i++) { this.oldPlatformMining.put(((PlatformMining) (t.get(i))).getId(), (PlatformMining) t.get(i)); } } logger.info("Loaded " + this.oldPlatformMining.size() + " PlatformMining objects from the mining database."); this.platformMining = new HashMap<Long, PlatformMining>(); this.configMiningTimestamp = this.dbHandler.getMiningSession() .createQuery("select max(lastModified) from ConfigMining x where x.platform="+ this.connector.getPlatformId() + " order by x.id asc").list(); if (this.configMiningTimestamp.get(0) == null) { this.configMiningTimestamp.set(0, new Timestamp(0)); } final long readingtimestamp = this.configMiningTimestamp.get(0).getTime(); // load objects which are already in Mining DB for associations Query logCount = session.createQuery("select max(id) from ResourceLogMining where platform=" + this.connector.getPlatformId()); this.resourceLogMax = ((ArrayList<Long>) logCount.list()).get(0); if (this.resourceLogMax == null) { this.resourceLogMax = 0L; } logCount = session.createSQLQuery("select max(id) from chat_log where platform=" + this.connector.getPlatformId()); this.chatLogMax = ((ArrayList<Long>) logCount.list()).get(0); if (this.chatLogMax == null) { this.chatLogMax = 0L; } logCount = session.createSQLQuery("select max(id) from assignment_log where platform=" + this.connector.getPlatformId()); this.assignmentLogMax = ((ArrayList<Long>) logCount.list()).get(0); if (this.assignmentLogMax == null) { this.assignmentLogMax = 0L; } logCount = session.createSQLQuery("select max(id) from course_log where platform=" + this.connector.getPlatformId()); this.courseLogMax = ((ArrayList<Long>) logCount.list()).get(0); if (this.courseLogMax == null) { this.courseLogMax = 0L; } logCount = session.createSQLQuery("select max(id) from forum_log where platform=" + this.connector.getPlatformId()); this.forumLogMax = ((ArrayList<Long>) logCount.list()).get(0); if (this.forumLogMax == null) { this.forumLogMax = 0L; } logCount = session.createSQLQuery("select max(id) from question_log where platform=" + this.connector.getPlatformId()); this.questionLogMax = ((ArrayList<Long>) logCount.list()).get(0); if (this.questionLogMax == null) { this.questionLogMax = 0L; } logCount = session.createSQLQuery("select max(id) from quiz_log where platform=" + this.connector.getPlatformId()); this.quizLogMax = ((ArrayList<Long>) logCount.list()).get(0); if (this.quizLogMax == null) { this.quizLogMax = 0L; } logCount = session.createSQLQuery("select max(id) from scorm_log where platform=" + this.connector.getPlatformId()); this.scormLogMax = ((ArrayList<Long>) logCount.list()).get(0); if (this.scormLogMax == null) { this.scormLogMax = 0L; } logCount = session.createSQLQuery("select max(id) from wiki_log where platform=" + this.connector.getPlatformId()); this.wikiLogMax = ((ArrayList<Long>) logCount.list()).get(0); if (this.wikiLogMax == null) { this.wikiLogMax = 0L; } t = this.dbHandler.performQuery(session, EQueryType.HQL, "from CourseMining x where x.platform=" + this.connector.getPlatformId() + " order by x.id asc"); this.oldCourseMining = new HashMap<Long, CourseMining>(); for (int i = 0; i < t.size(); i++) { this.oldCourseMining.put(((CourseMining) (t.get(i))).getId(), (CourseMining) t.get(i)); } logger.info("Loaded " + this.oldCourseMining.size() + " CourseMining objects from the mining database."); t = this.dbHandler.performQuery(session, EQueryType.HQL, "from QuizMining x where x.platform=" + this.connector.getPlatformId() + " order by x.id asc"); this.oldQuizMining = new HashMap<Long, QuizMining>(); for (int i = 0; i < t.size(); i++) { this.oldQuizMining.put(((QuizMining) (t.get(i))).getId(), (QuizMining) t.get(i)); } logger.info("Loaded " + this.oldQuizMining.size() + " QuizMining objects from the mining database."); t = this.dbHandler.performQuery(session, EQueryType.HQL, "from AssignmentMining x where x.platform=" + this.connector.getPlatformId() + " order by x.id asc"); this.oldAssignmentMining = new HashMap<Long, AssignmentMining>(); for (int i = 0; i < t.size(); i++) { this.oldAssignmentMining.put(((AssignmentMining) (t.get(i))).getId(), (AssignmentMining) t.get(i)); } logger.info("Loaded " + this.oldAssignmentMining.size() + " AssignmentMining objects from the mining database."); t = this.dbHandler.performQuery(session, EQueryType.HQL, "from ScormMining x where x.platform=" + this.connector.getPlatformId() + " order by x.id asc"); this.oldScormMining = new HashMap<Long, ScormMining>(); for (int i = 0; i < t.size(); i++) { this.oldScormMining.put(((ScormMining) (t.get(i))).getId(), (ScormMining) t.get(i)); } logger.info("Loaded " + this.oldScormMining.size() + " ScormMining objects from the mining database."); t = this.dbHandler.performQuery(session, EQueryType.HQL, "from ForumMining x where x.platform=" + this.connector.getPlatformId() + " order by x.id asc"); this.oldForumMining = new HashMap<Long, ForumMining>(); for (int i = 0; i < t.size(); i++) { this.oldForumMining.put(((ForumMining) (t.get(i))).getId(), (ForumMining) t.get(i)); } logger.info("Loaded " + this.oldForumMining.size() + " ForumMining objects from the mining database."); t = this.dbHandler.performQuery(session, EQueryType.HQL, "from ResourceMining x where x.platform=" + this.connector.getPlatformId() + " order by x.id asc"); this.oldResourceMining = new HashMap<Long, ResourceMining>(); for (int i = 0; i < t.size(); i++) { this.oldResourceMining.put(((ResourceMining) (t.get(i))).getId(), (ResourceMining) t.get(i)); } logger.info("Loaded " + this.oldResourceMining.size() + " ResourceMining objects from the mining database."); t = this.dbHandler.performQuery(session, EQueryType.HQL, "from UserMining x where x.platform=" + this.connector.getPlatformId() + " order by x.id asc"); this.oldUserMining = new HashMap<Long, UserMining>(); for (int i = 0; i < t.size(); i++) { this.oldUserMining.put(((UserMining) (t.get(i))).getId(), (UserMining) t.get(i)); } logger.info("Loaded " + this.oldUserMining.size() + " UserMining objects from the mining database."); t = this.dbHandler.performQuery(session, EQueryType.HQL, "from WikiMining x where x.platform=" + this.connector.getPlatformId() + " order by x.id asc"); this.oldWikiMining = new HashMap<Long, WikiMining>(); for (int i = 0; i < t.size(); i++) { this.oldWikiMining.put(((WikiMining) (t.get(i))).getId(), (WikiMining) t.get(i)); } logger.info("Loaded " + this.oldWikiMining.size() + " WikiMining objects from the mining database."); t = this.dbHandler.performQuery(session, EQueryType.HQL, "from GroupMining x where x.platform=" + this.connector.getPlatformId() + " order by x.id asc"); this.oldGroupMining = new HashMap<Long, GroupMining>(); for (int i = 0; i < t.size(); i++) { this.oldGroupMining.put(((GroupMining) (t.get(i))).getId(), (GroupMining) t.get(i)); } logger.info("Loaded " + this.oldGroupMining.size() + " GroupMining objects from the mining database."); t = this.dbHandler.performQuery(session, EQueryType.HQL, "from QuestionMining x where x.platform=" + this.connector.getPlatformId() + " order by x.id asc"); this.oldQuestionMining = new HashMap<Long, QuestionMining>(); for (int i = 0; i < t.size(); i++) { this.oldQuestionMining.put(((QuestionMining) (t.get(i))).getId(), (QuestionMining) t.get(i)); } logger.info("Loaded " + this.oldQuizMining.size() + " QuestionMining objects from the mining database."); t = this.dbHandler.performQuery(session, EQueryType.HQL, "from RoleMining x where x.platform=" + this.connector.getPlatformId() + " order by x.id asc"); this.oldRoleMining = new HashMap<Long, RoleMining>(); for (int i = 0; i < t.size(); i++) { this.oldRoleMining.put(((RoleMining) (t.get(i))).getId(), (RoleMining) t.get(i)); } logger.info("Loaded " + this.oldRoleMining.size() + " RoleMining objects from the mining database."); t = this.dbHandler.performQuery(session, EQueryType.HQL, "from QuizQuestionMining x where x.platform=" + this.connector.getPlatformId() + " order by x.id asc"); this.oldQuizQuestionMining = new HashMap<Long, QuizQuestionMining>(); for (int i = 0; i < t.size(); i++) { this.oldQuizQuestionMining.put(((QuizQuestionMining) (t.get(i))).getId(), (QuizQuestionMining) t.get(i)); } logger.info("Loaded " + this.oldQuizQuestionMining.size() + " QuizQuestionMining objects from the mining database."); t = this.dbHandler.performQuery(session, EQueryType.HQL, "from LevelMining x where x.platform=" + this.connector.getPlatformId() + " order by x.id asc"); this.oldLevelMining = new HashMap<Long, LevelMining>(); for (int i = 0; i < t.size(); i++) { this.oldLevelMining.put(((LevelMining) (t.get(i))).getId(), (LevelMining) t.get(i)); } logger.info("Loaded " + this.oldLevelMining.size() + " LevelMining objects from the mining database."); t = this.dbHandler.performQuery(session, EQueryType.HQL, "from ChatMining x where x.platform=" + this.connector.getPlatformId() + " order by x.id asc"); this.oldChatMining = new HashMap<Long, ChatMining>(); for (int i = 0; i < t.size(); i++) { this.oldChatMining.put(((ChatMining) (t.get(i))).getId(), (ChatMining) t.get(i)); } logger.info("Loaded " + this.oldChatMining.size() + " ChatMining objects from the mining database."); this.dbHandler.closeSession(session); return readingtimestamp; }
diff --git a/public/java/src/org/broadinstitute/sting/utils/genotype/Haplotype.java b/public/java/src/org/broadinstitute/sting/utils/genotype/Haplotype.java index cb6557408..31791e805 100755 --- a/public/java/src/org/broadinstitute/sting/utils/genotype/Haplotype.java +++ b/public/java/src/org/broadinstitute/sting/utils/genotype/Haplotype.java @@ -1,161 +1,165 @@ /* * Copyright (c) 2010, The Broad Institute * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.broadinstitute.sting.utils.genotype; import org.broadinstitute.sting.utils.variantcontext.Allele; import org.broadinstitute.sting.utils.variantcontext.VariantContext; import org.broadinstitute.sting.gatk.contexts.ReferenceContext; import org.broadinstitute.sting.utils.GenomeLoc; import org.broadinstitute.sting.utils.GenomeLocParser; import org.broadinstitute.sting.utils.exceptions.ReviewedStingException; import java.util.*; public class Haplotype { protected byte[] bases = null; protected double[] quals = null; private GenomeLoc genomeLocation = null; private boolean isReference = false; /** * Create a simple consensus sequence with provided bases and a uniform quality over all bases of qual * * @param bases bases * @param qual qual */ public Haplotype(byte[] bases, int qual) { this.bases = bases; quals = new double[bases.length]; Arrays.fill(quals, (double)qual); } public Haplotype(byte[] bases, double[] quals) { this.bases = bases; this.quals = quals; } public Haplotype(byte[] bases) { this(bases, 0); } public Haplotype(byte[] bases, GenomeLoc loc) { this(bases); this.genomeLocation = loc; } public Haplotype(byte[] bases, GenomeLoc loc, boolean isRef) { this(bases, loc); this.isReference = isRef; } public double getQualitySum() { double s = 0; for (int k=0; k < bases.length; k++) { s += quals[k]; } return s; } public String toString() { String returnString = ""; for(int iii = 0; iii < bases.length; iii++) { returnString += (char) bases[iii]; } return returnString; } public double[] getQuals() { return quals; } public byte[] getBasesAsBytes() { return bases; } public long getStartPosition() { return genomeLocation.getStart(); } public long getStopPosition() { return genomeLocation.getStop(); } public boolean isReference() { return isReference; } public static LinkedHashMap<Allele,Haplotype> makeHaplotypeListFromAlleles(List<Allele> alleleList, int startPos, ReferenceContext ref, final int haplotypeSize, final int numPrefBases) { LinkedHashMap<Allele,Haplotype> haplotypeMap = new LinkedHashMap<Allele,Haplotype>(); Allele refAllele = null; for (Allele a:alleleList) { if (a.isReference()) { refAllele = a; break; } } if (refAllele == null) throw new ReviewedStingException("BUG: no ref alleles in input to makeHaplotypeListfrom Alleles at loc: "+ startPos); byte[] refBases = ref.getBases(); int startIdxInReference = (int)(1+startPos-numPrefBases-ref.getWindow().getStart()); //int numPrefBases = (int)(vc.getStart()-ref.getWindow().getStart()+1); // indel vc starts one before event byte[] basesBeforeVariant = Arrays.copyOfRange(refBases,startIdxInReference,startIdxInReference+numPrefBases); + int startAfter = startIdxInReference+numPrefBases+ refAllele.getBases().length; + // protect against long events that overrun available reference context + if (startAfter > refBases.length) + startAfter = refBases.length; byte[] basesAfterVariant = Arrays.copyOfRange(refBases, - startIdxInReference+numPrefBases+ refAllele.getBases().length, refBases.length); + startAfter, refBases.length); // Create location for all haplotypes int startLoc = ref.getWindow().getStart() + startIdxInReference; int stopLoc = startLoc + haplotypeSize-1; GenomeLoc locus = ref.getGenomeLocParser().createGenomeLoc(ref.getLocus().getContig(),startLoc,stopLoc); for (Allele a : alleleList) { byte[] alleleBases = a.getBases(); // use string concatenation String haplotypeString = new String(basesBeforeVariant) + new String(alleleBases) + new String(basesAfterVariant); haplotypeString = haplotypeString.substring(0,haplotypeSize); haplotypeMap.put(a,new Haplotype(haplotypeString.getBytes(), locus, a.isReference())); } return haplotypeMap; } }
false
true
public static LinkedHashMap<Allele,Haplotype> makeHaplotypeListFromAlleles(List<Allele> alleleList, int startPos, ReferenceContext ref, final int haplotypeSize, final int numPrefBases) { LinkedHashMap<Allele,Haplotype> haplotypeMap = new LinkedHashMap<Allele,Haplotype>(); Allele refAllele = null; for (Allele a:alleleList) { if (a.isReference()) { refAllele = a; break; } } if (refAllele == null) throw new ReviewedStingException("BUG: no ref alleles in input to makeHaplotypeListfrom Alleles at loc: "+ startPos); byte[] refBases = ref.getBases(); int startIdxInReference = (int)(1+startPos-numPrefBases-ref.getWindow().getStart()); //int numPrefBases = (int)(vc.getStart()-ref.getWindow().getStart()+1); // indel vc starts one before event byte[] basesBeforeVariant = Arrays.copyOfRange(refBases,startIdxInReference,startIdxInReference+numPrefBases); byte[] basesAfterVariant = Arrays.copyOfRange(refBases, startIdxInReference+numPrefBases+ refAllele.getBases().length, refBases.length); // Create location for all haplotypes int startLoc = ref.getWindow().getStart() + startIdxInReference; int stopLoc = startLoc + haplotypeSize-1; GenomeLoc locus = ref.getGenomeLocParser().createGenomeLoc(ref.getLocus().getContig(),startLoc,stopLoc); for (Allele a : alleleList) { byte[] alleleBases = a.getBases(); // use string concatenation String haplotypeString = new String(basesBeforeVariant) + new String(alleleBases) + new String(basesAfterVariant); haplotypeString = haplotypeString.substring(0,haplotypeSize); haplotypeMap.put(a,new Haplotype(haplotypeString.getBytes(), locus, a.isReference())); } return haplotypeMap; }
public static LinkedHashMap<Allele,Haplotype> makeHaplotypeListFromAlleles(List<Allele> alleleList, int startPos, ReferenceContext ref, final int haplotypeSize, final int numPrefBases) { LinkedHashMap<Allele,Haplotype> haplotypeMap = new LinkedHashMap<Allele,Haplotype>(); Allele refAllele = null; for (Allele a:alleleList) { if (a.isReference()) { refAllele = a; break; } } if (refAllele == null) throw new ReviewedStingException("BUG: no ref alleles in input to makeHaplotypeListfrom Alleles at loc: "+ startPos); byte[] refBases = ref.getBases(); int startIdxInReference = (int)(1+startPos-numPrefBases-ref.getWindow().getStart()); //int numPrefBases = (int)(vc.getStart()-ref.getWindow().getStart()+1); // indel vc starts one before event byte[] basesBeforeVariant = Arrays.copyOfRange(refBases,startIdxInReference,startIdxInReference+numPrefBases); int startAfter = startIdxInReference+numPrefBases+ refAllele.getBases().length; // protect against long events that overrun available reference context if (startAfter > refBases.length) startAfter = refBases.length; byte[] basesAfterVariant = Arrays.copyOfRange(refBases, startAfter, refBases.length); // Create location for all haplotypes int startLoc = ref.getWindow().getStart() + startIdxInReference; int stopLoc = startLoc + haplotypeSize-1; GenomeLoc locus = ref.getGenomeLocParser().createGenomeLoc(ref.getLocus().getContig(),startLoc,stopLoc); for (Allele a : alleleList) { byte[] alleleBases = a.getBases(); // use string concatenation String haplotypeString = new String(basesBeforeVariant) + new String(alleleBases) + new String(basesAfterVariant); haplotypeString = haplotypeString.substring(0,haplotypeSize); haplotypeMap.put(a,new Haplotype(haplotypeString.getBytes(), locus, a.isReference())); } return haplotypeMap; }
diff --git a/src/test/cascading/BasicPipesTest.java b/src/test/cascading/BasicPipesTest.java index 490707d0..0d258f48 100644 --- a/src/test/cascading/BasicPipesTest.java +++ b/src/test/cascading/BasicPipesTest.java @@ -1,435 +1,436 @@ /* * Copyright (c) 2007-2010 Concurrent, Inc. All Rights Reserved. * * Project and contact information: http://www.cascading.org/ * * This file is part of the Cascading project. * * Cascading is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Cascading is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Cascading. If not, see <http://www.gnu.org/licenses/>. */ package cascading; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; import cascading.flow.Flow; import cascading.flow.FlowConnector; import cascading.operation.Aggregator; import cascading.operation.ConcreteCall; import cascading.operation.Filter; import cascading.operation.Function; import cascading.operation.Identity; import cascading.operation.aggregator.Count; import cascading.operation.expression.ExpressionFilter; import cascading.operation.function.UnGroup; import cascading.operation.regex.RegexFilter; import cascading.operation.regex.RegexParser; import cascading.operation.regex.RegexSplitter; import cascading.pipe.CoGroup; import cascading.pipe.Each; import cascading.pipe.Every; import cascading.pipe.GroupBy; import cascading.pipe.Pipe; import cascading.scheme.TextLine; import cascading.tap.Hfs; import cascading.tap.Tap; import cascading.tuple.Fields; import cascading.tuple.Tuple; import cascading.tuple.TupleEntry; import cascading.tuple.TupleEntryIterator; import cascading.tuple.TupleListCollector; /** * These tests execute basic function using field positions, not names. so there will be duplicates with * FieldedPipestest */ public class BasicPipesTest extends CascadingTestCase { String inputFileApache = "build/test/data/apache.10.txt"; String inputFileIps = "build/test/data/ips.20.txt"; String inputFileNums = "build/test/data/nums.20.txt"; String inputFileUpper = "build/test/data/upper.txt"; String inputFileLower = "build/test/data/lower.txt"; String inputFileJoined = "build/test/data/lower+upper.txt"; String outputPath = "build/test/output/results"; public BasicPipesTest() { super( "build pipes" ); } /** * Test the count aggregator function * * @throws IOException */ public void testCount() throws Exception { runTestCount( new Fields( 1 ), new Fields( 0 ), new Fields( 0, 1 ) ); } public void testCount2() throws Exception { runTestCount( new Fields( 1 ), new Fields( "count" ), new Fields( 0, "count" ) ); } public void testCount3() throws Exception { runTestCount( new Fields( 1 ), new Fields( "count" ), Fields.ALL ); } public void testCount4() throws Exception { runTestCount( Fields.ALL, new Fields( "count" ), Fields.ALL ); } void runTestCount( Fields argumentSelector, Fields fieldDeclaration, Fields outputSelector ) throws Exception { if( !new File( inputFileIps ).exists() ) fail( "data file not found" ); Tap source = new Hfs( new TextLine( Fields.size( 2 ) ), inputFileIps ); Tap sink = new Hfs( new TextLine(), outputPath + "/count", true ); Pipe pipe = new Pipe( "count" ); pipe = new GroupBy( pipe, new Fields( 1 ) ); pipe = new Every( pipe, argumentSelector, new Count( fieldDeclaration ), outputSelector ); Flow flow = new FlowConnector().connect( source, sink, pipe ); // flow.writeDOT( "basic.dot" ); flow.start(); flow.complete(); TupleEntryIterator iterator = flow.openSink(); Function splitter = new RegexSplitter( Fields.size( 2 ) ); boolean found = false; while( iterator.hasNext() ) { Tuple tuple = iterator.next().getTuple(); // System.out.println( "tuple = " + tuple ); TupleListCollector tupleEntryCollector = new TupleListCollector( Fields.size( 2 ) ); Tuple tuple1 = tuple.get( new int[]{1} ); ConcreteCall operationCall = new ConcreteCall( new TupleEntry( tuple1 ), tupleEntryCollector ); + splitter.prepare( null, operationCall ); splitter.operate( null, operationCall ); Tuple tupleEntry = tupleEntryCollector.iterator().next(); if( tupleEntry.get( 0 ).equals( "63.123.238.8" ) ) { found = true; assertEquals( "wrong count", "2", tupleEntry.get( 1 ) ); } } iterator.close(); if( !found ) fail( "never found ip" ); validateLength( flow, 17 ); } /** * A slightly more complex pipe * * @throws IOException */ public void testSimple() throws Exception { if( !new File( inputFileApache ).exists() ) fail( "data file not found" ); Tap source = new Hfs( new TextLine( Fields.size( 2 ) ), inputFileApache ); Tap sink = new Hfs( new TextLine( Fields.size( 1 ) ), outputPath + "/simple", true ); Pipe pipe = new Pipe( "test" ); Function parser = new RegexParser( "^[^ ]*" ); pipe = new Each( pipe, new Fields( 1 ), parser, new Fields( 0, 2 ) ); // test that selector against incoming creates proper outgoing pipe = new Each( pipe, new Fields( 1 ), new Identity() ); pipe = new GroupBy( pipe, new Fields( 0 ) ); Aggregator counter = new Count(); pipe = new Every( pipe, new Fields( 0 ), counter, new Fields( 0, 1 ) ); Flow flow = new FlowConnector().connect( source, sink, pipe ); // flow.writeDOT( "simple.dot" ); flow.complete(); validateLength( flow, 8, 1 ); } /** * tests that the Fields.ARGS declarator properly resolves into a declarator * * @throws Exception */ public void testSimpleResult() throws Exception { if( !new File( inputFileLower ).exists() ) fail( "data file not found" ); Tap source = new Hfs( new TextLine( Fields.size( 2 ) ), inputFileLower ); Tap sink = new Hfs( new TextLine( Fields.size( 1 ) ), outputPath + "/simpleresult", true ); Pipe pipe = new Pipe( "test" ); pipe = new Each( pipe, new Fields( 0 ), new ExpressionFilter( "$0 == 0", Long.class ) ); pipe = new Each( pipe, new Fields( 1 ), new Identity() ); pipe = new Each( pipe, Fields.ALL, new RegexFilter( "a|b|c" ) ); pipe = new GroupBy( pipe, new Fields( 0 ) ); Aggregator counter = new Count(); pipe = new Every( pipe, new Fields( 0 ), counter, new Fields( 0, 1 ) ); Flow flow = new FlowConnector().connect( source, sink, pipe ); // flow.writeDOT( "simple.dot" ); flow.complete(); validateLength( flow, 2, 1 ); } public void testSimpleRelative() throws Exception { if( !new File( inputFileApache ).exists() ) fail( "data file not found" ); Tap source = new Hfs( new TextLine( Fields.size( 2 ) ), inputFileApache ); Tap sink = new Hfs( new TextLine(), outputPath + "/simplerelative", true ); Pipe pipe = new Pipe( "test" ); Function parser = new RegexParser( "^[^ ]*" ); pipe = new Each( pipe, new Fields( -1 ), parser, new Fields( -1 ) ); pipe = new GroupBy( pipe, new Fields( 0 ) ); Aggregator counter = new Count(); pipe = new Every( pipe, new Fields( 0 ), counter, new Fields( 0, 1 ) ); Flow flow = new FlowConnector().connect( source, sink, pipe ); // flow.writeDOT( "simple.dot" ); flow.complete(); validateLength( flow, 8 ); } public void testCoGroup() throws Exception { if( !new File( inputFileLower ).exists() ) fail( "data file not found" ); Tap sourceLower = new Hfs( new TextLine( Fields.size( 2 ) ), inputFileLower ); Tap sourceUpper = new Hfs( new TextLine(), inputFileUpper ); Map sources = new HashMap(); sources.put( "lower", sourceLower ); sources.put( "upper", sourceUpper ); // using null pos so all fields are written Tap sink = new Hfs( new TextLine(), outputPath + "/complex/cogroup/", true ); Function splitter = new RegexSplitter( Fields.size( 2 ), " " ); Pipe pipeLower = new Each( new Pipe( "lower" ), new Fields( 1 ), splitter, Fields.RESULTS ); Pipe pipeUpper = new Each( new Pipe( "upper" ), new Fields( 1 ), splitter, Fields.RESULTS ); Pipe splice = new CoGroup( pipeLower, new Fields( 0 ), pipeUpper, new Fields( 0 ) ); Flow countFlow = new FlowConnector().connect( sources, sink, splice ); // System.out.println( "countFlow =\n" + countFlow ); // countFlow.writeDOT( "cogroup.dot" ); countFlow.complete(); validateLength( countFlow, 5 ); TupleEntryIterator iterator = countFlow.openSink(); assertEquals( "not equal: tuple.get(1)", "1\ta\t1\tA", iterator.next().get( 1 ) ); assertEquals( "not equal: tuple.get(1)", "2\tb\t2\tB", iterator.next().get( 1 ) ); iterator.close(); } public void testUnGroup() throws Exception { if( !new File( inputFileJoined ).exists() ) fail( "data file not found" ); Tap source = new Hfs( new TextLine( Fields.size( 2 ) ), inputFileJoined ); Tap sink = new Hfs( new TextLine(), outputPath + "/ungrouped", true ); Pipe pipe = new Pipe( "test" ); pipe = new Each( pipe, new Fields( 1 ), new RegexSplitter( Fields.size( 3 ) ) ); pipe = new Each( pipe, new UnGroup( Fields.size( 2 ), new Fields( 0 ), Fields.fields( new Fields( 1 ), new Fields( 2 ) ) ) ); Flow flow = new FlowConnector().connect( source, sink, pipe ); // flow.writeDOT( "ungroup.dot" ); flow.complete(); validateLength( flow, 10 ); } public void testFilterAll() throws Exception { if( !new File( inputFileApache ).exists() ) fail( "data file not found" ); Tap source = new Hfs( new TextLine( Fields.size( 2 ) ), inputFileApache ); Tap sink = new Hfs( new TextLine(), outputPath + "/filterall", true ); Pipe pipe = new Pipe( "test" ); Filter filter = new RegexFilter( ".*", true ); pipe = new Each( pipe, new Fields( 1 ), filter ); Flow flow = new FlowConnector().connect( source, sink, pipe ); flow.complete(); validateLength( flow, 0 ); } public void testFilter() throws Exception { if( !new File( inputFileApache ).exists() ) fail( "data file not found" ); Tap source = new Hfs( new TextLine( Fields.size( 2 ) ), inputFileApache ); Tap sink = new Hfs( new TextLine(), outputPath + "/filter", true ); Pipe pipe = new Pipe( "test" ); Filter filter = new RegexFilter( "^68.*" ); pipe = new Each( pipe, new Fields( 1 ), filter ); Flow flow = new FlowConnector().connect( source, sink, pipe ); flow.complete(); validateLength( flow, 3 ); } public void testSimpleChain() throws Exception { if( !new File( inputFileApache ).exists() ) fail( "data file not found" ); Tap source = new Hfs( new TextLine( Fields.size( 2 ) ), inputFileApache ); Tap sink = new Hfs( new TextLine(), outputPath + "/simple", true ); Pipe pipe = new Pipe( "test" ); Function parser = new RegexParser( "^[^ ]*" ); pipe = new Each( pipe, new Fields( 1 ), parser, new Fields( 2 ) ); pipe = new GroupBy( pipe, new Fields( 0 ) ); pipe = new Every( pipe, new Fields( 0 ), new Count(), new Fields( 0, 1 ) ); // add a second group to force a new map/red pipe = new GroupBy( pipe, new Fields( 0 ) ); Flow flow = new FlowConnector().connect( source, sink, pipe ); // flow.writeDOT( "simplechain.dot" ); flow.complete(); validateLength( flow, 8 ); } public void testReplace() throws Exception { if( !new File( inputFileApache ).exists() ) fail( "data file not found" ); Tap source = new Hfs( new TextLine(), inputFileApache ); Tap sink = new Hfs( new TextLine(), outputPath + "/replace", true ); Pipe pipe = new Pipe( "test" ); Function parser = new RegexParser( Fields.ARGS, "^[^ ]*" ); pipe = new Each( pipe, new Fields( 1 ), parser, Fields.REPLACE ); Flow flow = new FlowConnector().connect( source, sink, pipe ); // flow.writeDOT( "simple.dot" ); flow.complete(); validateLength( flow, 10, 2, Pattern.compile( "\\d+\\s\\d+\\s[\\d]{1,3}\\.[\\d]{1,3}\\.[\\d]{1,3}\\.[\\d]{1,3}" ) ); } public void testSwap() throws Exception { if( !new File( inputFileApache ).exists() ) fail( "data file not found" ); Tap source = new Hfs( new TextLine(), inputFileApache ); Tap sink = new Hfs( new TextLine(), outputPath + "/swap", true ); Pipe pipe = new Pipe( "test" ); Function parser = new RegexParser( new Fields( 0 ), "^[^ ]*" ); pipe = new Each( pipe, new Fields( 1 ), parser, Fields.SWAP ); Flow flow = new FlowConnector().connect( source, sink, pipe ); // flow.writeDOT( "simple.dot" ); flow.complete(); validateLength( flow, 10, 2, Pattern.compile( "^\\d+\\s\\d+\\s[\\d]{1,3}\\.[\\d]{1,3}\\.[\\d]{1,3}\\.[\\d]{1,3}$" ) ); } }
true
true
void runTestCount( Fields argumentSelector, Fields fieldDeclaration, Fields outputSelector ) throws Exception { if( !new File( inputFileIps ).exists() ) fail( "data file not found" ); Tap source = new Hfs( new TextLine( Fields.size( 2 ) ), inputFileIps ); Tap sink = new Hfs( new TextLine(), outputPath + "/count", true ); Pipe pipe = new Pipe( "count" ); pipe = new GroupBy( pipe, new Fields( 1 ) ); pipe = new Every( pipe, argumentSelector, new Count( fieldDeclaration ), outputSelector ); Flow flow = new FlowConnector().connect( source, sink, pipe ); // flow.writeDOT( "basic.dot" ); flow.start(); flow.complete(); TupleEntryIterator iterator = flow.openSink(); Function splitter = new RegexSplitter( Fields.size( 2 ) ); boolean found = false; while( iterator.hasNext() ) { Tuple tuple = iterator.next().getTuple(); // System.out.println( "tuple = " + tuple ); TupleListCollector tupleEntryCollector = new TupleListCollector( Fields.size( 2 ) ); Tuple tuple1 = tuple.get( new int[]{1} ); ConcreteCall operationCall = new ConcreteCall( new TupleEntry( tuple1 ), tupleEntryCollector ); splitter.operate( null, operationCall ); Tuple tupleEntry = tupleEntryCollector.iterator().next(); if( tupleEntry.get( 0 ).equals( "63.123.238.8" ) ) { found = true; assertEquals( "wrong count", "2", tupleEntry.get( 1 ) ); } } iterator.close(); if( !found ) fail( "never found ip" ); validateLength( flow, 17 ); }
void runTestCount( Fields argumentSelector, Fields fieldDeclaration, Fields outputSelector ) throws Exception { if( !new File( inputFileIps ).exists() ) fail( "data file not found" ); Tap source = new Hfs( new TextLine( Fields.size( 2 ) ), inputFileIps ); Tap sink = new Hfs( new TextLine(), outputPath + "/count", true ); Pipe pipe = new Pipe( "count" ); pipe = new GroupBy( pipe, new Fields( 1 ) ); pipe = new Every( pipe, argumentSelector, new Count( fieldDeclaration ), outputSelector ); Flow flow = new FlowConnector().connect( source, sink, pipe ); // flow.writeDOT( "basic.dot" ); flow.start(); flow.complete(); TupleEntryIterator iterator = flow.openSink(); Function splitter = new RegexSplitter( Fields.size( 2 ) ); boolean found = false; while( iterator.hasNext() ) { Tuple tuple = iterator.next().getTuple(); // System.out.println( "tuple = " + tuple ); TupleListCollector tupleEntryCollector = new TupleListCollector( Fields.size( 2 ) ); Tuple tuple1 = tuple.get( new int[]{1} ); ConcreteCall operationCall = new ConcreteCall( new TupleEntry( tuple1 ), tupleEntryCollector ); splitter.prepare( null, operationCall ); splitter.operate( null, operationCall ); Tuple tupleEntry = tupleEntryCollector.iterator().next(); if( tupleEntry.get( 0 ).equals( "63.123.238.8" ) ) { found = true; assertEquals( "wrong count", "2", tupleEntry.get( 1 ) ); } } iterator.close(); if( !found ) fail( "never found ip" ); validateLength( flow, 17 ); }
diff --git a/CocaColaClimateAmbassador/src/main/java/com/cocacola/climateambassador/adapters/MenuListAdapter.java b/CocaColaClimateAmbassador/src/main/java/com/cocacola/climateambassador/adapters/MenuListAdapter.java index 7d8ca6e..922daa4 100644 --- a/CocaColaClimateAmbassador/src/main/java/com/cocacola/climateambassador/adapters/MenuListAdapter.java +++ b/CocaColaClimateAmbassador/src/main/java/com/cocacola/climateambassador/adapters/MenuListAdapter.java @@ -1,106 +1,106 @@ package com.cocacola.climateambassador.adapters; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.cocacola.climateambassador.R; import com.cocacola.climateambassador.models.NavigationDrawerItem; import java.util.List; public class MenuListAdapter extends BaseAdapter { private List<NavigationDrawerItem> mNavigationItems; private Context mContext; private LayoutInflater mInflater; public MenuListAdapter(Context context, List<NavigationDrawerItem> navigationItems) { mNavigationItems = navigationItems; mContext = context; mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { return mNavigationItems.size(); } @Override public long getItemId(int position) { return position; } @Override public NavigationDrawerItem getItem(int position) { return mNavigationItems.get(position); } @Override public int getViewTypeCount() { return 2; } @Override public int getItemViewType(int position) { return getItem(position).isHeader() ? 0 : 1; } public View getView(int position, View convertView, ViewGroup parent) { NavigationDrawerItem item = getItem(position); View v = (item.isHeader()) ? getHeaderView(item) : getNavigationDrawerItemView(item); return v; } private View getHeaderView(NavigationDrawerItem item) { View v = mInflater.inflate(R.layout.drawer_header, null); TextView text = (TextView) v.findViewById(R.id.drawer_header_text); text.setText(item.getTitle()); return v; } private View getNavigationDrawerItemView(NavigationDrawerItem item) { View v = mInflater.inflate(R.layout.drawer_list_item, null); - TextView txtTitle = (TextView) v.findViewById(R.id.title); - ImageView imgIcon = (ImageView) v.findViewById(R.id.icon); + TextView txtTitle = (TextView) v.findViewById(R.id.drawer_item_title); + ImageView imgIcon = (ImageView) v.findViewById(R.id.drawer_item_icon); txtTitle.setText(item.getTitle()); imgIcon.setImageResource(item.getIconId()); v.setOnClickListener(new OnNavigationItemClickListener(item.getActivityClz())); return v; } private class OnNavigationItemClickListener implements View.OnClickListener { private Class<?> clazzToLaunch; private OnNavigationItemClickListener(Class<?> clazzToLaunch) { this.clazzToLaunch = clazzToLaunch; } @Override public void onClick(View v) { Intent intent = new Intent(mContext, clazzToLaunch); mContext.startActivity(intent); } } }
true
true
private View getNavigationDrawerItemView(NavigationDrawerItem item) { View v = mInflater.inflate(R.layout.drawer_list_item, null); TextView txtTitle = (TextView) v.findViewById(R.id.title); ImageView imgIcon = (ImageView) v.findViewById(R.id.icon); txtTitle.setText(item.getTitle()); imgIcon.setImageResource(item.getIconId()); v.setOnClickListener(new OnNavigationItemClickListener(item.getActivityClz())); return v; }
private View getNavigationDrawerItemView(NavigationDrawerItem item) { View v = mInflater.inflate(R.layout.drawer_list_item, null); TextView txtTitle = (TextView) v.findViewById(R.id.drawer_item_title); ImageView imgIcon = (ImageView) v.findViewById(R.id.drawer_item_icon); txtTitle.setText(item.getTitle()); imgIcon.setImageResource(item.getIconId()); v.setOnClickListener(new OnNavigationItemClickListener(item.getActivityClz())); return v; }
diff --git a/src/com/android/phone/EditFdnContactScreen.java b/src/com/android/phone/EditFdnContactScreen.java old mode 100644 new mode 100755 index cca9a9f6..2992b7dc --- a/src/com/android/phone/EditFdnContactScreen.java +++ b/src/com/android/phone/EditFdnContactScreen.java @@ -1,451 +1,458 @@ /* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.phone; import static android.view.Window.PROGRESS_VISIBILITY_OFF; import static android.view.Window.PROGRESS_VISIBILITY_ON; import android.app.Activity; import android.content.AsyncQueryHandler; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Intent; import android.content.res.Resources; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.provider.Contacts.PeopleColumns; import android.provider.Contacts.PhonesColumns; import android.telephony.PhoneNumberUtils; import android.text.Selection; import android.text.Spannable; import android.text.TextUtils; import android.text.method.DialerKeyListener; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; /** * Activity to let the user add or edit an FDN contact. */ public class EditFdnContactScreen extends Activity { private static final String LOG_TAG = PhoneGlobals.LOG_TAG; private static final boolean DBG = false; // Menu item codes private static final int MENU_IMPORT = 1; private static final int MENU_DELETE = 2; private static final String INTENT_EXTRA_NAME = "name"; private static final String INTENT_EXTRA_NUMBER = "number"; private static final int PIN2_REQUEST_CODE = 100; private String mName; private String mNumber; private String mPin2; private boolean mAddContact; private QueryHandler mQueryHandler; private EditText mNameField; private EditText mNumberField; private LinearLayout mPinFieldContainer; private Button mButton; private Handler mHandler = new Handler(); /** * Constants used in importing from contacts */ /** request code when invoking subactivity */ private static final int CONTACTS_PICKER_CODE = 200; /** projection for phone number query */ private static final String NUM_PROJECTION[] = {PeopleColumns.DISPLAY_NAME, PhonesColumns.NUMBER}; /** static intent to invoke phone number picker */ private static final Intent CONTACT_IMPORT_INTENT; static { CONTACT_IMPORT_INTENT = new Intent(Intent.ACTION_GET_CONTENT); CONTACT_IMPORT_INTENT.setType(android.provider.Contacts.Phones.CONTENT_ITEM_TYPE); } /** flag to track saving state */ private boolean mDataBusy; @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); resolveIntent(); getWindow().requestFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.edit_fdn_contact_screen); setupView(); setTitle(mAddContact ? R.string.add_fdn_contact : R.string.edit_fdn_contact); displayProgress(false); } /** * We now want to bring up the pin request screen AFTER the * contact information is displayed, to help with user * experience. * * Also, process the results from the contact picker. */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { if (DBG) log("onActivityResult request:" + requestCode + " result:" + resultCode); switch (requestCode) { case PIN2_REQUEST_CODE: Bundle extras = (intent != null) ? intent.getExtras() : null; if (extras != null) { mPin2 = extras.getString("pin2"); if (mAddContact) { addContact(); } else { updateContact(); } } else if (resultCode != RESULT_OK) { // if they cancelled, then we just cancel too. if (DBG) log("onActivityResult: cancelled."); finish(); } break; // look for the data associated with this number, and update // the display with it. case CONTACTS_PICKER_CODE: if (resultCode != RESULT_OK) { if (DBG) log("onActivityResult: cancelled."); return; } - Cursor cursor = getContentResolver().query(intent.getData(), + Cursor cursor = null; + try { + cursor = getContentResolver().query(intent.getData(), NUM_PROJECTION, null, null, null); - if ((cursor == null) || (!cursor.moveToFirst())) { - Log.w(LOG_TAG,"onActivityResult: bad contact data, no results found."); - return; + if ((cursor == null) || (!cursor.moveToFirst())) { + Log.w(LOG_TAG,"onActivityResult: bad contact data, no results found."); + return; + } + mNameField.setText(cursor.getString(0)); + mNumberField.setText(cursor.getString(1)); + } finally { + if (cursor != null) { + cursor.close(); + } } - mNameField.setText(cursor.getString(0)); - mNumberField.setText(cursor.getString(1)); break; } } /** * Overridden to display the import and delete commands. */ @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); Resources r = getResources(); // Added the icons to the context menu menu.add(0, MENU_IMPORT, 0, r.getString(R.string.importToFDNfromContacts)) .setIcon(R.drawable.ic_menu_contact); menu.add(0, MENU_DELETE, 0, r.getString(R.string.menu_delete)) .setIcon(android.R.drawable.ic_menu_delete); return true; } /** * Allow the menu to be opened ONLY if we're not busy. */ @Override public boolean onPrepareOptionsMenu(Menu menu) { boolean result = super.onPrepareOptionsMenu(menu); return mDataBusy ? false : result; } /** * Overridden to allow for handling of delete and import. */ @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_IMPORT: startActivityForResult(CONTACT_IMPORT_INTENT, CONTACTS_PICKER_CODE); return true; case MENU_DELETE: deleteSelected(); return true; } return super.onOptionsItemSelected(item); } private void resolveIntent() { Intent intent = getIntent(); mName = intent.getStringExtra(INTENT_EXTRA_NAME); mNumber = intent.getStringExtra(INTENT_EXTRA_NUMBER); mAddContact = TextUtils.isEmpty(mNumber); } /** * We have multiple layouts, one to indicate that the user needs to * open the keyboard to enter information (if the keybord is hidden). * So, we need to make sure that the layout here matches that in the * layout file. */ private void setupView() { mNameField = (EditText) findViewById(R.id.fdn_name); if (mNameField != null) { mNameField.setOnFocusChangeListener(mOnFocusChangeHandler); mNameField.setOnClickListener(mClicked); } mNumberField = (EditText) findViewById(R.id.fdn_number); if (mNumberField != null) { mNumberField.setKeyListener(DialerKeyListener.getInstance()); mNumberField.setOnFocusChangeListener(mOnFocusChangeHandler); mNumberField.setOnClickListener(mClicked); } if (!mAddContact) { if (mNameField != null) { mNameField.setText(mName); } if (mNumberField != null) { mNumberField.setText(mNumber); } } mButton = (Button) findViewById(R.id.button); if (mButton != null) { mButton.setOnClickListener(mClicked); } mPinFieldContainer = (LinearLayout) findViewById(R.id.pinc); } private String getNameFromTextField() { return mNameField.getText().toString(); } private String getNumberFromTextField() { return mNumberField.getText().toString(); } private Uri getContentURI() { return Uri.parse("content://icc/fdn"); } /** * @param number is voice mail number * @return true if number length is less than 20-digit limit * * TODO: Fix this logic. */ private boolean isValidNumber(String number) { return (number.length() <= 20); } private void addContact() { if (DBG) log("addContact"); final String number = PhoneNumberUtils.convertAndStrip(getNumberFromTextField()); if (!isValidNumber(number)) { handleResult(false, true); return; } Uri uri = getContentURI(); ContentValues bundle = new ContentValues(3); bundle.put("tag", getNameFromTextField()); bundle.put("number", number); bundle.put("pin2", mPin2); mQueryHandler = new QueryHandler(getContentResolver()); mQueryHandler.startInsert(0, null, uri, bundle); displayProgress(true); showStatus(getResources().getText(R.string.adding_fdn_contact)); } private void updateContact() { if (DBG) log("updateContact"); final String name = getNameFromTextField(); final String number = PhoneNumberUtils.convertAndStrip(getNumberFromTextField()); if (!isValidNumber(number)) { handleResult(false, true); return; } Uri uri = getContentURI(); ContentValues bundle = new ContentValues(); bundle.put("tag", mName); bundle.put("number", mNumber); bundle.put("newTag", name); bundle.put("newNumber", number); bundle.put("pin2", mPin2); mQueryHandler = new QueryHandler(getContentResolver()); mQueryHandler.startUpdate(0, null, uri, bundle, null, null); displayProgress(true); showStatus(getResources().getText(R.string.updating_fdn_contact)); } /** * Handle the delete command, based upon the state of the Activity. */ private void deleteSelected() { // delete ONLY if this is NOT a new contact. if (!mAddContact) { Intent intent = new Intent(); intent.setClass(this, DeleteFdnContactScreen.class); intent.putExtra(INTENT_EXTRA_NAME, mName); intent.putExtra(INTENT_EXTRA_NUMBER, mNumber); startActivity(intent); } finish(); } private void authenticatePin2() { Intent intent = new Intent(); intent.setClass(this, GetPin2Screen.class); startActivityForResult(intent, PIN2_REQUEST_CODE); } private void displayProgress(boolean flag) { // indicate we are busy. mDataBusy = flag; getWindow().setFeatureInt( Window.FEATURE_INDETERMINATE_PROGRESS, mDataBusy ? PROGRESS_VISIBILITY_ON : PROGRESS_VISIBILITY_OFF); // make sure we don't allow calls to save when we're // not ready for them. mButton.setClickable(!mDataBusy); } /** * Removed the status field, with preference to displaying a toast * to match the rest of settings UI. */ private void showStatus(CharSequence statusMsg) { if (statusMsg != null) { Toast.makeText(this, statusMsg, Toast.LENGTH_LONG) .show(); } } private void handleResult(boolean success, boolean invalidNumber) { if (success) { if (DBG) log("handleResult: success!"); showStatus(getResources().getText(mAddContact ? R.string.fdn_contact_added : R.string.fdn_contact_updated)); } else { if (DBG) log("handleResult: failed!"); if (invalidNumber) { showStatus(getResources().getText(R.string.fdn_invalid_number)); } else { // There's no way to know whether the failure is due to incorrect PIN2 or // an inappropriate phone number. showStatus(getResources().getText(R.string.pin2_or_fdn_invalid)); } } mHandler.postDelayed(new Runnable() { @Override public void run() { finish(); } }, 2000); } private final View.OnClickListener mClicked = new View.OnClickListener() { @Override public void onClick(View v) { if (mPinFieldContainer.getVisibility() != View.VISIBLE) { return; } if (v == mNameField) { mNumberField.requestFocus(); } else if (v == mNumberField) { mButton.requestFocus(); } else if (v == mButton) { // Authenticate the pin AFTER the contact information // is entered, and if we're not busy. if (!mDataBusy) { authenticatePin2(); } } } }; private final View.OnFocusChangeListener mOnFocusChangeHandler = new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { TextView textView = (TextView) v; Selection.selectAll((Spannable) textView.getText()); } } }; private class QueryHandler extends AsyncQueryHandler { public QueryHandler(ContentResolver cr) { super(cr); } @Override protected void onQueryComplete(int token, Object cookie, Cursor c) { } @Override protected void onInsertComplete(int token, Object cookie, Uri uri) { if (DBG) log("onInsertComplete"); displayProgress(false); handleResult(uri != null, false); } @Override protected void onUpdateComplete(int token, Object cookie, int result) { if (DBG) log("onUpdateComplete"); displayProgress(false); handleResult(result > 0, false); } @Override protected void onDeleteComplete(int token, Object cookie, int result) { } } private void log(String msg) { Log.d(LOG_TAG, "[EditFdnContact] " + msg); } }
false
true
protected void onActivityResult(int requestCode, int resultCode, Intent intent) { if (DBG) log("onActivityResult request:" + requestCode + " result:" + resultCode); switch (requestCode) { case PIN2_REQUEST_CODE: Bundle extras = (intent != null) ? intent.getExtras() : null; if (extras != null) { mPin2 = extras.getString("pin2"); if (mAddContact) { addContact(); } else { updateContact(); } } else if (resultCode != RESULT_OK) { // if they cancelled, then we just cancel too. if (DBG) log("onActivityResult: cancelled."); finish(); } break; // look for the data associated with this number, and update // the display with it. case CONTACTS_PICKER_CODE: if (resultCode != RESULT_OK) { if (DBG) log("onActivityResult: cancelled."); return; } Cursor cursor = getContentResolver().query(intent.getData(), NUM_PROJECTION, null, null, null); if ((cursor == null) || (!cursor.moveToFirst())) { Log.w(LOG_TAG,"onActivityResult: bad contact data, no results found."); return; } mNameField.setText(cursor.getString(0)); mNumberField.setText(cursor.getString(1)); break; } }
protected void onActivityResult(int requestCode, int resultCode, Intent intent) { if (DBG) log("onActivityResult request:" + requestCode + " result:" + resultCode); switch (requestCode) { case PIN2_REQUEST_CODE: Bundle extras = (intent != null) ? intent.getExtras() : null; if (extras != null) { mPin2 = extras.getString("pin2"); if (mAddContact) { addContact(); } else { updateContact(); } } else if (resultCode != RESULT_OK) { // if they cancelled, then we just cancel too. if (DBG) log("onActivityResult: cancelled."); finish(); } break; // look for the data associated with this number, and update // the display with it. case CONTACTS_PICKER_CODE: if (resultCode != RESULT_OK) { if (DBG) log("onActivityResult: cancelled."); return; } Cursor cursor = null; try { cursor = getContentResolver().query(intent.getData(), NUM_PROJECTION, null, null, null); if ((cursor == null) || (!cursor.moveToFirst())) { Log.w(LOG_TAG,"onActivityResult: bad contact data, no results found."); return; } mNameField.setText(cursor.getString(0)); mNumberField.setText(cursor.getString(1)); } finally { if (cursor != null) { cursor.close(); } } break; } }
diff --git a/vraptor-core/src/test/java/br/com/caelum/vraptor/interceptor/InstantiateInterceptorTest.java b/vraptor-core/src/test/java/br/com/caelum/vraptor/interceptor/InstantiateInterceptorTest.java index cd2fdd49..7bf2249f 100644 --- a/vraptor-core/src/test/java/br/com/caelum/vraptor/interceptor/InstantiateInterceptorTest.java +++ b/vraptor-core/src/test/java/br/com/caelum/vraptor/interceptor/InstantiateInterceptorTest.java @@ -1,73 +1,72 @@ /*** * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package br.com.caelum.vraptor.interceptor; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.IOException; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import br.com.caelum.vraptor.InterceptionException; import br.com.caelum.vraptor.core.InterceptorStack; import br.com.caelum.vraptor.view.DogController; import br.com.caelum.vraptor4.controller.ControllerMethod; import br.com.caelum.vraptor4.controller.DefaultBeanClass; public class InstantiateInterceptorTest { private @Mock InterceptorStack stack; private @Mock ControllerMethod method; @Before public void setup() { MockitoAnnotations.initMocks(this); } @Test public void shouldAcceptAlways() { assertTrue(new InstantiateInterceptor(null).accepts(null)); } @Test public void shouldUseContainerForNewComponent() throws InterceptionException, IOException { final DogController myDog = new DogController(); InstanceContainer container = new InstanceContainer(myDog); InstantiateInterceptor interceptor = new InstantiateInterceptor(container); when(method.getResource()).thenReturn(new DefaultBeanClass(DogController.class)); interceptor.intercept(stack, method, null); - assertTrue(container.isEmpty()); verify(stack).next(method, myDog); } @Test public void shouldNotInstantiateIfThereIsAlreadyAResource() throws InterceptionException, IOException { final DogController myDog = new DogController(); InstantiateInterceptor interceptor = new InstantiateInterceptor(null); interceptor.intercept(stack, method, myDog); verify(stack).next(method, myDog); } }
true
true
public void shouldUseContainerForNewComponent() throws InterceptionException, IOException { final DogController myDog = new DogController(); InstanceContainer container = new InstanceContainer(myDog); InstantiateInterceptor interceptor = new InstantiateInterceptor(container); when(method.getResource()).thenReturn(new DefaultBeanClass(DogController.class)); interceptor.intercept(stack, method, null); assertTrue(container.isEmpty()); verify(stack).next(method, myDog); }
public void shouldUseContainerForNewComponent() throws InterceptionException, IOException { final DogController myDog = new DogController(); InstanceContainer container = new InstanceContainer(myDog); InstantiateInterceptor interceptor = new InstantiateInterceptor(container); when(method.getResource()).thenReturn(new DefaultBeanClass(DogController.class)); interceptor.intercept(stack, method, null); verify(stack).next(method, myDog); }
diff --git a/project2/src/hmm/StateCollection.java b/project2/src/hmm/StateCollection.java index ed9d176..5889dad 100644 --- a/project2/src/hmm/StateCollection.java +++ b/project2/src/hmm/StateCollection.java @@ -1,142 +1,142 @@ package hmm; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; public class StateCollection { HashMap<String, State> states; HashSet<String> state_names; public State startTag() { return states.get(""); } public StateCollection() { states = new HashMap<String, State>(); state_names = new HashSet<String>(); } public void addStateTansitionObservation(String word, String stateString, String previousStateString) { if (previousStateString != "") state_names.add(previousStateString); State previousState; State state; // load previous state if (!states.containsKey(previousStateString)) { previousState = new State(previousStateString); states.put(previousStateString, previousState); } else { previousState = states.get(previousStateString); } // load current state if (!states.containsKey(stateString)) { state = new State(stateString); states.put(stateString, state); } else { state = states.get(stateString); } state.addWordEmissionObservation(word); previousState.addStateTransitionObservation(state.name); } public void addFinalStateTransitionObservation(String previousState) { state_names.add(previousState); states.get(previousState).addStateTransitionObservation(null); } /** * Calculate the probability of a sentence and a tag sequence * @param sentence word/tag pairs which make up the sentence * @return */ public double calculateProbabilityofSentenceWithStates( ArrayList<String> sentence) { double probability = 1; String old_tag = ""; for (String wordPair : sentence) { String[] splitting = wordPair.split("/"); String word = splitting[0]; String tag = splitting[1]; // Multiply with tag-to-tag probability probability *= states.get(old_tag).nextStateProbability(tag); // Multiply with tag-to-word probability probability *= states.get(tag).wordEmittingProbability(word); old_tag = tag; } // Multiply with final-tag probability probability *= states.get(old_tag).nextStateProbability(null); return probability; } public ArrayList<String> calculateStatesofSentence( ArrayList<String> sentence) { ArrayList<String> result = new ArrayList<String>(); HashMap<String, Double> probabilities = new HashMap<String, Double>(); String[] splitting = sentence.get(0).split("/"); String first_word = splitting[0]; // Calculate starting probabilities for (String state : state_names) { double value = states.get("").nextStateProbability(state); value *= states.get(state).wordEmittingProbability(first_word); probabilities.put(state, value); } result.add(getMaxState(probabilities)); // Calculate all other probabilities HashMap<String, Double> new_probabilities = new HashMap<String, Double>(); - for (int i=1; i<sentence.size(); i++) { - splitting = sentence.get(1).split("/"); + for (int i=1; i<sentence.size(); i++) { + splitting = sentence.get(i).split("/"); String word = splitting[0]; for (String state : state_names) { double max_value = 0; for (String previous_state : state_names) { double value = probabilities.get(previous_state); value *= states.get(previous_state).nextStateProbability(state); value *= states.get(state).wordEmittingProbability(word); if (value > max_value) max_value = value; } new_probabilities.put(state, max_value); } result.add(getMaxState(new_probabilities)); probabilities = new_probabilities; new_probabilities = new HashMap<String, Double>(); } return result; } private static String getMaxState(HashMap<String, Double> probabilities) { String max_string = ""; double max_probability = 0; for (String key : probabilities.keySet()) { double new_probability = probabilities.get(key); if (new_probability > max_probability) { max_probability = new_probability; max_string = key; } } return max_string; } }
true
true
public ArrayList<String> calculateStatesofSentence( ArrayList<String> sentence) { ArrayList<String> result = new ArrayList<String>(); HashMap<String, Double> probabilities = new HashMap<String, Double>(); String[] splitting = sentence.get(0).split("/"); String first_word = splitting[0]; // Calculate starting probabilities for (String state : state_names) { double value = states.get("").nextStateProbability(state); value *= states.get(state).wordEmittingProbability(first_word); probabilities.put(state, value); } result.add(getMaxState(probabilities)); // Calculate all other probabilities HashMap<String, Double> new_probabilities = new HashMap<String, Double>(); for (int i=1; i<sentence.size(); i++) { splitting = sentence.get(1).split("/"); String word = splitting[0]; for (String state : state_names) { double max_value = 0; for (String previous_state : state_names) { double value = probabilities.get(previous_state); value *= states.get(previous_state).nextStateProbability(state); value *= states.get(state).wordEmittingProbability(word); if (value > max_value) max_value = value; } new_probabilities.put(state, max_value); } result.add(getMaxState(new_probabilities)); probabilities = new_probabilities; new_probabilities = new HashMap<String, Double>(); } return result; }
public ArrayList<String> calculateStatesofSentence( ArrayList<String> sentence) { ArrayList<String> result = new ArrayList<String>(); HashMap<String, Double> probabilities = new HashMap<String, Double>(); String[] splitting = sentence.get(0).split("/"); String first_word = splitting[0]; // Calculate starting probabilities for (String state : state_names) { double value = states.get("").nextStateProbability(state); value *= states.get(state).wordEmittingProbability(first_word); probabilities.put(state, value); } result.add(getMaxState(probabilities)); // Calculate all other probabilities HashMap<String, Double> new_probabilities = new HashMap<String, Double>(); for (int i=1; i<sentence.size(); i++) { splitting = sentence.get(i).split("/"); String word = splitting[0]; for (String state : state_names) { double max_value = 0; for (String previous_state : state_names) { double value = probabilities.get(previous_state); value *= states.get(previous_state).nextStateProbability(state); value *= states.get(state).wordEmittingProbability(word); if (value > max_value) max_value = value; } new_probabilities.put(state, max_value); } result.add(getMaxState(new_probabilities)); probabilities = new_probabilities; new_probabilities = new HashMap<String, Double>(); } return result; }
diff --git a/org.emftext.sdk.concretesyntax.resource.cs.post_processing/src/org/emftext/sdk/syntax_analysis/OptionsAnalyser.java b/org.emftext.sdk.concretesyntax.resource.cs.post_processing/src/org/emftext/sdk/syntax_analysis/OptionsAnalyser.java index b74a90687..aa9db1940 100644 --- a/org.emftext.sdk.concretesyntax.resource.cs.post_processing/src/org/emftext/sdk/syntax_analysis/OptionsAnalyser.java +++ b/org.emftext.sdk.concretesyntax.resource.cs.post_processing/src/org/emftext/sdk/syntax_analysis/OptionsAnalyser.java @@ -1,237 +1,241 @@ /******************************************************************************* * Copyright (c) 2006-2010 * Software Technology Group, Dresden University of Technology * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Software Technology Group - TU Dresden, Germany * - initial API and implementation ******************************************************************************/ package org.emftext.sdk.syntax_analysis; import static org.emftext.sdk.OptionManager.TOKEN_SPACE_VALUE_AUTOMATIC; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.emftext.sdk.AbstractPostProcessor; import org.emftext.sdk.OptionManager; import org.emftext.sdk.concretesyntax.ConcreteSyntax; import org.emftext.sdk.concretesyntax.Option; import org.emftext.sdk.concretesyntax.OptionTypes; import org.emftext.sdk.concretesyntax.resource.cs.mopp.CsResource; import org.emftext.sdk.concretesyntax.resource.cs.mopp.ECsProblemType; import org.emftext.sdk.quickfixes.RemoveElementQuickFix; /** * A post processor that checks whether the values for all code generation * options are valid. */ public class OptionsAnalyser extends AbstractPostProcessor { private static final String TOKEN_SPACE_VALUE_ERROR_MESSAGE = "Value must be positive integers or '" + TOKEN_SPACE_VALUE_AUTOMATIC + "'."; private static final String DUPLICATE_OPTION_FOUND = "Found duplicate option '%s' with %s value."; private final List<OptionTypes> BOOLEAN_OPTIONS; private final List<OptionTypes> STRING_OPTIONS; private final List<OptionTypes> NON_STANDARD_OPTIONS; public OptionsAnalyser() { BOOLEAN_OPTIONS = OptionManager.INSTANCE.getBooleanOptions(); STRING_OPTIONS = OptionManager.INSTANCE.getStringOptions(); NON_STANDARD_OPTIONS = OptionManager.INSTANCE.getNonStandardOptions(); } @Override public void analyse(CsResource resource, ConcreteSyntax syntax) { // first analyze options individually List<Option> options = syntax.getOptions(); for (Option option : options) { analyseOption(resource, option); } // second, analyze option conflicts analyseOptionConflicts(resource, syntax, options); // third, analyze that options are set at most once analyseDuplicateOption(resource, syntax, options); } private void analyseDuplicateOption(CsResource resource, ConcreteSyntax syntax, List<Option> options) { Map<OptionTypes, Option> setOptions = new LinkedHashMap<OptionTypes, Option>(); for (Option option : options) { OptionTypes type = option.getType(); if (setOptions.keySet().contains(type)) { // option was set before - compare values Option optionBefore = setOptions.get(type); String valueBefore = optionBefore.getValue(); if (valueBefore.equals(option.getValue())) { // values are the same - issues a warning String message = String.format(DUPLICATE_OPTION_FOUND, option.getType().getLiteral(), "same"); addProblem(resource, ECsProblemType.DUPLICATE_OPTION_WITH_SAME_VALUE, message, option, new RemoveElementQuickFix("Remove option", option)); } else { // values are different - issues an error String message = String.format(DUPLICATE_OPTION_FOUND, option.getType().getLiteral(), "different"); addProblem(resource, ECsProblemType.DUPLICATE_OPTION_WITH_DIFFERENT_VALUE, message, option, new RemoveElementQuickFix("Remove option", option)); } } setOptions.put(type, option); } } /** * Checks whether the grammar contains conflicting options. */ private void analyseOptionConflicts(CsResource resource, ConcreteSyntax syntax, List<Option> options) { checkForClassicPrinterAutomaticTokenSpaceConflict(resource, syntax, options); checkPluginIdConflict(resource, syntax, options); } private void checkPluginIdConflict( CsResource resource, ConcreteSyntax syntax, List<Option> options) { OptionManager optionManager = OptionManager.INSTANCE; String antlrPluginID = optionManager.getStringOptionValue(syntax, OptionTypes.ANTLR_PLUGIN_ID); String resourcePluginID = optionManager.getStringOptionValue(syntax, OptionTypes.RESOURCE_PLUGIN_ID); String resourceUIPluginID = optionManager.getStringOptionValue(syntax, OptionTypes.RESOURCE_UI_PLUGIN_ID); + int setPluginIDs = 0; Set<String> pluginIDs = new LinkedHashSet<String>(); if (antlrPluginID != null) { pluginIDs.add(antlrPluginID); + setPluginIDs++; } if (resourcePluginID != null) { pluginIDs.add(resourcePluginID); + setPluginIDs++; } - if (pluginIDs.size() == 1) { + if (pluginIDs.size() > 0 && pluginIDs.size() < setPluginIDs) { // antlrPluginID == resourcePluginID String message = "The ID for the resource plug-ins must be different from the ANTLR commons plug-in."; addProblem( resource, ECsProblemType.PLUGIN_ID_CONFLICT, message, optionManager.findOptionByType(options, OptionTypes.RESOURCE_PLUGIN_ID) ); if (resourceUIPluginID != null) { pluginIDs.add(resourceUIPluginID); } if (pluginIDs.size() == 1) { // antlrPluginID == resourcePluginID == resourceUIPluginID addProblem( resource, ECsProblemType.PLUGIN_ID_CONFLICT, message, optionManager.findOptionByType(options, OptionTypes.RESOURCE_UI_PLUGIN_ID) ); } } else { if (resourceUIPluginID != null) { pluginIDs.add(resourceUIPluginID); + setPluginIDs++; } - if (pluginIDs.size() > 0 && pluginIDs.size() < 3) { + if (pluginIDs.size() > 0 && pluginIDs.size() < setPluginIDs) { // (antlrPluginID || resourcePluginID) == resourceUIPluginID addProblem( resource, ECsProblemType.PLUGIN_ID_CONFLICT, "The ID for the resource UI plug-in must be different from the ANTLR commons plug-in and the resource plug-in.", optionManager.findOptionByType(options, OptionTypes.RESOURCE_UI_PLUGIN_ID) ); } else { // all IDs are different or null, which is perfectly fine } } } private void checkForClassicPrinterAutomaticTokenSpaceConflict( CsResource resource, ConcreteSyntax syntax, List<Option> options) { OptionManager optionManager = OptionManager.INSTANCE; boolean useClassicPrinter = optionManager.getBooleanOptionValue(syntax, OptionTypes.USE_CLASSIC_PRINTER); if (useClassicPrinter) { String tokenSpace = optionManager.getStringOptionValue(syntax, OptionTypes.TOKENSPACE); if (TOKEN_SPACE_VALUE_AUTOMATIC.equals(tokenSpace)) { addProblem( resource, ECsProblemType.AUTOMATIC_TOKEN_SPACE_CONFLICT_WITH_CLASSIC_PRINTER, "Value '" + TOKEN_SPACE_VALUE_AUTOMATIC + "' is not compatible with the classic printer.", optionManager.findOptionByType(options, OptionTypes.TOKENSPACE) ); } } } private void analyseOption(CsResource resource, Option option) { OptionTypes type = option.getType(); String value = option.getValue(); checkValue(resource, option, type, value); checkForNonStandard(resource, option, type); } private void checkForNonStandard(CsResource resource, Option option, OptionTypes type) { if (NON_STANDARD_OPTIONS.contains(type)) { addProblem(resource, ECsProblemType.NON_STANDARD_OPTION, type.getLiteral() + " is a non-standard option, which might not be supported in future versions.", option); } } private void checkValue(CsResource resource, Option option, OptionTypes type, String value) { if (BOOLEAN_OPTIONS.contains(type)) { checkBooleanValue(resource, option, type, value); } else if (type == OptionTypes.PARSER_GENERATOR) { checkParserGeneratorValue(resource, option, value); } else if (STRING_OPTIONS.contains(type)) { // string values are accepted as they are } else if (type == OptionTypes.TOKENSPACE) { checkTokenspaceValue(resource, option, value); } else if (type == OptionTypes.DEFAULT_TOKEN_NAME) { checkDefaultTokenNameValue(resource, option, value); } else { addProblem(resource, ECsProblemType.UNKNOWN_OPTION, "Unknown option (" + type + ").", option); } } private void checkParserGeneratorValue(CsResource resource, Option option, String value) { if (!OptionManager.ANTLR.equals(value) && !OptionManager.SCALES.equals(value)) { addProblem(resource, ECsProblemType.INVALID_PARSER_GENERATOR, "Invalid parser generator (Valid generators are: " + OptionManager.ANTLR + ", " + OptionManager.SCALES + ").", option); } } private void checkDefaultTokenNameValue(CsResource resource, Option option, String value) { if (value == null || value.length() < 2) { addProblem(resource, ECsProblemType.INVALID_DEFAULT_TOKEN_NAME, "Please provide a String with at least two letters.", option); } } private void checkTokenspaceValue(CsResource resource, Option option, String value) { if (TOKEN_SPACE_VALUE_AUTOMATIC.equals(value)) { return; } try { int v = Integer.parseInt(value); if (v < 0) { addProblem(resource, ECsProblemType.TOKEN_SPACE_VALUE_MUST_BE_POSITIVE_INTEGER, TOKEN_SPACE_VALUE_ERROR_MESSAGE, option); } } catch (NumberFormatException e) { addProblem(resource, ECsProblemType.TOKEN_SPACE_VALUE_MUST_BE_INTEGER, TOKEN_SPACE_VALUE_ERROR_MESSAGE, option); } } private void checkBooleanValue(CsResource resource, Option option, OptionTypes type, String value) { boolean isTrue = "true".equals(value); boolean isFalse = "false".equals(value); if (!isTrue && !isFalse) { addProblem(resource, ECsProblemType.OPTION_VALUE_MUST_BE_BOOLEAN, "Only boolean values: 'true' or 'false' are supported.", option); } } }
false
true
private void checkPluginIdConflict( CsResource resource, ConcreteSyntax syntax, List<Option> options) { OptionManager optionManager = OptionManager.INSTANCE; String antlrPluginID = optionManager.getStringOptionValue(syntax, OptionTypes.ANTLR_PLUGIN_ID); String resourcePluginID = optionManager.getStringOptionValue(syntax, OptionTypes.RESOURCE_PLUGIN_ID); String resourceUIPluginID = optionManager.getStringOptionValue(syntax, OptionTypes.RESOURCE_UI_PLUGIN_ID); Set<String> pluginIDs = new LinkedHashSet<String>(); if (antlrPluginID != null) { pluginIDs.add(antlrPluginID); } if (resourcePluginID != null) { pluginIDs.add(resourcePluginID); } if (pluginIDs.size() == 1) { // antlrPluginID == resourcePluginID String message = "The ID for the resource plug-ins must be different from the ANTLR commons plug-in."; addProblem( resource, ECsProblemType.PLUGIN_ID_CONFLICT, message, optionManager.findOptionByType(options, OptionTypes.RESOURCE_PLUGIN_ID) ); if (resourceUIPluginID != null) { pluginIDs.add(resourceUIPluginID); } if (pluginIDs.size() == 1) { // antlrPluginID == resourcePluginID == resourceUIPluginID addProblem( resource, ECsProblemType.PLUGIN_ID_CONFLICT, message, optionManager.findOptionByType(options, OptionTypes.RESOURCE_UI_PLUGIN_ID) ); } } else { if (resourceUIPluginID != null) { pluginIDs.add(resourceUIPluginID); } if (pluginIDs.size() > 0 && pluginIDs.size() < 3) { // (antlrPluginID || resourcePluginID) == resourceUIPluginID addProblem( resource, ECsProblemType.PLUGIN_ID_CONFLICT, "The ID for the resource UI plug-in must be different from the ANTLR commons plug-in and the resource plug-in.", optionManager.findOptionByType(options, OptionTypes.RESOURCE_UI_PLUGIN_ID) ); } else { // all IDs are different or null, which is perfectly fine } } }
private void checkPluginIdConflict( CsResource resource, ConcreteSyntax syntax, List<Option> options) { OptionManager optionManager = OptionManager.INSTANCE; String antlrPluginID = optionManager.getStringOptionValue(syntax, OptionTypes.ANTLR_PLUGIN_ID); String resourcePluginID = optionManager.getStringOptionValue(syntax, OptionTypes.RESOURCE_PLUGIN_ID); String resourceUIPluginID = optionManager.getStringOptionValue(syntax, OptionTypes.RESOURCE_UI_PLUGIN_ID); int setPluginIDs = 0; Set<String> pluginIDs = new LinkedHashSet<String>(); if (antlrPluginID != null) { pluginIDs.add(antlrPluginID); setPluginIDs++; } if (resourcePluginID != null) { pluginIDs.add(resourcePluginID); setPluginIDs++; } if (pluginIDs.size() > 0 && pluginIDs.size() < setPluginIDs) { // antlrPluginID == resourcePluginID String message = "The ID for the resource plug-ins must be different from the ANTLR commons plug-in."; addProblem( resource, ECsProblemType.PLUGIN_ID_CONFLICT, message, optionManager.findOptionByType(options, OptionTypes.RESOURCE_PLUGIN_ID) ); if (resourceUIPluginID != null) { pluginIDs.add(resourceUIPluginID); } if (pluginIDs.size() == 1) { // antlrPluginID == resourcePluginID == resourceUIPluginID addProblem( resource, ECsProblemType.PLUGIN_ID_CONFLICT, message, optionManager.findOptionByType(options, OptionTypes.RESOURCE_UI_PLUGIN_ID) ); } } else { if (resourceUIPluginID != null) { pluginIDs.add(resourceUIPluginID); setPluginIDs++; } if (pluginIDs.size() > 0 && pluginIDs.size() < setPluginIDs) { // (antlrPluginID || resourcePluginID) == resourceUIPluginID addProblem( resource, ECsProblemType.PLUGIN_ID_CONFLICT, "The ID for the resource UI plug-in must be different from the ANTLR commons plug-in and the resource plug-in.", optionManager.findOptionByType(options, OptionTypes.RESOURCE_UI_PLUGIN_ID) ); } else { // all IDs are different or null, which is perfectly fine } } }
diff --git a/src/me/libraryaddict/Hungergames/Managers/ConfigManager.java b/src/me/libraryaddict/Hungergames/Managers/ConfigManager.java index 5ff0959..12a9837 100644 --- a/src/me/libraryaddict/Hungergames/Managers/ConfigManager.java +++ b/src/me/libraryaddict/Hungergames/Managers/ConfigManager.java @@ -1,623 +1,623 @@ package me.libraryaddict.Hungergames.Managers; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import me.libraryaddict.Hungergames.Hungergames; import me.libraryaddict.Hungergames.Types.HungergamesApi; import me.libraryaddict.Hungergames.Utilities.UpdateChecker; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; public class ConfigManager { private String alivePrefix; private double border; private double borderClosesIn; private int chestLayers; private List<String> commandsToRunBeforeShutdown; private String currentVersion; private boolean disableMetrics; private boolean displayMessages; private boolean displayScoreboards; private ItemStack feast; private ArrayList<Integer> feastBroadcastTimes = new ArrayList<Integer>(); private ItemStack feastGround; private ItemStack feastInsides; private int feastSize; private boolean feastTnt; private boolean fireSpread; private boolean flyPreGame; private boolean forceCords; private int gameShutdownDelay; private ArrayList<Integer> gameStartingBroadcastTimes = new ArrayList<Integer>(); private boolean generatePillars; private Hungergames hg; private int invincibility; private ArrayList<Integer> invincibilityBroadcastTimes = new ArrayList<Integer>(); private boolean kickOnDeath; private boolean kitSelector; private ItemStack kitSelectorBack; private boolean kitSelectorDynamicSize; private ItemStack kitSelectorForward; private ItemStack kitSelectorIcon; private int kitSelectorInventorySize; private String latestVersion = null; private boolean invisSpectators; private int minPlayers; public int mobSpawnChance; private boolean mushroomStew; private int mushroomStewRestores; private boolean mysqlEnabled; private ItemStack pillarCorner; private ItemStack pillarInsides; private boolean roundedBorder; private boolean shortenNames; private String spectatingPrefix; private boolean spectatorChat; private ItemStack spectatorItemBack; private ItemStack spectatorItemForwards; private boolean spectators; private int timeOfDay = 0; private int timeTillFeast; private UpdateChecker updateChecker; private int wonBroadcastsDelay; private int x; private int z; public ConfigManager() { hg = HungergamesApi.getHungergames(); loadConfig(); } /** * @param Current * time * @return Should it advertise about the feast? */ public boolean advertiseFeast(int time) { time = timeTillFeast - time; if (time % (60 * 5) == 0) return true; if (time <= 180) { if (time % 60 == 0) return true; } else if (time % 180 == 0) return true; return feastBroadcastTimes.contains(time); } /** * @param time * till game starts * @return Should it advertise the game is starting? */ public boolean advertiseGameStarting(int time) { if (time > -180) { if (time % 60 == 0) return true; } else if (time % 180 == 0 || time % (5 * 60) == 0) return true; return gameStartingBroadcastTimes.contains(time); } /** * @param Currenttime * @return Should it advertise about invincibility? */ public boolean advertiseInvincibility(int time) { time = invincibility - time; if (time <= 180) { if (time % 60 == 0) return true; } else if (time % 180 == 0 || time % (5 * 60) == 0) return true; return invincibilityBroadcastTimes.contains(time); } /** * Makes the update checker check for a update */ public void checkUpdate() throws Exception { updateChecker = new UpdateChecker(); updateChecker.checkUpdate(getCurrentVersion()); latestVersion = updateChecker.getLatestVersion(); if (latestVersion != null) { latestVersion = "v" + latestVersion; for (Player p : Bukkit.getOnlinePlayers()) if (p.hasPermission("hungergames.update")) p.sendMessage(String.format(HungergamesApi.getTranslationManager().getMessagePlayerUpdateAvailable(), getCurrentVersion(), getLatestVersion())); } } /** * Check for a update */ /** * @return Should it display messages about the game starting in bla bla? */ public boolean displayMessages() { return displayMessages; } /** * @return Should it use scoreboards at all? */ public boolean displayScoreboards() { return displayScoreboards; } /** * @return The feast starts in T-Minus <Seconds> */ public int feastStartsIn() { return timeTillFeast - hg.currentTime; } /** * @return Should the plugin force the worlds spawn to be here */ public boolean forceCords() { return forceCords; } /** * @return Should it generate pillars beneath spawn to make it realistic */ public boolean generatePillars() { return generatePillars; } public String getAlivePrefix() { return alivePrefix; } /** * @return How much does the border close in per second? */ public double getBorderCloseInRate() { return borderClosesIn; } /** * @return Whats the current size of the border? */ public double getBorderSize() { return border; } /** * @return How many layers high is the feast */ public int getChestLayers() { return chestLayers; } /** * Get the commands to run before shutdown */ public List<String> getCommandsToRunBeforeShutdown() { return commandsToRunBeforeShutdown; } public String getCurrentVersion() { return currentVersion; } /** * @return Whats the material used for the outside covering of the feast */ public ItemStack getFeast() { return feast; } /** * @return Whats the material used for the feast ground */ public ItemStack getFeastGround() { return feastGround; } /** * @return Whats the material used for the inside of the feast where no one sees */ public ItemStack getFeastInsides() { return feastInsides; } /** * @return How big is the feast generation */ public int getFeastSize() { return feastSize; } /** * @return How much delay before shutting the game down? */ public int getGameShutdownDelay() { return gameShutdownDelay; } /** * @return How long does invincibility last? */ public int getInvincibilityTime() { return invincibility; } /** * @return Get the item which will is the kit selectors 'forward' */ public ItemStack getKitSelectorBack() { return kitSelectorBack; } /** * @return Get the item which will is the kit selectors 'back' */ public ItemStack getKitSelectorForward() { return kitSelectorForward; } /** * @return Get the item which will be displayed as the kit selector */ public ItemStack getKitSelectorIcon() { return kitSelectorIcon; } public int getKitSelectorInventorySize() { return kitSelectorInventorySize; } /** * Get the latest version released */ public String getLatestVersion() { return latestVersion; } /** * @return How many players are required to start the game */ public int getMinPlayers() { return minPlayers; } /** * What chance does a animal have of spawning */ public int getMobSpawnChance() { return mobSpawnChance; } /** * @return Whats the material used for the pillars corners */ public ItemStack getPillarCorner() { return pillarCorner; } /** * @return Whats the material used for the rest of the pillars */ public ItemStack getPillarInsides() { return pillarInsides; } /** * @return Whats the X its forcing spawn to be */ public int getSpawnX() { return x; } /** * @return Whats the Z its forcing spawn to be */ public int getSpawnZ() { return z; } public String getSpectatingPrefix() { return spectatingPrefix; } public ItemStack getSpectatorInventoryBack() { return spectatorItemBack; } public ItemStack getSpectatorInventoryForwards() { return spectatorItemForwards; } /** * @return How long until the feast starts? */ public int getTimeFeastStarts() { return timeTillFeast; } public int getTimeOfDay() { return timeOfDay; } /** * @return How much delay before crowing the name of the winner? */ public int getWinnerBroadcastDelay() { return wonBroadcastsDelay; } /** * @return Invincibility wears off in T-Minus <Seconds> */ public int invincibilityWearsOffIn() { return invincibility - hg.currentTime; } /** * @return Does the topmost tnt hidden under the enchanting table ignite on punch? */ public boolean isFeastTntIgnite() { return feastTnt; } /** * @return Should there be forest fires before the game starts? */ public boolean isFireSpreadDisabled() { return fireSpread; } public boolean isFlyPreGame() { return flyPreGame; } /** * @return Does the game kick the players on death */ public boolean isKickOnDeath() { return kickOnDeath; } public boolean isKitSelectorDynamicSize() { return kitSelectorDynamicSize; } public boolean isMetricsDisabled() { return disableMetrics; } /** * @return Is mushroom stew enabled? */ public boolean isMushroomStew() { return mushroomStew; } /** * @return Is the plugin using mysql */ public boolean isMySqlEnabled() { return mysqlEnabled; } public boolean isRoundedBorder() { return roundedBorder; } /** * Is everyones name shortened to view their killstreak in tab */ public boolean isShortenedNames() { return shortenNames; } /** * @return Is spectator chat hidden from mortal eyes to prevent the giving away of tactics and distractions? */ public boolean isSpectatorChatHidden() { return spectatorChat; } /** * @return Are players allowed to join a game in progress? */ public boolean isSpectatorsEnabled() { return spectators; } /** * Reload the config. This doesn't reload some values however */ public void loadConfig() { hg.saveDefaultConfig(); final TranslationManager cm = HungergamesApi.getTranslationManager(); if (Bukkit.getServer().getAllowEnd() && hg.getConfig().getBoolean("DisableEnd", true)) { YamlConfiguration config = YamlConfiguration.loadConfiguration(new File("bukkit.yml")); config.set("settings.allow-end", false); try { config.save(new File("bukkit.yml")); } catch (IOException e) { e.printStackTrace(); } System.out.println(cm.getLoggerDisabledEnd()); } ReflectionManager rm = HungergamesApi.getReflectionManager(); if (hg.getServer().getAllowNether() && hg.getConfig().getBoolean("DisableNether", true)) { rm.setPropertiesConfig("allow-nether", false); rm.savePropertiesConfig(); System.out.println(cm.getLoggerDisabledNether()); } if (hg.getServer().getSpawnRadius() > 0 && hg.getConfig().getBoolean("ChangeSpawnLimit", true)) { rm.setPropertiesConfig("spawn-protection", 0); rm.savePropertiesConfig(); System.out.println(cm.getLoggerChangedSpawnRadius()); } if ((Integer) rm.getPropertiesConfig("max-build-height", 128) > 128 && hg.getConfig().getBoolean("ChangeHeightLimit", true)) { rm.setPropertiesConfig("max-build-height", 128); rm.savePropertiesConfig(); System.out.println(cm.getLoggerChangedHeightLimit()); } currentVersion = "v" + hg.getDescription().getVersion(); if (hg.getConfig().getBoolean("CheckUpdates")) Bukkit.getScheduler().scheduleAsyncDelayedTask(hg, new Runnable() { public void run() { try { checkUpdate(); } catch (Exception ex) { System.out.print(String.format(cm.getLoggerFailedToCheckUpdate(), ex.getMessage())); } } }); hg.currentTime = -Math.abs(hg.getConfig().getInt("Countdown", 270)); mysqlEnabled = hg.getConfig().getBoolean("UseMySql", false); displayScoreboards = hg.getConfig().getBoolean("Scoreboards", false); displayMessages = hg.getConfig().getBoolean("Messages", true); minPlayers = hg.getConfig().getInt("MinPlayers", 2); fireSpread = hg.getConfig().getBoolean("DisableFireSpread", false); wonBroadcastsDelay = hg.getConfig().getInt("WinnerBroadcastingDelay"); gameShutdownDelay = hg.getConfig().getInt("GameShutdownDelay"); feastSize = hg.getConfig().getInt("FeastSize", 20); invincibility = hg.getConfig().getInt("Invincibility", 120); chestLayers = hg.getConfig().getInt("ChestLayers", 500); timeTillFeast = hg.getConfig().getInt("TimeTillFeast", 500); spectatorChat = !hg.getConfig().getBoolean("SpectatorChat", true); shortenNames = hg.getConfig().getBoolean("ShortenNames"); spectators = hg.getConfig().getBoolean("Spectators", true); kickOnDeath = hg.getConfig().getBoolean("KickOnDeath"); mushroomStew = hg.getConfig().getBoolean("MushroomStew", false); mushroomStewRestores = hg.getConfig().getInt("MushroomStewRestores", 5); kitSelector = hg.getConfig().getBoolean("EnableKitSelector", true); feastTnt = hg.getConfig().getBoolean("FeastTnt", true); feastGround = parseItem(hg.getConfig().getString("FeastGround")); feast = parseItem(hg.getConfig().getString("Feast")); generatePillars = hg.getConfig().getBoolean("Pillars", true); feastInsides = parseItem(hg.getConfig().getString("FeastInsides")); pillarCorner = parseItem(hg.getConfig().getString("PillarCorner")); pillarInsides = parseItem(hg.getConfig().getString("PillarInsides")); forceCords = hg.getConfig().getBoolean("ForceCords", true); x = hg.getConfig().getInt("ForceX", 0); z = hg.getConfig().getInt("ForceZ", 0); kitSelectorIcon = parseItem(hg.getConfig().getString("KitSelectorIcon")); if (kitSelectorIcon == null) kitSelectorIcon = new ItemStack(Material.FEATHER); kitSelectorBack = parseItem(hg.getConfig().getString("KitSelectorForward")); if (kitSelectorBack == null) kitSelectorBack = new ItemStack(Material.SUGAR_CANE_BLOCK); kitSelectorForward = parseItem(hg.getConfig().getString("KitSelectorBack")); if (kitSelectorForward == null) kitSelectorForward = new ItemStack(Material.SUGAR_CANE_BLOCK); spectatorItemBack = parseItem(hg.getConfig().getString("SpectatorInventoryForward")); if (spectatorItemBack == null) spectatorItemBack = new ItemStack(Material.SUGAR_CANE_BLOCK); spectatorItemForwards = parseItem(hg.getConfig().getString("SpectatorInventoryBack")); if (spectatorItemForwards == null) spectatorItemForwards = new ItemStack(Material.SUGAR_CANE_BLOCK); kitSelectorDynamicSize = hg.getConfig().getBoolean("KitSelectorDynamicSize"); kitSelectorInventorySize = hg.getConfig().getInt("KitSelectorInventorySize"); mobSpawnChance = hg.getConfig().getInt("MobSpawnChance"); if (hg.getConfig().contains("CommandsToRunBeforeShutdown")) commandsToRunBeforeShutdown = hg.getConfig().getStringList("CommandsToRunBeforeShutdown"); else commandsToRunBeforeShutdown = new ArrayList<String>(); disableMetrics = hg.getConfig().getBoolean("DisableMetrics"); flyPreGame = hg.getConfig().getBoolean("FlyPregame"); if (hg.getConfig().getBoolean("ChangeAlivePrefix")) alivePrefix = hg.getConfig().getString("AlivePrefix"); if (hg.getConfig().getBoolean("ChangeSpectatingPrefix")) spectatingPrefix = hg.getConfig().getString("SpectatingPrefix"); - invisSpectators = hg.getConfig().getBoolean("InvisibleSpectators"); + invisSpectators = !hg.getConfig().getBoolean("InvisibleSpectators"); // Create the times where it broadcasts and advertises the feast feastBroadcastTimes.clear(); for (int i = 1; i < 6; i++) feastBroadcastTimes.add(i); feastBroadcastTimes.add(30); feastBroadcastTimes.add(15); feastBroadcastTimes.add(10); invincibilityBroadcastTimes.clear(); // Create the times where it advertises invincibility for (int i = 1; i <= 5; i++) invincibilityBroadcastTimes.add(i); invincibilityBroadcastTimes.add(30); invincibilityBroadcastTimes.add(15); invincibilityBroadcastTimes.add(10); // Create the times where it advertises when the game starts gameStartingBroadcastTimes.clear(); for (int i = 1; i <= 5; i++) gameStartingBroadcastTimes.add(-i); gameStartingBroadcastTimes.add(-30); gameStartingBroadcastTimes.add(-15); gameStartingBroadcastTimes.add(-10); } /** * @return How much hearts or hunger should soup restore */ public int mushroomStewRestores() { return mushroomStewRestores; } /** * @param String * containing item * @return Itemstack parsed from the string */ public ItemStack parseItem(String string) { String[] args = string.split(" "); int id = hg.isNumeric(args[0]) ? Integer.parseInt(args[0]) : (Material.getMaterial(args[0].toUpperCase()) == null ? Material.AIR : Material.getMaterial(args[0] .toUpperCase())).getId(); return new ItemStack(id, 1, Short.parseShort(args[1])); } public void setBorderCloseInRate(double rate) { this.borderClosesIn = rate; } /** * @param Whats * the new border size? */ public void setBorderSize(double newBorder) { border = newBorder; } public void setRoundedBorder(boolean roundedBorder) { this.roundedBorder = roundedBorder; } public void setTimeOfDay(int timeOfDay) { this.timeOfDay = timeOfDay; } /** * @return Should it give players that fancy kit selector */ public boolean useKitSelector() { return kitSelector; } public boolean isInvisSpectators() { return invisSpectators; } }
true
true
public void loadConfig() { hg.saveDefaultConfig(); final TranslationManager cm = HungergamesApi.getTranslationManager(); if (Bukkit.getServer().getAllowEnd() && hg.getConfig().getBoolean("DisableEnd", true)) { YamlConfiguration config = YamlConfiguration.loadConfiguration(new File("bukkit.yml")); config.set("settings.allow-end", false); try { config.save(new File("bukkit.yml")); } catch (IOException e) { e.printStackTrace(); } System.out.println(cm.getLoggerDisabledEnd()); } ReflectionManager rm = HungergamesApi.getReflectionManager(); if (hg.getServer().getAllowNether() && hg.getConfig().getBoolean("DisableNether", true)) { rm.setPropertiesConfig("allow-nether", false); rm.savePropertiesConfig(); System.out.println(cm.getLoggerDisabledNether()); } if (hg.getServer().getSpawnRadius() > 0 && hg.getConfig().getBoolean("ChangeSpawnLimit", true)) { rm.setPropertiesConfig("spawn-protection", 0); rm.savePropertiesConfig(); System.out.println(cm.getLoggerChangedSpawnRadius()); } if ((Integer) rm.getPropertiesConfig("max-build-height", 128) > 128 && hg.getConfig().getBoolean("ChangeHeightLimit", true)) { rm.setPropertiesConfig("max-build-height", 128); rm.savePropertiesConfig(); System.out.println(cm.getLoggerChangedHeightLimit()); } currentVersion = "v" + hg.getDescription().getVersion(); if (hg.getConfig().getBoolean("CheckUpdates")) Bukkit.getScheduler().scheduleAsyncDelayedTask(hg, new Runnable() { public void run() { try { checkUpdate(); } catch (Exception ex) { System.out.print(String.format(cm.getLoggerFailedToCheckUpdate(), ex.getMessage())); } } }); hg.currentTime = -Math.abs(hg.getConfig().getInt("Countdown", 270)); mysqlEnabled = hg.getConfig().getBoolean("UseMySql", false); displayScoreboards = hg.getConfig().getBoolean("Scoreboards", false); displayMessages = hg.getConfig().getBoolean("Messages", true); minPlayers = hg.getConfig().getInt("MinPlayers", 2); fireSpread = hg.getConfig().getBoolean("DisableFireSpread", false); wonBroadcastsDelay = hg.getConfig().getInt("WinnerBroadcastingDelay"); gameShutdownDelay = hg.getConfig().getInt("GameShutdownDelay"); feastSize = hg.getConfig().getInt("FeastSize", 20); invincibility = hg.getConfig().getInt("Invincibility", 120); chestLayers = hg.getConfig().getInt("ChestLayers", 500); timeTillFeast = hg.getConfig().getInt("TimeTillFeast", 500); spectatorChat = !hg.getConfig().getBoolean("SpectatorChat", true); shortenNames = hg.getConfig().getBoolean("ShortenNames"); spectators = hg.getConfig().getBoolean("Spectators", true); kickOnDeath = hg.getConfig().getBoolean("KickOnDeath"); mushroomStew = hg.getConfig().getBoolean("MushroomStew", false); mushroomStewRestores = hg.getConfig().getInt("MushroomStewRestores", 5); kitSelector = hg.getConfig().getBoolean("EnableKitSelector", true); feastTnt = hg.getConfig().getBoolean("FeastTnt", true); feastGround = parseItem(hg.getConfig().getString("FeastGround")); feast = parseItem(hg.getConfig().getString("Feast")); generatePillars = hg.getConfig().getBoolean("Pillars", true); feastInsides = parseItem(hg.getConfig().getString("FeastInsides")); pillarCorner = parseItem(hg.getConfig().getString("PillarCorner")); pillarInsides = parseItem(hg.getConfig().getString("PillarInsides")); forceCords = hg.getConfig().getBoolean("ForceCords", true); x = hg.getConfig().getInt("ForceX", 0); z = hg.getConfig().getInt("ForceZ", 0); kitSelectorIcon = parseItem(hg.getConfig().getString("KitSelectorIcon")); if (kitSelectorIcon == null) kitSelectorIcon = new ItemStack(Material.FEATHER); kitSelectorBack = parseItem(hg.getConfig().getString("KitSelectorForward")); if (kitSelectorBack == null) kitSelectorBack = new ItemStack(Material.SUGAR_CANE_BLOCK); kitSelectorForward = parseItem(hg.getConfig().getString("KitSelectorBack")); if (kitSelectorForward == null) kitSelectorForward = new ItemStack(Material.SUGAR_CANE_BLOCK); spectatorItemBack = parseItem(hg.getConfig().getString("SpectatorInventoryForward")); if (spectatorItemBack == null) spectatorItemBack = new ItemStack(Material.SUGAR_CANE_BLOCK); spectatorItemForwards = parseItem(hg.getConfig().getString("SpectatorInventoryBack")); if (spectatorItemForwards == null) spectatorItemForwards = new ItemStack(Material.SUGAR_CANE_BLOCK); kitSelectorDynamicSize = hg.getConfig().getBoolean("KitSelectorDynamicSize"); kitSelectorInventorySize = hg.getConfig().getInt("KitSelectorInventorySize"); mobSpawnChance = hg.getConfig().getInt("MobSpawnChance"); if (hg.getConfig().contains("CommandsToRunBeforeShutdown")) commandsToRunBeforeShutdown = hg.getConfig().getStringList("CommandsToRunBeforeShutdown"); else commandsToRunBeforeShutdown = new ArrayList<String>(); disableMetrics = hg.getConfig().getBoolean("DisableMetrics"); flyPreGame = hg.getConfig().getBoolean("FlyPregame"); if (hg.getConfig().getBoolean("ChangeAlivePrefix")) alivePrefix = hg.getConfig().getString("AlivePrefix"); if (hg.getConfig().getBoolean("ChangeSpectatingPrefix")) spectatingPrefix = hg.getConfig().getString("SpectatingPrefix"); invisSpectators = hg.getConfig().getBoolean("InvisibleSpectators"); // Create the times where it broadcasts and advertises the feast feastBroadcastTimes.clear(); for (int i = 1; i < 6; i++) feastBroadcastTimes.add(i); feastBroadcastTimes.add(30); feastBroadcastTimes.add(15); feastBroadcastTimes.add(10); invincibilityBroadcastTimes.clear(); // Create the times where it advertises invincibility for (int i = 1; i <= 5; i++) invincibilityBroadcastTimes.add(i); invincibilityBroadcastTimes.add(30); invincibilityBroadcastTimes.add(15); invincibilityBroadcastTimes.add(10); // Create the times where it advertises when the game starts gameStartingBroadcastTimes.clear(); for (int i = 1; i <= 5; i++) gameStartingBroadcastTimes.add(-i); gameStartingBroadcastTimes.add(-30); gameStartingBroadcastTimes.add(-15); gameStartingBroadcastTimes.add(-10); }
public void loadConfig() { hg.saveDefaultConfig(); final TranslationManager cm = HungergamesApi.getTranslationManager(); if (Bukkit.getServer().getAllowEnd() && hg.getConfig().getBoolean("DisableEnd", true)) { YamlConfiguration config = YamlConfiguration.loadConfiguration(new File("bukkit.yml")); config.set("settings.allow-end", false); try { config.save(new File("bukkit.yml")); } catch (IOException e) { e.printStackTrace(); } System.out.println(cm.getLoggerDisabledEnd()); } ReflectionManager rm = HungergamesApi.getReflectionManager(); if (hg.getServer().getAllowNether() && hg.getConfig().getBoolean("DisableNether", true)) { rm.setPropertiesConfig("allow-nether", false); rm.savePropertiesConfig(); System.out.println(cm.getLoggerDisabledNether()); } if (hg.getServer().getSpawnRadius() > 0 && hg.getConfig().getBoolean("ChangeSpawnLimit", true)) { rm.setPropertiesConfig("spawn-protection", 0); rm.savePropertiesConfig(); System.out.println(cm.getLoggerChangedSpawnRadius()); } if ((Integer) rm.getPropertiesConfig("max-build-height", 128) > 128 && hg.getConfig().getBoolean("ChangeHeightLimit", true)) { rm.setPropertiesConfig("max-build-height", 128); rm.savePropertiesConfig(); System.out.println(cm.getLoggerChangedHeightLimit()); } currentVersion = "v" + hg.getDescription().getVersion(); if (hg.getConfig().getBoolean("CheckUpdates")) Bukkit.getScheduler().scheduleAsyncDelayedTask(hg, new Runnable() { public void run() { try { checkUpdate(); } catch (Exception ex) { System.out.print(String.format(cm.getLoggerFailedToCheckUpdate(), ex.getMessage())); } } }); hg.currentTime = -Math.abs(hg.getConfig().getInt("Countdown", 270)); mysqlEnabled = hg.getConfig().getBoolean("UseMySql", false); displayScoreboards = hg.getConfig().getBoolean("Scoreboards", false); displayMessages = hg.getConfig().getBoolean("Messages", true); minPlayers = hg.getConfig().getInt("MinPlayers", 2); fireSpread = hg.getConfig().getBoolean("DisableFireSpread", false); wonBroadcastsDelay = hg.getConfig().getInt("WinnerBroadcastingDelay"); gameShutdownDelay = hg.getConfig().getInt("GameShutdownDelay"); feastSize = hg.getConfig().getInt("FeastSize", 20); invincibility = hg.getConfig().getInt("Invincibility", 120); chestLayers = hg.getConfig().getInt("ChestLayers", 500); timeTillFeast = hg.getConfig().getInt("TimeTillFeast", 500); spectatorChat = !hg.getConfig().getBoolean("SpectatorChat", true); shortenNames = hg.getConfig().getBoolean("ShortenNames"); spectators = hg.getConfig().getBoolean("Spectators", true); kickOnDeath = hg.getConfig().getBoolean("KickOnDeath"); mushroomStew = hg.getConfig().getBoolean("MushroomStew", false); mushroomStewRestores = hg.getConfig().getInt("MushroomStewRestores", 5); kitSelector = hg.getConfig().getBoolean("EnableKitSelector", true); feastTnt = hg.getConfig().getBoolean("FeastTnt", true); feastGround = parseItem(hg.getConfig().getString("FeastGround")); feast = parseItem(hg.getConfig().getString("Feast")); generatePillars = hg.getConfig().getBoolean("Pillars", true); feastInsides = parseItem(hg.getConfig().getString("FeastInsides")); pillarCorner = parseItem(hg.getConfig().getString("PillarCorner")); pillarInsides = parseItem(hg.getConfig().getString("PillarInsides")); forceCords = hg.getConfig().getBoolean("ForceCords", true); x = hg.getConfig().getInt("ForceX", 0); z = hg.getConfig().getInt("ForceZ", 0); kitSelectorIcon = parseItem(hg.getConfig().getString("KitSelectorIcon")); if (kitSelectorIcon == null) kitSelectorIcon = new ItemStack(Material.FEATHER); kitSelectorBack = parseItem(hg.getConfig().getString("KitSelectorForward")); if (kitSelectorBack == null) kitSelectorBack = new ItemStack(Material.SUGAR_CANE_BLOCK); kitSelectorForward = parseItem(hg.getConfig().getString("KitSelectorBack")); if (kitSelectorForward == null) kitSelectorForward = new ItemStack(Material.SUGAR_CANE_BLOCK); spectatorItemBack = parseItem(hg.getConfig().getString("SpectatorInventoryForward")); if (spectatorItemBack == null) spectatorItemBack = new ItemStack(Material.SUGAR_CANE_BLOCK); spectatorItemForwards = parseItem(hg.getConfig().getString("SpectatorInventoryBack")); if (spectatorItemForwards == null) spectatorItemForwards = new ItemStack(Material.SUGAR_CANE_BLOCK); kitSelectorDynamicSize = hg.getConfig().getBoolean("KitSelectorDynamicSize"); kitSelectorInventorySize = hg.getConfig().getInt("KitSelectorInventorySize"); mobSpawnChance = hg.getConfig().getInt("MobSpawnChance"); if (hg.getConfig().contains("CommandsToRunBeforeShutdown")) commandsToRunBeforeShutdown = hg.getConfig().getStringList("CommandsToRunBeforeShutdown"); else commandsToRunBeforeShutdown = new ArrayList<String>(); disableMetrics = hg.getConfig().getBoolean("DisableMetrics"); flyPreGame = hg.getConfig().getBoolean("FlyPregame"); if (hg.getConfig().getBoolean("ChangeAlivePrefix")) alivePrefix = hg.getConfig().getString("AlivePrefix"); if (hg.getConfig().getBoolean("ChangeSpectatingPrefix")) spectatingPrefix = hg.getConfig().getString("SpectatingPrefix"); invisSpectators = !hg.getConfig().getBoolean("InvisibleSpectators"); // Create the times where it broadcasts and advertises the feast feastBroadcastTimes.clear(); for (int i = 1; i < 6; i++) feastBroadcastTimes.add(i); feastBroadcastTimes.add(30); feastBroadcastTimes.add(15); feastBroadcastTimes.add(10); invincibilityBroadcastTimes.clear(); // Create the times where it advertises invincibility for (int i = 1; i <= 5; i++) invincibilityBroadcastTimes.add(i); invincibilityBroadcastTimes.add(30); invincibilityBroadcastTimes.add(15); invincibilityBroadcastTimes.add(10); // Create the times where it advertises when the game starts gameStartingBroadcastTimes.clear(); for (int i = 1; i <= 5; i++) gameStartingBroadcastTimes.add(-i); gameStartingBroadcastTimes.add(-30); gameStartingBroadcastTimes.add(-15); gameStartingBroadcastTimes.add(-10); }
diff --git a/src/examples/org/apache/hama/examples/RandomMatrix.java b/src/examples/org/apache/hama/examples/RandomMatrix.java index 1abff30..06e492c 100644 --- a/src/examples/org/apache/hama/examples/RandomMatrix.java +++ b/src/examples/org/apache/hama/examples/RandomMatrix.java @@ -1,43 +1,43 @@ /** * Copyright 2007 The Apache Software Foundation * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hama.examples; import java.io.IOException; import org.apache.hama.DenseMatrix; public class RandomMatrix extends AbstractExample { public static void main(String[] args) throws IOException { if (args.length < 3) { System.out - .println("add [-m maps] [-r reduces] <rows> <columns> <matrix_name>"); + .println("random [-m maps] [-r reduces] <rows> <columns> <matrix_name>"); System.exit(-1); } else { parseArgs(args); } int row = Integer.parseInt(ARGS.get(0)); int column = Integer.parseInt(ARGS.get(1)); DenseMatrix a = DenseMatrix.random_mapred(conf, row, column); a.save(ARGS.get(2)); } }
true
true
public static void main(String[] args) throws IOException { if (args.length < 3) { System.out .println("add [-m maps] [-r reduces] <rows> <columns> <matrix_name>"); System.exit(-1); } else { parseArgs(args); } int row = Integer.parseInt(ARGS.get(0)); int column = Integer.parseInt(ARGS.get(1)); DenseMatrix a = DenseMatrix.random_mapred(conf, row, column); a.save(ARGS.get(2)); }
public static void main(String[] args) throws IOException { if (args.length < 3) { System.out .println("random [-m maps] [-r reduces] <rows> <columns> <matrix_name>"); System.exit(-1); } else { parseArgs(args); } int row = Integer.parseInt(ARGS.get(0)); int column = Integer.parseInt(ARGS.get(1)); DenseMatrix a = DenseMatrix.random_mapred(conf, row, column); a.save(ARGS.get(2)); }
diff --git a/LogicMail/src/org/logicprobe/LogicMail/mail/NetworkMailStore.java b/LogicMail/src/org/logicprobe/LogicMail/mail/NetworkMailStore.java index 288d28e..505523f 100644 --- a/LogicMail/src/org/logicprobe/LogicMail/mail/NetworkMailStore.java +++ b/LogicMail/src/org/logicprobe/LogicMail/mail/NetworkMailStore.java @@ -1,276 +1,273 @@ /*- * Copyright (c) 2008, Derek Konigsberg * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the project nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.logicprobe.LogicMail.mail; import net.rim.device.api.system.UnsupportedOperationException; import org.logicprobe.LogicMail.conf.AccountConfig; import org.logicprobe.LogicMail.message.MessageFlags; import org.logicprobe.LogicMail.message.MimeMessagePart; public class NetworkMailStore extends AbstractMailStore { private IncomingMailClient client; private IncomingMailConnectionHandler connectionHandler; private AccountConfig accountConfig; public NetworkMailStore(AccountConfig accountConfig) { super(); this.client = MailClientFactory.createMailClient(accountConfig); this.accountConfig = accountConfig; this.connectionHandler = new IncomingMailConnectionHandler(this, client); this.connectionHandler.start(); } /** * Gets the account configuration associated with this network mail store. * * @return Account configuration. */ public AccountConfig getAccountConfig() { return this.accountConfig; } public void shutdown(boolean wait) { connectionHandler.shutdown(wait); } /** * Restarts the mail connection handler thread. */ public void restart() { if(!connectionHandler.isRunning()) { connectionHandler.start(); } } public boolean isLocal() { return false; } public boolean hasFolders() { return client.hasFolders(); } public boolean hasMessageParts() { return client.hasMessageParts(); } public boolean hasFlags() { return client.hasFlags(); } public boolean hasAppend() { return client.hasAppend(); } public boolean hasCopy() { return client.hasCopy(); } public boolean hasUndelete() { return client.hasUndelete(); } public boolean hasExpunge() { return client.hasExpunge(); } /** * Returns whether the mail store supports retrieval of a full folder * message index-to-UID map. * * @return True if index-to-UID map retrieval is supported, false otherwise * @see #requestFolderMessageIndexMap(FolderTreeItem, MailStoreRequestCallback) */ public boolean hasFolderMessageIndexMap() { return client.hasFolderMessageIndexMap(); } /** * Returns whether the mail store has a locked folder view while connected. * If this method returns true, then an explicit refresh during an existing * connection will not return new data. * @return True if folder contents are locked while connected, false otherwise. */ public boolean hasLockedFolders() { return client.hasLockedFolders(); } public boolean isConnected() { return client.isConnected(); } /** * Gets the inbox folder, if available. */ public FolderTreeItem getInboxFolder() { return client.getInboxFolder(); } /** * Requests that the mail store disconnect from the mail server. * <p> * Unlike the <code>shutdown(boolean)</code> method, this does not cause * the connection handler thread to terminate. As such, any subsequent * request may cause it to reconnect. * </p> */ public void requestDisconnect() { processRequest(new NetworkDisconnectRequest(this, NetworkDisconnectRequest.REQUEST_DISCONNECT)); } /** * Creates a request to instruct the mail client to enable or disable its * idle mode. This request is useful at the beginning and end of a batch * operation, to prevent the mail client from entering and exiting idle * mode between requests. * * @param idleEnabled whether or not the idle mode should be enabled */ public NetworkClientIdleModeRequest createClientIdleModeRequest(boolean idleEnabled) { NetworkClientIdleModeRequest request = new NetworkClientIdleModeRequest(this, idleEnabled); return request; } public FolderTreeRequest createFolderTreeRequest() { NetworkFolderTreeRequest request = new NetworkFolderTreeRequest(this); return request; } public FolderExpungeRequest createFolderExpungeRequest(FolderTreeItem folder) { NetworkFolderExpungeRequest request = new NetworkFolderExpungeRequest(this, folder); return request; } public FolderStatusRequest createFolderStatusRequest(FolderTreeItem[] folders) { NetworkFolderStatusRequest request = new NetworkFolderStatusRequest(this, folders); return request; } public FolderMessagesRequest createFolderMessagesRangeRequest(FolderTreeItem folder, MessageToken firstToken, int increment) { if(firstToken == null || increment <= 0) { throw new IllegalArgumentException(); } NetworkFolderMessagesRequest request = new NetworkFolderMessagesRequest(this, folder, firstToken, increment); return request; } public FolderMessagesRequest createFolderMessagesSetRequest(FolderTreeItem folder, MessageToken[] messageTokens, boolean flagsOnly) { NetworkFolderMessagesRequest request = new NetworkFolderMessagesRequest(this, folder, messageTokens, flagsOnly); return request; } public FolderMessagesRequest createFolderMessagesSetByIndexRequest(FolderTreeItem folder, int[] messageIndices) { NetworkFolderMessagesRequest request = new NetworkFolderMessagesRequest(this, folder, messageIndices); return request; } public FolderMessagesRequest createFolderMessagesRecentRequest(FolderTreeItem folder, boolean flagsOnly) { NetworkFolderMessagesRequest request = new NetworkFolderMessagesRequest(this, folder, flagsOnly); return request; } /** * Requests the message UID-to-index map for a particular folder. * <p> * Successful completion is indicated by a call to * {@link FolderListener#folderMessageIndexMapAvailable(FolderMessageIndexMapEvent)}. * </p> * * @param folder The folder to request a message listing for. */ public NetworkFolderMessageIndexMapRequest requestFolderMessageIndexMap(FolderTreeItem folder) { NetworkFolderMessageIndexMapRequest request = new NetworkFolderMessageIndexMapRequest(this, folder); return request; } public MessageRequest createMessageRequest(MessageToken messageToken, boolean useLimits) { NetworkMessageRequest request = new NetworkMessageRequest(this, messageToken, useLimits); return request; } public MessageRequest createMessagePartsRequest(MessageToken messageToken, MimeMessagePart[] messageParts) { NetworkMessageRequest request = new NetworkMessageRequest(this, messageToken, messageParts); return request; } public MessageFlagChangeRequest createMessageFlagChangeRequest( MessageToken messageToken, MessageFlags messageFlags, boolean addOrRemove) { if(messageFlags.isDeleted()) { if(!addOrRemove && !client.hasUndelete()) { throw new UnsupportedOperationException(); } } else if(!this.hasFlags()) { throw new UnsupportedOperationException(); } - else { - throw new IllegalArgumentException(); - } NetworkMessageFlagChangeRequest request = new NetworkMessageFlagChangeRequest(this, messageToken, messageFlags, addOrRemove); return request; } public MessageAppendRequest createMessageAppendRequest(FolderTreeItem folder, String rawMessage, MessageFlags initialFlags) { if(!this.hasAppend()) { throw new UnsupportedOperationException(); } NetworkMessageAppendRequest request = new NetworkMessageAppendRequest(this, folder, rawMessage, initialFlags); return request; } public MessageCopyRequest createMessageCopyRequest(MessageToken messageToken, FolderTreeItem destinationFolder) { if(!this.hasCopy()) { throw new UnsupportedOperationException(); } NetworkMessageCopyRequest request = new NetworkMessageCopyRequest(this, messageToken, destinationFolder); return request; } public void processRequest(MailStoreRequest request) { if(request instanceof NetworkMailStoreRequest && request instanceof ConnectionHandlerRequest) { connectionHandler.addRequest((ConnectionHandlerRequest)request); } else { throw new IllegalArgumentException(); } } IncomingMailConnectionHandler getConnectionHandler() { return connectionHandler; } }
true
true
public MessageFlagChangeRequest createMessageFlagChangeRequest( MessageToken messageToken, MessageFlags messageFlags, boolean addOrRemove) { if(messageFlags.isDeleted()) { if(!addOrRemove && !client.hasUndelete()) { throw new UnsupportedOperationException(); } } else if(!this.hasFlags()) { throw new UnsupportedOperationException(); } else { throw new IllegalArgumentException(); } NetworkMessageFlagChangeRequest request = new NetworkMessageFlagChangeRequest(this, messageToken, messageFlags, addOrRemove); return request; }
public MessageFlagChangeRequest createMessageFlagChangeRequest( MessageToken messageToken, MessageFlags messageFlags, boolean addOrRemove) { if(messageFlags.isDeleted()) { if(!addOrRemove && !client.hasUndelete()) { throw new UnsupportedOperationException(); } } else if(!this.hasFlags()) { throw new UnsupportedOperationException(); } NetworkMessageFlagChangeRequest request = new NetworkMessageFlagChangeRequest(this, messageToken, messageFlags, addOrRemove); return request; }
diff --git a/lucene/analysis/common/src/java/org/apache/lucene/analysis/miscellaneous/PatternKeywordMarkerFilter.java b/lucene/analysis/common/src/java/org/apache/lucene/analysis/miscellaneous/PatternKeywordMarkerFilter.java index 886f19f2d5..2e055bbdbb 100644 --- a/lucene/analysis/common/src/java/org/apache/lucene/analysis/miscellaneous/PatternKeywordMarkerFilter.java +++ b/lucene/analysis/common/src/java/org/apache/lucene/analysis/miscellaneous/PatternKeywordMarkerFilter.java @@ -1,56 +1,56 @@ package org.apache.lucene.analysis.miscellaneous; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; import org.apache.lucene.analysis.tokenattributes.KeywordAttribute; /** * Marks terms as keywords via the {@link KeywordAttribute}. Each token * that matches the provided pattern is marked as a keyword by setting * {@link KeywordAttribute#setKeyword(boolean)} to <code>true</code>. */ public final class PatternKeywordMarkerFilter extends KeywordMarkerFilter { private final CharTermAttribute termAtt = addAttribute(CharTermAttribute.class); private final Matcher matcher; /** * Create a new {@link PatternKeywordMarkerFilter}, that marks the current * token as a keyword if the tokens term buffer matches the provided * {@link Pattern} via the {@link KeywordAttribute}. * * @param in * TokenStream to filter * @param pattern * the pattern to apply to the incoming term buffer **/ - protected PatternKeywordMarkerFilter(TokenStream in, Pattern pattern) { + public PatternKeywordMarkerFilter(TokenStream in, Pattern pattern) { super(in); this.matcher = pattern.matcher(""); } @Override protected boolean isKeyword() { matcher.reset(termAtt); return matcher.matches(); } }
true
true
protected PatternKeywordMarkerFilter(TokenStream in, Pattern pattern) { super(in); this.matcher = pattern.matcher(""); }
public PatternKeywordMarkerFilter(TokenStream in, Pattern pattern) { super(in); this.matcher = pattern.matcher(""); }
diff --git a/src/me/lucariatias/plugins/kaisocraft/PartyCommand.java b/src/me/lucariatias/plugins/kaisocraft/PartyCommand.java index 9603aac..d0c87bd 100644 --- a/src/me/lucariatias/plugins/kaisocraft/PartyCommand.java +++ b/src/me/lucariatias/plugins/kaisocraft/PartyCommand.java @@ -1,181 +1,183 @@ package me.lucariatias.plugins.kaisocraft; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Entity; import org.bukkit.entity.HumanEntity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; public class PartyCommand implements CommandExecutor { @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (cmd.getName().equalsIgnoreCase("party")) { if (args.length > 0) { sender.sendMessage(ChatColor.YELLOW + "==" + ChatColor.BLUE + "/" + cmd.getName().toLowerCase() + " " + ChatColor.DARK_BLUE + args[0].toLowerCase() + ChatColor.YELLOW + "=="); if (args[0].equalsIgnoreCase("members")) { if (sender.hasPermission("kaisocraft.command.party.members")) { sender.sendMessage(ChatColor.GREEN + "==" + ChatColor.DARK_GREEN + "Your party" + ChatColor.GREEN + "=="); for (Player player : ((Player) sender).getWorld().getPlayers()) { if (KaisoCraft.getPlayerGuild(player.getName()) == KaisoCraft.getPlayerGuild(sender.getName())) { if (player.getLocation().distance(((Player) sender).getLocation()) <= 32) { sender.sendMessage(ChatColor.LIGHT_PURPLE + player.getName() + ChatColor.DARK_PURPLE + " : Lvl" + player.getLevel() + " " + ChatColor.LIGHT_PURPLE + player.getType().toString()); } } } sender.sendMessage(ChatColor.RED + "==" + ChatColor.DARK_RED + "Enemy party" + ChatColor.RED + "=="); for (Entity entity : ((Player) sender).getWorld().getEntities()) { if (entity instanceof LivingEntity) { if (!(entity instanceof Player)) { if (((Player) sender).getLocation().distance(entity.getLocation()) <= 32) { sender.sendMessage(ChatColor.DARK_PURPLE + "Lvl" + KaisoCraft.getEntityLevel(entity) + ChatColor.LIGHT_PURPLE + " " + entity.getType().toString()); } } else { if (KaisoCraft.getPlayerGuild(((Player) entity).getName()) != null) { if (KaisoCraft.getPlayerGuild(sender.getName()) != null) { if (KaisoCraft.getPlayerGuild(((Player) entity).getName()) != KaisoCraft.getPlayerGuild(sender.getName())) { sender.sendMessage(ChatColor.LIGHT_PURPLE + ((Player) entity).getName() + ChatColor.DARK_PURPLE + " : Lvl" + ((Player) entity).getLevel() + " " + ChatColor.LIGHT_PURPLE + ((Player) entity).getType().toString()); } } } else { - sender.sendMessage(ChatColor.LIGHT_PURPLE + ((Player) entity).getName() + ChatColor.DARK_PURPLE + " : Lvl" + ((Player) entity).getLevel() + " " + ChatColor.LIGHT_PURPLE + ((Player) entity).getType().toString()); + if ((Player) entity != (Player) sender) { + sender.sendMessage(ChatColor.LIGHT_PURPLE + ((Player) entity).getName() + ChatColor.DARK_PURPLE + " : Lvl" + ((Player) entity).getLevel() + " " + ChatColor.LIGHT_PURPLE + ((Player) entity).getType().toString()); + } } } } } } else { sender.sendMessage(ChatColor.RED + "You do not have permission!"); sender.sendMessage(ChatColor.GREEN + "Permission node: " + ChatColor.DARK_GREEN + "kaisocraft.command.party.members"); } } if (args[0].equalsIgnoreCase("stats")) { if (sender.hasPermission("kaisocraft.command.party.stats")) { if (args.length >= 2) { if (Bukkit.getServer().getPlayer(args[1]) != null) { Player player = Bukkit.getServer().getPlayer(args[1]); if (KaisoCraft.getPlayerGuild(player.getName()) == KaisoCraft.getPlayerGuild(sender.getName())) { if (((Player) sender).getWorld() == player.getWorld()) { if (((Player) sender).getLocation().distance(player.getLocation()) <= 32) { sender.sendMessage(ChatColor.GREEN + "==" + ChatColor.DARK_GREEN + player.getName() + ChatColor.GREEN + "=="); sender.sendMessage(ChatColor.DARK_AQUA + "Level: " + ChatColor.AQUA + player.getLevel()); sender.sendMessage(ChatColor.DARK_AQUA + "Exp: " + ChatColor.AQUA + KaisoCraft.getExp(player) + "/" + player.getExpToLevel()); sender.sendMessage(ChatColor.DARK_AQUA + "HP: " + ChatColor.AQUA + player.getHealth() + "/" + player.getMaxHealth()); sender.sendMessage(ChatColor.DARK_AQUA + "Attack: " + ChatColor.AQUA + KaisoCraft.getPlayerAttack(player)); sender.sendMessage(ChatColor.DARK_AQUA + "Defence: " + ChatColor.AQUA + KaisoCraft.getPlayerDefence(player)); } else { sender.sendMessage(ChatColor.DARK_RED + player.getName() + ChatColor.RED + " is not currently in your party!"); } } else { sender.sendMessage(ChatColor.DARK_RED + player.getName() + ChatColor.RED + " is not currently in your party!"); } } else { sender.sendMessage(ChatColor.DARK_RED + player.getName() + ChatColor.RED + " is not a member of your guild!"); } } else { sender.sendMessage(ChatColor.RED + "That player is not currently online!"); } } else { Player player = (Player) sender; sender.sendMessage(ChatColor.GREEN + "==" + ChatColor.DARK_GREEN + player.getName() + ChatColor.GREEN + "=="); sender.sendMessage(ChatColor.DARK_AQUA + "Level: " + ChatColor.AQUA + player.getLevel()); sender.sendMessage(ChatColor.DARK_AQUA + "Exp: " + ChatColor.AQUA + KaisoCraft.getExp(player) + "/" + player.getExpToLevel()); sender.sendMessage(ChatColor.DARK_AQUA + "HP: " + ChatColor.AQUA + player.getHealth() + "/" + player.getMaxHealth()); sender.sendMessage(ChatColor.DARK_AQUA + "Attack: " + ChatColor.AQUA + KaisoCraft.getPlayerAttack(player)); sender.sendMessage(ChatColor.DARK_AQUA + "Defence: " + ChatColor.AQUA + KaisoCraft.getPlayerDefence(player)); } } else { sender.sendMessage(ChatColor.RED + "You do not have permission!"); sender.sendMessage(ChatColor.GREEN + "Permission node: " + ChatColor.DARK_GREEN + "kaisocraft.command.party.stats"); } } if (args[0].equalsIgnoreCase("assist")) { if (sender.hasPermission("kaisocraft.command.party.assist")) { if (args.length >= 2) { if (Bukkit.getServer().getPlayer(args[1]) != null) { Player player = Bukkit.getServer().getPlayer(args[1]); if (KaisoCraft.getPlayerGuild(Bukkit.getServer().getPlayer(args[1]).getName()) == KaisoCraft.getPlayerGuild(sender.getName())) { if (((Player) sender).getWorld() == player.getWorld()) { if (((Player) sender).getLocation().distance(player.getLocation()) <= 32) { sender.sendMessage(ChatColor.GREEN + "Assisting " + ChatColor.DARK_GREEN + player.getName() + ChatColor.GREEN + "..."); ((Player) sender).teleport(player.getLocation()); } else { sender.sendMessage(ChatColor.DARK_RED + player.getName() + ChatColor.RED + " is not currently in your party!"); } } else { sender.sendMessage(ChatColor.DARK_RED + player.getName() + ChatColor.RED + " is not currently in your party!"); } } else { sender.sendMessage(ChatColor.DARK_RED + player.getName() + ChatColor.RED + " is not a member of your guild!"); } } else { sender.sendMessage(ChatColor.RED + "That player is not currently online!"); } } else { sender.sendMessage(ChatColor.RED + "Incorrect usage!"); sender.sendMessage(ChatColor.GREEN + "Usage: /party assist [player]"); } } else { sender.sendMessage(ChatColor.RED + "You do not have permission!"); sender.sendMessage(ChatColor.GREEN + "Permission node: " + ChatColor.DARK_GREEN + "kaisocraft.command.party.stats"); } } if (args[0].equalsIgnoreCase("trade")) { if (sender.hasPermission("kaisocraft.command.party.trade")) { if (args.length >= 2) { if (Bukkit.getServer().getPlayer(args[1]) != null) { Player player = Bukkit.getServer().getPlayer(args[1]); if (KaisoCraft.getPlayerGuild(Bukkit.getServer().getPlayer(args[1]).getName()) == KaisoCraft.getPlayerGuild(sender.getName())) { if (((Player) sender).getWorld() == player.getWorld()) { if (((Player) sender).getLocation().distance(player.getLocation()) <= 32) { if (KaisoCraft.trades.get(args[1]) != null) { sender.sendMessage(ChatColor.GREEN + "Opened trade inventory " + ChatColor.DARK_GREEN + args[0]); ((Player) sender).openInventory(KaisoCraft.trades.get(args[1])); if (KaisoCraft.trades.get(args[1]).getViewers().isEmpty()) { sender.sendMessage(ChatColor.RED + "No one is currently trading in this inventory!"); } else { sender.sendMessage(ChatColor.GREEN + "Currently trading with:"); for (HumanEntity entity : KaisoCraft.trades.get(args[1]).getViewers()) { sender.sendMessage(ChatColor.DARK_GREEN + entity.getName()); } } } else { sender.sendMessage(ChatColor.GREEN + "Created trade inventory " + ChatColor.DARK_GREEN + args[1]); KaisoCraft.trades.put(args[0], Bukkit.getServer().createInventory(null, 27, "Trade")); ((Player) sender).openInventory(KaisoCraft.trades.get(args[1])); sender.sendMessage(ChatColor.RED + "No one is currently trading in this inventory!"); } } else { sender.sendMessage(ChatColor.DARK_RED + player.getName() + ChatColor.RED + " is not currently in your party!"); } } else { sender.sendMessage(ChatColor.DARK_RED + player.getName() + ChatColor.RED + " is not currently in your party!"); } } else { sender.sendMessage(ChatColor.DARK_RED + player.getName() + ChatColor.RED + " is not a member of your guild!"); } } else { sender.sendMessage(ChatColor.RED + "That player is not currently online!"); } } else { sender.sendMessage(ChatColor.RED + "Incorrect usage!"); sender.sendMessage(ChatColor.GREEN + "Usage: /party assist [player]"); } } else { sender.sendMessage(ChatColor.RED + "You do not have permission!"); sender.sendMessage(ChatColor.GREEN + "Permission node: " + ChatColor.DARK_GREEN + "kaisocraft.command.party.stats"); } } } return true; } return false; } }
true
true
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (cmd.getName().equalsIgnoreCase("party")) { if (args.length > 0) { sender.sendMessage(ChatColor.YELLOW + "==" + ChatColor.BLUE + "/" + cmd.getName().toLowerCase() + " " + ChatColor.DARK_BLUE + args[0].toLowerCase() + ChatColor.YELLOW + "=="); if (args[0].equalsIgnoreCase("members")) { if (sender.hasPermission("kaisocraft.command.party.members")) { sender.sendMessage(ChatColor.GREEN + "==" + ChatColor.DARK_GREEN + "Your party" + ChatColor.GREEN + "=="); for (Player player : ((Player) sender).getWorld().getPlayers()) { if (KaisoCraft.getPlayerGuild(player.getName()) == KaisoCraft.getPlayerGuild(sender.getName())) { if (player.getLocation().distance(((Player) sender).getLocation()) <= 32) { sender.sendMessage(ChatColor.LIGHT_PURPLE + player.getName() + ChatColor.DARK_PURPLE + " : Lvl" + player.getLevel() + " " + ChatColor.LIGHT_PURPLE + player.getType().toString()); } } } sender.sendMessage(ChatColor.RED + "==" + ChatColor.DARK_RED + "Enemy party" + ChatColor.RED + "=="); for (Entity entity : ((Player) sender).getWorld().getEntities()) { if (entity instanceof LivingEntity) { if (!(entity instanceof Player)) { if (((Player) sender).getLocation().distance(entity.getLocation()) <= 32) { sender.sendMessage(ChatColor.DARK_PURPLE + "Lvl" + KaisoCraft.getEntityLevel(entity) + ChatColor.LIGHT_PURPLE + " " + entity.getType().toString()); } } else { if (KaisoCraft.getPlayerGuild(((Player) entity).getName()) != null) { if (KaisoCraft.getPlayerGuild(sender.getName()) != null) { if (KaisoCraft.getPlayerGuild(((Player) entity).getName()) != KaisoCraft.getPlayerGuild(sender.getName())) { sender.sendMessage(ChatColor.LIGHT_PURPLE + ((Player) entity).getName() + ChatColor.DARK_PURPLE + " : Lvl" + ((Player) entity).getLevel() + " " + ChatColor.LIGHT_PURPLE + ((Player) entity).getType().toString()); } } } else { sender.sendMessage(ChatColor.LIGHT_PURPLE + ((Player) entity).getName() + ChatColor.DARK_PURPLE + " : Lvl" + ((Player) entity).getLevel() + " " + ChatColor.LIGHT_PURPLE + ((Player) entity).getType().toString()); } } } } } else { sender.sendMessage(ChatColor.RED + "You do not have permission!"); sender.sendMessage(ChatColor.GREEN + "Permission node: " + ChatColor.DARK_GREEN + "kaisocraft.command.party.members"); } } if (args[0].equalsIgnoreCase("stats")) { if (sender.hasPermission("kaisocraft.command.party.stats")) { if (args.length >= 2) { if (Bukkit.getServer().getPlayer(args[1]) != null) { Player player = Bukkit.getServer().getPlayer(args[1]); if (KaisoCraft.getPlayerGuild(player.getName()) == KaisoCraft.getPlayerGuild(sender.getName())) { if (((Player) sender).getWorld() == player.getWorld()) { if (((Player) sender).getLocation().distance(player.getLocation()) <= 32) { sender.sendMessage(ChatColor.GREEN + "==" + ChatColor.DARK_GREEN + player.getName() + ChatColor.GREEN + "=="); sender.sendMessage(ChatColor.DARK_AQUA + "Level: " + ChatColor.AQUA + player.getLevel()); sender.sendMessage(ChatColor.DARK_AQUA + "Exp: " + ChatColor.AQUA + KaisoCraft.getExp(player) + "/" + player.getExpToLevel()); sender.sendMessage(ChatColor.DARK_AQUA + "HP: " + ChatColor.AQUA + player.getHealth() + "/" + player.getMaxHealth()); sender.sendMessage(ChatColor.DARK_AQUA + "Attack: " + ChatColor.AQUA + KaisoCraft.getPlayerAttack(player)); sender.sendMessage(ChatColor.DARK_AQUA + "Defence: " + ChatColor.AQUA + KaisoCraft.getPlayerDefence(player)); } else { sender.sendMessage(ChatColor.DARK_RED + player.getName() + ChatColor.RED + " is not currently in your party!"); } } else { sender.sendMessage(ChatColor.DARK_RED + player.getName() + ChatColor.RED + " is not currently in your party!"); } } else { sender.sendMessage(ChatColor.DARK_RED + player.getName() + ChatColor.RED + " is not a member of your guild!"); } } else { sender.sendMessage(ChatColor.RED + "That player is not currently online!"); } } else { Player player = (Player) sender; sender.sendMessage(ChatColor.GREEN + "==" + ChatColor.DARK_GREEN + player.getName() + ChatColor.GREEN + "=="); sender.sendMessage(ChatColor.DARK_AQUA + "Level: " + ChatColor.AQUA + player.getLevel()); sender.sendMessage(ChatColor.DARK_AQUA + "Exp: " + ChatColor.AQUA + KaisoCraft.getExp(player) + "/" + player.getExpToLevel()); sender.sendMessage(ChatColor.DARK_AQUA + "HP: " + ChatColor.AQUA + player.getHealth() + "/" + player.getMaxHealth()); sender.sendMessage(ChatColor.DARK_AQUA + "Attack: " + ChatColor.AQUA + KaisoCraft.getPlayerAttack(player)); sender.sendMessage(ChatColor.DARK_AQUA + "Defence: " + ChatColor.AQUA + KaisoCraft.getPlayerDefence(player)); } } else { sender.sendMessage(ChatColor.RED + "You do not have permission!"); sender.sendMessage(ChatColor.GREEN + "Permission node: " + ChatColor.DARK_GREEN + "kaisocraft.command.party.stats"); } } if (args[0].equalsIgnoreCase("assist")) { if (sender.hasPermission("kaisocraft.command.party.assist")) { if (args.length >= 2) { if (Bukkit.getServer().getPlayer(args[1]) != null) { Player player = Bukkit.getServer().getPlayer(args[1]); if (KaisoCraft.getPlayerGuild(Bukkit.getServer().getPlayer(args[1]).getName()) == KaisoCraft.getPlayerGuild(sender.getName())) { if (((Player) sender).getWorld() == player.getWorld()) { if (((Player) sender).getLocation().distance(player.getLocation()) <= 32) { sender.sendMessage(ChatColor.GREEN + "Assisting " + ChatColor.DARK_GREEN + player.getName() + ChatColor.GREEN + "..."); ((Player) sender).teleport(player.getLocation()); } else { sender.sendMessage(ChatColor.DARK_RED + player.getName() + ChatColor.RED + " is not currently in your party!"); } } else { sender.sendMessage(ChatColor.DARK_RED + player.getName() + ChatColor.RED + " is not currently in your party!"); } } else { sender.sendMessage(ChatColor.DARK_RED + player.getName() + ChatColor.RED + " is not a member of your guild!"); } } else { sender.sendMessage(ChatColor.RED + "That player is not currently online!"); } } else { sender.sendMessage(ChatColor.RED + "Incorrect usage!"); sender.sendMessage(ChatColor.GREEN + "Usage: /party assist [player]"); } } else { sender.sendMessage(ChatColor.RED + "You do not have permission!"); sender.sendMessage(ChatColor.GREEN + "Permission node: " + ChatColor.DARK_GREEN + "kaisocraft.command.party.stats"); } } if (args[0].equalsIgnoreCase("trade")) { if (sender.hasPermission("kaisocraft.command.party.trade")) { if (args.length >= 2) { if (Bukkit.getServer().getPlayer(args[1]) != null) { Player player = Bukkit.getServer().getPlayer(args[1]); if (KaisoCraft.getPlayerGuild(Bukkit.getServer().getPlayer(args[1]).getName()) == KaisoCraft.getPlayerGuild(sender.getName())) { if (((Player) sender).getWorld() == player.getWorld()) { if (((Player) sender).getLocation().distance(player.getLocation()) <= 32) { if (KaisoCraft.trades.get(args[1]) != null) { sender.sendMessage(ChatColor.GREEN + "Opened trade inventory " + ChatColor.DARK_GREEN + args[0]); ((Player) sender).openInventory(KaisoCraft.trades.get(args[1])); if (KaisoCraft.trades.get(args[1]).getViewers().isEmpty()) { sender.sendMessage(ChatColor.RED + "No one is currently trading in this inventory!"); } else { sender.sendMessage(ChatColor.GREEN + "Currently trading with:"); for (HumanEntity entity : KaisoCraft.trades.get(args[1]).getViewers()) { sender.sendMessage(ChatColor.DARK_GREEN + entity.getName()); } } } else { sender.sendMessage(ChatColor.GREEN + "Created trade inventory " + ChatColor.DARK_GREEN + args[1]); KaisoCraft.trades.put(args[0], Bukkit.getServer().createInventory(null, 27, "Trade")); ((Player) sender).openInventory(KaisoCraft.trades.get(args[1])); sender.sendMessage(ChatColor.RED + "No one is currently trading in this inventory!"); } } else { sender.sendMessage(ChatColor.DARK_RED + player.getName() + ChatColor.RED + " is not currently in your party!"); } } else { sender.sendMessage(ChatColor.DARK_RED + player.getName() + ChatColor.RED + " is not currently in your party!"); } } else { sender.sendMessage(ChatColor.DARK_RED + player.getName() + ChatColor.RED + " is not a member of your guild!"); } } else { sender.sendMessage(ChatColor.RED + "That player is not currently online!"); } } else { sender.sendMessage(ChatColor.RED + "Incorrect usage!"); sender.sendMessage(ChatColor.GREEN + "Usage: /party assist [player]"); } } else { sender.sendMessage(ChatColor.RED + "You do not have permission!"); sender.sendMessage(ChatColor.GREEN + "Permission node: " + ChatColor.DARK_GREEN + "kaisocraft.command.party.stats"); } } } return true; } return false; }
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (cmd.getName().equalsIgnoreCase("party")) { if (args.length > 0) { sender.sendMessage(ChatColor.YELLOW + "==" + ChatColor.BLUE + "/" + cmd.getName().toLowerCase() + " " + ChatColor.DARK_BLUE + args[0].toLowerCase() + ChatColor.YELLOW + "=="); if (args[0].equalsIgnoreCase("members")) { if (sender.hasPermission("kaisocraft.command.party.members")) { sender.sendMessage(ChatColor.GREEN + "==" + ChatColor.DARK_GREEN + "Your party" + ChatColor.GREEN + "=="); for (Player player : ((Player) sender).getWorld().getPlayers()) { if (KaisoCraft.getPlayerGuild(player.getName()) == KaisoCraft.getPlayerGuild(sender.getName())) { if (player.getLocation().distance(((Player) sender).getLocation()) <= 32) { sender.sendMessage(ChatColor.LIGHT_PURPLE + player.getName() + ChatColor.DARK_PURPLE + " : Lvl" + player.getLevel() + " " + ChatColor.LIGHT_PURPLE + player.getType().toString()); } } } sender.sendMessage(ChatColor.RED + "==" + ChatColor.DARK_RED + "Enemy party" + ChatColor.RED + "=="); for (Entity entity : ((Player) sender).getWorld().getEntities()) { if (entity instanceof LivingEntity) { if (!(entity instanceof Player)) { if (((Player) sender).getLocation().distance(entity.getLocation()) <= 32) { sender.sendMessage(ChatColor.DARK_PURPLE + "Lvl" + KaisoCraft.getEntityLevel(entity) + ChatColor.LIGHT_PURPLE + " " + entity.getType().toString()); } } else { if (KaisoCraft.getPlayerGuild(((Player) entity).getName()) != null) { if (KaisoCraft.getPlayerGuild(sender.getName()) != null) { if (KaisoCraft.getPlayerGuild(((Player) entity).getName()) != KaisoCraft.getPlayerGuild(sender.getName())) { sender.sendMessage(ChatColor.LIGHT_PURPLE + ((Player) entity).getName() + ChatColor.DARK_PURPLE + " : Lvl" + ((Player) entity).getLevel() + " " + ChatColor.LIGHT_PURPLE + ((Player) entity).getType().toString()); } } } else { if ((Player) entity != (Player) sender) { sender.sendMessage(ChatColor.LIGHT_PURPLE + ((Player) entity).getName() + ChatColor.DARK_PURPLE + " : Lvl" + ((Player) entity).getLevel() + " " + ChatColor.LIGHT_PURPLE + ((Player) entity).getType().toString()); } } } } } } else { sender.sendMessage(ChatColor.RED + "You do not have permission!"); sender.sendMessage(ChatColor.GREEN + "Permission node: " + ChatColor.DARK_GREEN + "kaisocraft.command.party.members"); } } if (args[0].equalsIgnoreCase("stats")) { if (sender.hasPermission("kaisocraft.command.party.stats")) { if (args.length >= 2) { if (Bukkit.getServer().getPlayer(args[1]) != null) { Player player = Bukkit.getServer().getPlayer(args[1]); if (KaisoCraft.getPlayerGuild(player.getName()) == KaisoCraft.getPlayerGuild(sender.getName())) { if (((Player) sender).getWorld() == player.getWorld()) { if (((Player) sender).getLocation().distance(player.getLocation()) <= 32) { sender.sendMessage(ChatColor.GREEN + "==" + ChatColor.DARK_GREEN + player.getName() + ChatColor.GREEN + "=="); sender.sendMessage(ChatColor.DARK_AQUA + "Level: " + ChatColor.AQUA + player.getLevel()); sender.sendMessage(ChatColor.DARK_AQUA + "Exp: " + ChatColor.AQUA + KaisoCraft.getExp(player) + "/" + player.getExpToLevel()); sender.sendMessage(ChatColor.DARK_AQUA + "HP: " + ChatColor.AQUA + player.getHealth() + "/" + player.getMaxHealth()); sender.sendMessage(ChatColor.DARK_AQUA + "Attack: " + ChatColor.AQUA + KaisoCraft.getPlayerAttack(player)); sender.sendMessage(ChatColor.DARK_AQUA + "Defence: " + ChatColor.AQUA + KaisoCraft.getPlayerDefence(player)); } else { sender.sendMessage(ChatColor.DARK_RED + player.getName() + ChatColor.RED + " is not currently in your party!"); } } else { sender.sendMessage(ChatColor.DARK_RED + player.getName() + ChatColor.RED + " is not currently in your party!"); } } else { sender.sendMessage(ChatColor.DARK_RED + player.getName() + ChatColor.RED + " is not a member of your guild!"); } } else { sender.sendMessage(ChatColor.RED + "That player is not currently online!"); } } else { Player player = (Player) sender; sender.sendMessage(ChatColor.GREEN + "==" + ChatColor.DARK_GREEN + player.getName() + ChatColor.GREEN + "=="); sender.sendMessage(ChatColor.DARK_AQUA + "Level: " + ChatColor.AQUA + player.getLevel()); sender.sendMessage(ChatColor.DARK_AQUA + "Exp: " + ChatColor.AQUA + KaisoCraft.getExp(player) + "/" + player.getExpToLevel()); sender.sendMessage(ChatColor.DARK_AQUA + "HP: " + ChatColor.AQUA + player.getHealth() + "/" + player.getMaxHealth()); sender.sendMessage(ChatColor.DARK_AQUA + "Attack: " + ChatColor.AQUA + KaisoCraft.getPlayerAttack(player)); sender.sendMessage(ChatColor.DARK_AQUA + "Defence: " + ChatColor.AQUA + KaisoCraft.getPlayerDefence(player)); } } else { sender.sendMessage(ChatColor.RED + "You do not have permission!"); sender.sendMessage(ChatColor.GREEN + "Permission node: " + ChatColor.DARK_GREEN + "kaisocraft.command.party.stats"); } } if (args[0].equalsIgnoreCase("assist")) { if (sender.hasPermission("kaisocraft.command.party.assist")) { if (args.length >= 2) { if (Bukkit.getServer().getPlayer(args[1]) != null) { Player player = Bukkit.getServer().getPlayer(args[1]); if (KaisoCraft.getPlayerGuild(Bukkit.getServer().getPlayer(args[1]).getName()) == KaisoCraft.getPlayerGuild(sender.getName())) { if (((Player) sender).getWorld() == player.getWorld()) { if (((Player) sender).getLocation().distance(player.getLocation()) <= 32) { sender.sendMessage(ChatColor.GREEN + "Assisting " + ChatColor.DARK_GREEN + player.getName() + ChatColor.GREEN + "..."); ((Player) sender).teleport(player.getLocation()); } else { sender.sendMessage(ChatColor.DARK_RED + player.getName() + ChatColor.RED + " is not currently in your party!"); } } else { sender.sendMessage(ChatColor.DARK_RED + player.getName() + ChatColor.RED + " is not currently in your party!"); } } else { sender.sendMessage(ChatColor.DARK_RED + player.getName() + ChatColor.RED + " is not a member of your guild!"); } } else { sender.sendMessage(ChatColor.RED + "That player is not currently online!"); } } else { sender.sendMessage(ChatColor.RED + "Incorrect usage!"); sender.sendMessage(ChatColor.GREEN + "Usage: /party assist [player]"); } } else { sender.sendMessage(ChatColor.RED + "You do not have permission!"); sender.sendMessage(ChatColor.GREEN + "Permission node: " + ChatColor.DARK_GREEN + "kaisocraft.command.party.stats"); } } if (args[0].equalsIgnoreCase("trade")) { if (sender.hasPermission("kaisocraft.command.party.trade")) { if (args.length >= 2) { if (Bukkit.getServer().getPlayer(args[1]) != null) { Player player = Bukkit.getServer().getPlayer(args[1]); if (KaisoCraft.getPlayerGuild(Bukkit.getServer().getPlayer(args[1]).getName()) == KaisoCraft.getPlayerGuild(sender.getName())) { if (((Player) sender).getWorld() == player.getWorld()) { if (((Player) sender).getLocation().distance(player.getLocation()) <= 32) { if (KaisoCraft.trades.get(args[1]) != null) { sender.sendMessage(ChatColor.GREEN + "Opened trade inventory " + ChatColor.DARK_GREEN + args[0]); ((Player) sender).openInventory(KaisoCraft.trades.get(args[1])); if (KaisoCraft.trades.get(args[1]).getViewers().isEmpty()) { sender.sendMessage(ChatColor.RED + "No one is currently trading in this inventory!"); } else { sender.sendMessage(ChatColor.GREEN + "Currently trading with:"); for (HumanEntity entity : KaisoCraft.trades.get(args[1]).getViewers()) { sender.sendMessage(ChatColor.DARK_GREEN + entity.getName()); } } } else { sender.sendMessage(ChatColor.GREEN + "Created trade inventory " + ChatColor.DARK_GREEN + args[1]); KaisoCraft.trades.put(args[0], Bukkit.getServer().createInventory(null, 27, "Trade")); ((Player) sender).openInventory(KaisoCraft.trades.get(args[1])); sender.sendMessage(ChatColor.RED + "No one is currently trading in this inventory!"); } } else { sender.sendMessage(ChatColor.DARK_RED + player.getName() + ChatColor.RED + " is not currently in your party!"); } } else { sender.sendMessage(ChatColor.DARK_RED + player.getName() + ChatColor.RED + " is not currently in your party!"); } } else { sender.sendMessage(ChatColor.DARK_RED + player.getName() + ChatColor.RED + " is not a member of your guild!"); } } else { sender.sendMessage(ChatColor.RED + "That player is not currently online!"); } } else { sender.sendMessage(ChatColor.RED + "Incorrect usage!"); sender.sendMessage(ChatColor.GREEN + "Usage: /party assist [player]"); } } else { sender.sendMessage(ChatColor.RED + "You do not have permission!"); sender.sendMessage(ChatColor.GREEN + "Permission node: " + ChatColor.DARK_GREEN + "kaisocraft.command.party.stats"); } } } return true; } return false; }
diff --git a/rt/libcore/luni/src/main/java/java/net/PlainSocketImpl.java b/rt/libcore/luni/src/main/java/java/net/PlainSocketImpl.java index 68ba67e42..e462497d6 100644 --- a/rt/libcore/luni/src/main/java/java/net/PlainSocketImpl.java +++ b/rt/libcore/luni/src/main/java/java/net/PlainSocketImpl.java @@ -1,552 +1,554 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package java.net; import dalvik.system.CloseGuard; import java.io.FileDescriptor; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ConnectException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.SocketAddress; import java.net.SocketException; import java.net.SocketImpl; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.nio.ByteOrder; import java.util.Arrays; import libcore.io.ErrnoException; import libcore.io.IoBridge; import libcore.io.Libcore; import libcore.io.Memory; import libcore.io.Streams; import libcore.io.StructPollfd; import static libcore.io.OsConstants.*; /** * @hide used in java.nio. */ public class PlainSocketImpl extends SocketImpl { // For SOCKS support. A SOCKS bind() uses the last // host connected to in its request. private static InetAddress lastConnectedAddress; private static int lastConnectedPort; private boolean streaming = true; private boolean shutdownInput; private Proxy proxy; private final CloseGuard guard = CloseGuard.get(); public PlainSocketImpl(FileDescriptor fd) { this.fd = fd; if (fd.valid()) { guard.open("close"); } } public PlainSocketImpl(Proxy proxy) { this(new FileDescriptor()); this.proxy = proxy; } public PlainSocketImpl() { this(new FileDescriptor()); } public PlainSocketImpl(FileDescriptor fd, int localport, InetAddress addr, int port) { this.fd = fd; this.localport = localport; this.address = addr; this.port = port; if (fd.valid()) { guard.open("close"); } } @Override protected void accept(SocketImpl newImpl) throws IOException { if (usingSocks()) { ((PlainSocketImpl) newImpl).socksBind(); ((PlainSocketImpl) newImpl).socksAccept(); return; } try { // RovmVM note: accept() on Darwin does not honor the SO_RCVTIMEO // set using setSoTimeout(). As a work around we do poll() if a // timeout has been set followed by an accept(). int timeout = (Integer) getOption(SO_RCVTIMEO); if (timeout > 0) { StructPollfd pfd = new StructPollfd(); pfd.fd = fd; pfd.events = (short) (POLLIN | POLLERR); StructPollfd[] pfds = new StructPollfd[] {pfd}; + long start = System.currentTimeMillis(); + long deadline = start + timeout; while (true) { - long start = System.currentTimeMillis(); try { if (timeout <= 0 || Libcore.os.poll(pfds, timeout) == 0) { throw new SocketTimeoutException("accept() timed out"); } + break; } catch (ErrnoException e) { if (e.errno == EINTR) { - long duration = System.currentTimeMillis() - start; - timeout -= duration; + long now = System.currentTimeMillis(); + timeout = (int) (deadline - now); } else { throw e; } } } } InetSocketAddress peerAddress = new InetSocketAddress(); FileDescriptor clientFd = Libcore.os.accept(fd, peerAddress); // TODO: we can't just set newImpl.fd to clientFd because a nio SocketChannel may // be sharing the FileDescriptor. http://b//4452981. newImpl.fd.setInt$(clientFd.getInt$()); newImpl.address = peerAddress.getAddress(); newImpl.port = peerAddress.getPort(); } catch (ErrnoException errnoException) { if (errnoException.errno == EAGAIN || errnoException.errno == EWOULDBLOCK) { throw new SocketTimeoutException(errnoException); } throw errnoException.rethrowAsSocketException(); } // Reset the client's inherited read timeout to the Java-specified default of 0. newImpl.setOption(SocketOptions.SO_TIMEOUT, Integer.valueOf(0)); newImpl.localport = IoBridge.getSocketLocalPort(newImpl.fd); } private boolean usingSocks() { return proxy != null && proxy.type() == Proxy.Type.SOCKS; } public void initLocalPort(int localPort) { this.localport = localPort; } public void initRemoteAddressAndPort(InetAddress remoteAddress, int remotePort) { this.address = remoteAddress; this.port = remotePort; } private void checkNotClosed() throws IOException { if (!fd.valid()) { throw new SocketException("Socket is closed"); } } @Override protected synchronized int available() throws IOException { checkNotClosed(); // we need to check if the input has been shutdown. If so // we should return that there is no data to be read if (shutdownInput) { return 0; } return IoBridge.available(fd); } @Override protected void bind(InetAddress address, int port) throws IOException { IoBridge.bind(fd, address, port); this.address = address; if (port != 0) { this.localport = port; } else { this.localport = IoBridge.getSocketLocalPort(fd); } } @Override protected synchronized void close() throws IOException { guard.close(); IoBridge.closeSocket(fd); } @Override protected void connect(String aHost, int aPort) throws IOException { connect(InetAddress.getByName(aHost), aPort); } @Override protected void connect(InetAddress anAddr, int aPort) throws IOException { connect(anAddr, aPort, 0); } /** * Connects this socket to the specified remote host address/port. * * @param anAddr * the remote host address to connect to * @param aPort * the remote port to connect to * @param timeout * a timeout where supported. 0 means no timeout * @throws IOException * if an error occurs while connecting */ private void connect(InetAddress anAddr, int aPort, int timeout) throws IOException { InetAddress normalAddr = anAddr.isAnyLocalAddress() ? InetAddress.getLocalHost() : anAddr; if (streaming && usingSocks()) { socksConnect(anAddr, aPort, 0); } else { IoBridge.connect(fd, normalAddr, aPort, timeout); } super.address = normalAddr; super.port = aPort; } @Override protected void create(boolean streaming) throws IOException { this.streaming = streaming; this.fd = IoBridge.socket(streaming); } @Override protected void finalize() throws Throwable { try { if (guard != null) { guard.warnIfOpen(); } close(); } finally { super.finalize(); } } @Override protected synchronized InputStream getInputStream() throws IOException { checkNotClosed(); return new PlainSocketInputStream(this); } private static class PlainSocketInputStream extends InputStream { private final PlainSocketImpl socketImpl; public PlainSocketInputStream(PlainSocketImpl socketImpl) { this.socketImpl = socketImpl; } @Override public int available() throws IOException { return socketImpl.available(); } @Override public void close() throws IOException { socketImpl.close(); } @Override public int read() throws IOException { return Streams.readSingleByte(this); } @Override public int read(byte[] buffer, int offset, int byteCount) throws IOException { return socketImpl.read(buffer, offset, byteCount); } } @Override public Object getOption(int option) throws SocketException { return IoBridge.getSocketOption(fd, option); } @Override protected synchronized OutputStream getOutputStream() throws IOException { checkNotClosed(); return new PlainSocketOutputStream(this); } private static class PlainSocketOutputStream extends OutputStream { private final PlainSocketImpl socketImpl; public PlainSocketOutputStream(PlainSocketImpl socketImpl) { this.socketImpl = socketImpl; } @Override public void close() throws IOException { socketImpl.close(); } @Override public void write(int oneByte) throws IOException { Streams.writeSingleByte(this, oneByte); } @Override public void write(byte[] buffer, int offset, int byteCount) throws IOException { socketImpl.write(buffer, offset, byteCount); } } @Override protected void listen(int backlog) throws IOException { if (usingSocks()) { // Do nothing for a SOCKS connection. The listen occurs on the // server during the bind. return; } try { Libcore.os.listen(fd, backlog); } catch (ErrnoException errnoException) { throw errnoException.rethrowAsSocketException(); } } @Override public void setOption(int option, Object value) throws SocketException { IoBridge.setSocketOption(fd, option, value); } /** * Gets the SOCKS proxy server port. */ private int socksGetServerPort() { // get socks server port from proxy. It is unnecessary to check // "socksProxyPort" property, since proxy setting should only be // determined by ProxySelector. InetSocketAddress addr = (InetSocketAddress) proxy.address(); return addr.getPort(); } /** * Gets the InetAddress of the SOCKS proxy server. */ private InetAddress socksGetServerAddress() throws UnknownHostException { String proxyName; // get socks server address from proxy. It is unnecessary to check // "socksProxyHost" property, since all proxy setting should be // determined by ProxySelector. InetSocketAddress addr = (InetSocketAddress) proxy.address(); proxyName = addr.getHostName(); if (proxyName == null) { proxyName = addr.getAddress().getHostAddress(); } return InetAddress.getByName(proxyName); } /** * Connect using a SOCKS server. */ private void socksConnect(InetAddress applicationServerAddress, int applicationServerPort, int timeout) throws IOException { try { IoBridge.connect(fd, socksGetServerAddress(), socksGetServerPort(), timeout); } catch (Exception e) { throw new SocketException("SOCKS connection failed", e); } socksRequestConnection(applicationServerAddress, applicationServerPort); lastConnectedAddress = applicationServerAddress; lastConnectedPort = applicationServerPort; } /** * Request a SOCKS connection to the application server given. If the * request fails to complete successfully, an exception is thrown. */ private void socksRequestConnection(InetAddress applicationServerAddress, int applicationServerPort) throws IOException { socksSendRequest(Socks4Message.COMMAND_CONNECT, applicationServerAddress, applicationServerPort); Socks4Message reply = socksReadReply(); if (reply.getCommandOrResult() != Socks4Message.RETURN_SUCCESS) { throw new IOException(reply.getErrorString(reply.getCommandOrResult())); } } /** * Perform an accept for a SOCKS bind. */ public void socksAccept() throws IOException { Socks4Message reply = socksReadReply(); if (reply.getCommandOrResult() != Socks4Message.RETURN_SUCCESS) { throw new IOException(reply.getErrorString(reply.getCommandOrResult())); } } /** * Shutdown the input portion of the socket. */ @Override protected void shutdownInput() throws IOException { shutdownInput = true; try { Libcore.os.shutdown(fd, SHUT_RD); } catch (ErrnoException errnoException) { throw errnoException.rethrowAsSocketException(); } } /** * Shutdown the output portion of the socket. */ @Override protected void shutdownOutput() throws IOException { try { Libcore.os.shutdown(fd, SHUT_WR); } catch (ErrnoException errnoException) { throw errnoException.rethrowAsSocketException(); } } /** * Bind using a SOCKS server. */ private void socksBind() throws IOException { try { IoBridge.connect(fd, socksGetServerAddress(), socksGetServerPort()); } catch (Exception e) { throw new IOException("Unable to connect to SOCKS server", e); } // There must be a connection to an application host for the bind to work. if (lastConnectedAddress == null) { throw new SocketException("Invalid SOCKS client"); } // Use the last connected address and port in the bind request. socksSendRequest(Socks4Message.COMMAND_BIND, lastConnectedAddress, lastConnectedPort); Socks4Message reply = socksReadReply(); if (reply.getCommandOrResult() != Socks4Message.RETURN_SUCCESS) { throw new IOException(reply.getErrorString(reply.getCommandOrResult())); } // A peculiarity of socks 4 - if the address returned is 0, use the // original socks server address. if (reply.getIP() == 0) { address = socksGetServerAddress(); } else { // IPv6 support not yet required as // currently the Socks4Message.getIP() only returns int, // so only works with IPv4 4byte addresses byte[] replyBytes = new byte[4]; Memory.pokeInt(replyBytes, 0, reply.getIP(), ByteOrder.BIG_ENDIAN); address = InetAddress.getByAddress(replyBytes); } localport = reply.getPort(); } /** * Send a SOCKS V4 request. */ private void socksSendRequest(int command, InetAddress address, int port) throws IOException { Socks4Message request = new Socks4Message(); request.setCommandOrResult(command); request.setPort(port); request.setIP(address.getAddress()); request.setUserId("default"); getOutputStream().write(request.getBytes(), 0, request.getLength()); } /** * Read a SOCKS V4 reply. */ private Socks4Message socksReadReply() throws IOException { Socks4Message reply = new Socks4Message(); int bytesRead = 0; while (bytesRead < Socks4Message.REPLY_LENGTH) { int count = getInputStream().read(reply.getBytes(), bytesRead, Socks4Message.REPLY_LENGTH - bytesRead); if (count == -1) { break; } bytesRead += count; } if (Socks4Message.REPLY_LENGTH != bytesRead) { throw new SocketException("Malformed reply from SOCKS server"); } return reply; } @Override protected void connect(SocketAddress remoteAddr, int timeout) throws IOException { InetSocketAddress inetAddr = (InetSocketAddress) remoteAddr; connect(inetAddr.getAddress(), inetAddr.getPort(), timeout); } @Override protected boolean supportsUrgentData() { return true; } @Override protected void sendUrgentData(int value) throws IOException { try { byte[] buffer = new byte[] { (byte) value }; Libcore.os.sendto(fd, buffer, 0, 1, MSG_OOB, null, 0); } catch (ErrnoException errnoException) { throw errnoException.rethrowAsSocketException(); } } /** * For PlainSocketInputStream. */ private int read(byte[] buffer, int offset, int byteCount) throws IOException { if (byteCount == 0) { return 0; } Arrays.checkOffsetAndCount(buffer.length, offset, byteCount); if (shutdownInput) { return -1; } int readCount = IoBridge.recvfrom(true, fd, buffer, offset, byteCount, 0, null, false); // Return of zero bytes for a blocking socket means a timeout occurred if (readCount == 0) { throw new SocketTimeoutException(); } // Return of -1 indicates the peer was closed if (readCount == -1) { shutdownInput = true; } return readCount; } /** * For PlainSocketOutputStream. */ private void write(byte[] buffer, int offset, int byteCount) throws IOException { Arrays.checkOffsetAndCount(buffer.length, offset, byteCount); if (streaming) { while (byteCount > 0) { int bytesWritten = IoBridge.sendto(fd, buffer, offset, byteCount, 0, null, 0); byteCount -= bytesWritten; offset += bytesWritten; } } else { // Unlike writes to a streaming socket, writes to a datagram // socket are all-or-nothing, so we don't need a loop here. // http://code.google.com/p/android/issues/detail?id=15304 // RoboVM note: The original code passed this.address here as // destination address. However, on Darwin sendto() fails with // EINVAL if called with a non-null destination address for an // already connected socket (see issue #76). Non-streaming Sockets // are always connected in the constructor so it should be safe to // pass null here instead. IoBridge.sendto(fd, buffer, offset, byteCount, 0, null, port); } } }
false
true
protected void accept(SocketImpl newImpl) throws IOException { if (usingSocks()) { ((PlainSocketImpl) newImpl).socksBind(); ((PlainSocketImpl) newImpl).socksAccept(); return; } try { // RovmVM note: accept() on Darwin does not honor the SO_RCVTIMEO // set using setSoTimeout(). As a work around we do poll() if a // timeout has been set followed by an accept(). int timeout = (Integer) getOption(SO_RCVTIMEO); if (timeout > 0) { StructPollfd pfd = new StructPollfd(); pfd.fd = fd; pfd.events = (short) (POLLIN | POLLERR); StructPollfd[] pfds = new StructPollfd[] {pfd}; while (true) { long start = System.currentTimeMillis(); try { if (timeout <= 0 || Libcore.os.poll(pfds, timeout) == 0) { throw new SocketTimeoutException("accept() timed out"); } } catch (ErrnoException e) { if (e.errno == EINTR) { long duration = System.currentTimeMillis() - start; timeout -= duration; } else { throw e; } } } } InetSocketAddress peerAddress = new InetSocketAddress(); FileDescriptor clientFd = Libcore.os.accept(fd, peerAddress); // TODO: we can't just set newImpl.fd to clientFd because a nio SocketChannel may // be sharing the FileDescriptor. http://b//4452981. newImpl.fd.setInt$(clientFd.getInt$()); newImpl.address = peerAddress.getAddress(); newImpl.port = peerAddress.getPort(); } catch (ErrnoException errnoException) { if (errnoException.errno == EAGAIN || errnoException.errno == EWOULDBLOCK) { throw new SocketTimeoutException(errnoException); } throw errnoException.rethrowAsSocketException(); } // Reset the client's inherited read timeout to the Java-specified default of 0. newImpl.setOption(SocketOptions.SO_TIMEOUT, Integer.valueOf(0)); newImpl.localport = IoBridge.getSocketLocalPort(newImpl.fd); }
protected void accept(SocketImpl newImpl) throws IOException { if (usingSocks()) { ((PlainSocketImpl) newImpl).socksBind(); ((PlainSocketImpl) newImpl).socksAccept(); return; } try { // RovmVM note: accept() on Darwin does not honor the SO_RCVTIMEO // set using setSoTimeout(). As a work around we do poll() if a // timeout has been set followed by an accept(). int timeout = (Integer) getOption(SO_RCVTIMEO); if (timeout > 0) { StructPollfd pfd = new StructPollfd(); pfd.fd = fd; pfd.events = (short) (POLLIN | POLLERR); StructPollfd[] pfds = new StructPollfd[] {pfd}; long start = System.currentTimeMillis(); long deadline = start + timeout; while (true) { try { if (timeout <= 0 || Libcore.os.poll(pfds, timeout) == 0) { throw new SocketTimeoutException("accept() timed out"); } break; } catch (ErrnoException e) { if (e.errno == EINTR) { long now = System.currentTimeMillis(); timeout = (int) (deadline - now); } else { throw e; } } } } InetSocketAddress peerAddress = new InetSocketAddress(); FileDescriptor clientFd = Libcore.os.accept(fd, peerAddress); // TODO: we can't just set newImpl.fd to clientFd because a nio SocketChannel may // be sharing the FileDescriptor. http://b//4452981. newImpl.fd.setInt$(clientFd.getInt$()); newImpl.address = peerAddress.getAddress(); newImpl.port = peerAddress.getPort(); } catch (ErrnoException errnoException) { if (errnoException.errno == EAGAIN || errnoException.errno == EWOULDBLOCK) { throw new SocketTimeoutException(errnoException); } throw errnoException.rethrowAsSocketException(); } // Reset the client's inherited read timeout to the Java-specified default of 0. newImpl.setOption(SocketOptions.SO_TIMEOUT, Integer.valueOf(0)); newImpl.localport = IoBridge.getSocketLocalPort(newImpl.fd); }
diff --git a/plugins/org.eclipse.emf.mwe2.launch/src/org/eclipse/emf/mwe2/launch/runtime/Mwe2Runner.java b/plugins/org.eclipse.emf.mwe2.launch/src/org/eclipse/emf/mwe2/launch/runtime/Mwe2Runner.java index adacda0c..1803cfbb 100644 --- a/plugins/org.eclipse.emf.mwe2.launch/src/org/eclipse/emf/mwe2/launch/runtime/Mwe2Runner.java +++ b/plugins/org.eclipse.emf.mwe2.launch/src/org/eclipse/emf/mwe2/launch/runtime/Mwe2Runner.java @@ -1,106 +1,115 @@ /******************************************************************************* * Copyright (c) 2008,2010 itemis AG (http://www.itemis.eu) and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * *******************************************************************************/ package org.eclipse.emf.mwe2.launch.runtime; import java.util.HashMap; import java.util.List; import java.util.Map; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.util.EcoreUtil; import org.eclipse.emf.mwe2.language.factory.Mwe2ExecutionEngine; import org.eclipse.emf.mwe2.language.mwe2.Module; import org.eclipse.emf.mwe2.language.mwe2.Mwe2Package; import org.eclipse.emf.mwe2.runtime.workflow.IWorkflow; import org.eclipse.emf.mwe2.runtime.workflow.WorkflowContextImpl; import org.eclipse.xtext.mwe.RuntimeResourceSetInitializer; import org.eclipse.xtext.resource.IEObjectDescription; import org.eclipse.xtext.resource.IResourceDescription; import org.eclipse.xtext.resource.IResourceDescriptions; import com.google.common.collect.Maps; import com.google.inject.Inject; import com.google.inject.Provider; public class Mwe2Runner { @Inject private RuntimeResourceSetInitializer initializer; @Inject private Mwe2ExecutionEngine engine; @Inject private Provider<ResourceSet> resourceSetProvider; public void run(URI createURI, Map<String, String> params) { Resource resource = resourceSetProvider.get().getResource(createURI, true); if (resource != null) { if (!resource.getContents().isEmpty()) { EObject eObject = resource.getContents().get(0); if (eObject instanceof Module) { run(((Module) eObject).getCanonicalName(), params); return; } } } throw new IllegalArgumentException("Couldn't load module from URI " + createURI); } public void run(String moduleName, Map<String, String> params) { Module module = findModule(moduleName); if (module == null) throw new IllegalArgumentException("Couldn't find module with name '" + moduleName + "'."); EcoreUtil.resolveAll(module); if (!module.eResource().getErrors().isEmpty()) { throw new IllegalStateException(module.eResource().getErrors().toString()); } Map<String, Object> actualParams = getRealParams(params); - Object object = engine.create(module, actualParams); + Object object = null; + try { + object = engine.create(module, actualParams); + } catch (RuntimeException e) { + throw new RuntimeException("Problems instantiating module " + moduleName, e); + } if (!(object instanceof IWorkflow)) { throw new IllegalArgumentException("The root element must be of type IWorkflow but was '" + object.getClass() + "'."); } - ((IWorkflow) object).run(new WorkflowContextImpl()); + try { + ((IWorkflow) object).run(new WorkflowContextImpl()); + } catch (RuntimeException e) { + throw new RuntimeException("Problems running workflow " + moduleName, e); + } } protected Map<String, Object> getRealParams(Map<String, String> params) { HashMap<String, Object> map = Maps.newHashMap(); map.putAll(params); return map; } protected Module findModule(String moduleName) { ResourceSet resourceSet = initializer.getInitializedResourceSet(getPathes()); IResourceDescriptions descriptions = initializer.getDescriptions(resourceSet); for (IResourceDescription desc : descriptions.getAllResourceDescriptions()) { Iterable<IEObjectDescription> iterable = desc.getExportedObjects(Mwe2Package.Literals.MODULE, moduleName); for (IEObjectDescription objDesc : iterable) { return (Module) resourceSet.getEObject(objDesc.getEObjectURI(), true); } } return null; } protected List<String> getPathes() { return initializer.getClassPathEntries(); } public void setEngine(Mwe2ExecutionEngine engine) { this.engine = engine; } public void setInitializer(RuntimeResourceSetInitializer initializer) { this.initializer = initializer; } }
false
true
public void run(String moduleName, Map<String, String> params) { Module module = findModule(moduleName); if (module == null) throw new IllegalArgumentException("Couldn't find module with name '" + moduleName + "'."); EcoreUtil.resolveAll(module); if (!module.eResource().getErrors().isEmpty()) { throw new IllegalStateException(module.eResource().getErrors().toString()); } Map<String, Object> actualParams = getRealParams(params); Object object = engine.create(module, actualParams); if (!(object instanceof IWorkflow)) { throw new IllegalArgumentException("The root element must be of type IWorkflow but was '" + object.getClass() + "'."); } ((IWorkflow) object).run(new WorkflowContextImpl()); }
public void run(String moduleName, Map<String, String> params) { Module module = findModule(moduleName); if (module == null) throw new IllegalArgumentException("Couldn't find module with name '" + moduleName + "'."); EcoreUtil.resolveAll(module); if (!module.eResource().getErrors().isEmpty()) { throw new IllegalStateException(module.eResource().getErrors().toString()); } Map<String, Object> actualParams = getRealParams(params); Object object = null; try { object = engine.create(module, actualParams); } catch (RuntimeException e) { throw new RuntimeException("Problems instantiating module " + moduleName, e); } if (!(object instanceof IWorkflow)) { throw new IllegalArgumentException("The root element must be of type IWorkflow but was '" + object.getClass() + "'."); } try { ((IWorkflow) object).run(new WorkflowContextImpl()); } catch (RuntimeException e) { throw new RuntimeException("Problems running workflow " + moduleName, e); } }
diff --git a/src/synclogic/ClientSynchronizationUnit.java b/src/synclogic/ClientSynchronizationUnit.java index 430e2c1..3b291c8 100644 --- a/src/synclogic/ClientSynchronizationUnit.java +++ b/src/synclogic/ClientSynchronizationUnit.java @@ -1,316 +1,317 @@ package synclogic; import gui.GUILoggInInfo; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.IOException; import java.net.ConnectException; import java.net.InetAddress; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.swing.Timer; import model.Appointment; import model.Meeting; import model.Notification; import model.Room; import model.SaveableClass; import model.User; import model.XmlSerializerX; import no.ntnu.fp.net.co.Connection; import no.ntnu.fp.net.co.ConnectionImpl; import nu.xom.ParsingException; public class ClientSynchronizationUnit extends SynchronizationUnit implements PropertyChangeListener { private MessageQueue sendQueue; private Connection connection; private LoginRequest loginRequest; private UpdateRequest updateRequest; private Thread thread; private boolean stopThread = false; private GUILoggInInfo notificationShower; private static final int TIME_BETWEEN_UPDATES = 20000; public ClientSynchronizationUnit(){ this.sendQueue = new MessageQueue(); this.sendQueue.addPropertyChangeListener(this); this.thread = new Thread(new SendClass()); ActionListener updater = new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { System.out.println("Looking for updates"); synchronized (this) { try { List<ErrorMessage> errors = update(); for (ErrorMessage error : errors) { handleError(error); } } catch (Exception e) { e.printStackTrace(); } } System.out.println("Done"); } }; new Timer(TIME_BETWEEN_UPDATES, updater).start(); } public void setNotificationShower(GUILoggInInfo notificationShower) { this.notificationShower = notificationShower; } public void handleError(ErrorMessage error) { System.out.println("Behandler error..."); if(error.getValidObject() == null) { // Opprettelse av objekt var ikke lovlig this.listeners.remove(this.getObjectFromID(error.getInvalidObject().getSaveableClass(), error.getInvalidObject().getObjectID())); // TODO: La brukeren bestemme hva som skal skje } // TODO: Gjoer mer! } public void addToSendQueue(String o) { this.sendQueue.add(o); } public void addToSendQueue(SyncListener o) { this.sendQueue.add(XmlSerializerX.toXml(o, o.getSaveableClass())); } public List<Room> getAvailableRooms(Date start, Date end) { this.addToSendQueue(XmlSerializerX.toXml(new RoomAvailabilityRequest(start, end), SaveableClass.RoomAvailabilityRequest)); try { return (List<Room>) ((RoomAvailabilityRequest) XmlSerializerX.toObject(this.connection.receive())).getAvailableRooms(); } catch (Exception e) { e.printStackTrace(); return null; } } @Override public void propertyChange(PropertyChangeEvent event) { System.out.println("Thread state: " + this.thread.getState()); if (!this.thread.isAlive()){ new Thread(new SendClass()).start(); this.stopThread = false; } } private synchronized void internalWait(int time){ try { wait(time); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } class SendClass implements Runnable{ @Override public void run() { internalWait(50); while(!stopThread){ while (!sendQueue.isEmpty()){ try { connection.send(sendQueue.pop()); } catch (ConnectException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } internalWait(30); } internalWait(50); } } } /** * Sets up a connection to a server * @param ipAddress The IP address for the server to connect to * @param port The port to connect to */ public void connectToServer(String ipAddress, int port) throws IOException{ // TODO: Should the port really be 9999? this.connection = new ConnectionImpl(9999); try { this.connection.connect(InetAddress.getByName(ipAddress), port); internalWait(50); } catch (SocketTimeoutException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Logs in the user * @param username The username to log in * @param password The password that belongs to the username * @throws ConnectException If anything related to the connection goes wrong */ public boolean logIn(String username, String password) throws ConnectException{ this.loginRequest = new LoginRequest(username, password); try { this.connection.send(XmlSerializerX.toXml(this.loginRequest, SaveableClass.LoginRequest)); LoginRequest respons = (LoginRequest) XmlSerializerX.toObject(this.connection.receive()); if (respons.getLoginAccepted()){ update(); } return respons.getLoginAccepted(); } catch (IOException e) { throw new ConnectException(); } catch (ParseException e) { throw new ConnectException(); } catch (ParsingException e) { throw new ConnectException(); } } /** * Checks for updates on the server * @return A list of ErrorMessages from the server * @throws ConnectException If anything related to the connection goes wrong */ public List<ErrorMessage> update() throws ConnectException{ this.updateRequest = new UpdateRequest(); List<ErrorMessage> errorMessages = new ArrayList<ErrorMessage>(); try { addToSendQueue(XmlSerializerX.toXml(this.updateRequest, SaveableClass.UpdateRequest)); UpdateRequest respons = (UpdateRequest) XmlSerializerX.toObject(this.connection.receive()); for (int i = 0; i<respons.size(); i++) { if (respons.getObject(i) instanceof SyncListener){ SyncListener object = (SyncListener) respons.getObject(i); if (getObjectFromID(object.getSaveableClass(), object.getObjectID()) != null){ fire(object.getSaveableClass(), object.getObjectID(), object); } else{ addObject(object); } } else{ errorMessages.add((ErrorMessage) respons.getObject(i)); } } } catch (IOException e) { throw new ConnectException(); } catch (ParseException e) { throw new ConnectException(); } catch (ParsingException e) { throw new ConnectException(); } - if(this.notificationShower != null) { - this.notificationShower.loadNotifications(); - } + // TODO: uncomment under! +// if(this.notificationShower != null) { +// this.notificationShower.loadNotifications(); +// } return errorMessages; } /** * Returns a list of all the local users * @return A list of users */ public List<User> getAllUsers() { List<User> users = new ArrayList<User>(); for (SyncListener object : this.listeners) { if (object.getSaveableClass() == SaveableClass.User){ users.add((User) object); } } return users; } /** * Returns a list of all the local appointments * @return A list of users */ public List<Appointment> getAllAppointments() { List<Appointment> appointments = new ArrayList<Appointment>(); for (SyncListener object : this.listeners) { if (object instanceof Meeting){ System.out.println(((Meeting) object).getDescription()); appointments.add((Meeting) object); } else if (object instanceof Appointment){ appointments.add((Appointment) object); } } return appointments; } /** * Closes this connection * @throws IOException */ public void disconnect() throws IOException{ int counter = 0; while(true){ try { if (this.sendQueue.isEmpty()){ internalWait(500); this.connection.close(); this.stopThread = true; return; } } catch (IOException e) { if (counter>2){ throw e; } } counter++; internalWait(50); } } // public static void main(String[] args){ // ClientSynchronizationUnit syncUnit = new ClientSynchronizationUnit(); // try { // syncUnit.connectToServer("localhost", 1337); // syncUnit.logIn("joharei", "123"); // System.out.println("Logged in!!"); // } catch (ConnectException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } //// for (int i = 0; i<10; i++){ //// syncUnit.addToSendQueue("Element " + i); //// } // syncUnit.disconnect(); // } @Override public void addObject(SyncListener o) { if (o instanceof User){ this.listeners.add(o); for (Notification not : ((User) o).getNotifications()) { this.listeners.add(not); } } else if (o instanceof Appointment){ this.listeners.add(o); } } }
true
true
public List<ErrorMessage> update() throws ConnectException{ this.updateRequest = new UpdateRequest(); List<ErrorMessage> errorMessages = new ArrayList<ErrorMessage>(); try { addToSendQueue(XmlSerializerX.toXml(this.updateRequest, SaveableClass.UpdateRequest)); UpdateRequest respons = (UpdateRequest) XmlSerializerX.toObject(this.connection.receive()); for (int i = 0; i<respons.size(); i++) { if (respons.getObject(i) instanceof SyncListener){ SyncListener object = (SyncListener) respons.getObject(i); if (getObjectFromID(object.getSaveableClass(), object.getObjectID()) != null){ fire(object.getSaveableClass(), object.getObjectID(), object); } else{ addObject(object); } } else{ errorMessages.add((ErrorMessage) respons.getObject(i)); } } } catch (IOException e) { throw new ConnectException(); } catch (ParseException e) { throw new ConnectException(); } catch (ParsingException e) { throw new ConnectException(); } if(this.notificationShower != null) { this.notificationShower.loadNotifications(); } return errorMessages; }
public List<ErrorMessage> update() throws ConnectException{ this.updateRequest = new UpdateRequest(); List<ErrorMessage> errorMessages = new ArrayList<ErrorMessage>(); try { addToSendQueue(XmlSerializerX.toXml(this.updateRequest, SaveableClass.UpdateRequest)); UpdateRequest respons = (UpdateRequest) XmlSerializerX.toObject(this.connection.receive()); for (int i = 0; i<respons.size(); i++) { if (respons.getObject(i) instanceof SyncListener){ SyncListener object = (SyncListener) respons.getObject(i); if (getObjectFromID(object.getSaveableClass(), object.getObjectID()) != null){ fire(object.getSaveableClass(), object.getObjectID(), object); } else{ addObject(object); } } else{ errorMessages.add((ErrorMessage) respons.getObject(i)); } } } catch (IOException e) { throw new ConnectException(); } catch (ParseException e) { throw new ConnectException(); } catch (ParsingException e) { throw new ConnectException(); } // TODO: uncomment under! // if(this.notificationShower != null) { // this.notificationShower.loadNotifications(); // } return errorMessages; }
diff --git a/stripes/src/net/sourceforge/stripes/controller/multipart/DefaultMultipartWrapperFactory.java b/stripes/src/net/sourceforge/stripes/controller/multipart/DefaultMultipartWrapperFactory.java index 6458278..bc91e6d 100644 --- a/stripes/src/net/sourceforge/stripes/controller/multipart/DefaultMultipartWrapperFactory.java +++ b/stripes/src/net/sourceforge/stripes/controller/multipart/DefaultMultipartWrapperFactory.java @@ -1,171 +1,171 @@ /* Copyright 2005-2006 Tim Fennell * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sourceforge.stripes.controller.multipart; import net.sourceforge.stripes.controller.FileUploadLimitExceededException; import net.sourceforge.stripes.config.Configuration; import net.sourceforge.stripes.util.Log; import net.sourceforge.stripes.exception.StripesRuntimeException; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.io.File; import java.util.regex.Pattern; import java.util.regex.Matcher; /** * <p>Default implementation of a factory for MultipartWrappers. Looks up a class name in * Configuration under the key specified by {@link #WRAPPER_CLASS_NAME}. If no class * name is configured, defaults to the {@link CosMultipartWrapper}. An additional configuration * parameter is supported to specify the maximum post size allowable.</p> * * @author Tim Fennell * @since Stripes 1.4 */ public class DefaultMultipartWrapperFactory implements MultipartWrapperFactory { /** The configuration key used to lookup the implementation of MultipartWrapper. */ public static final String WRAPPER_CLASS_NAME = "MultipartWrapper.Class"; /** The names of the MultipartWrapper classes that will be tried if no other is specified. */ public static final String[] BUNDLED_IMPLEMENTATIONS = { "net.sourceforge.stripes.controller.multipart.CommonsMultipartWrapper", "net.sourceforge.stripes.controller.multipart.CosMultipartWrapper" }; /** Key used to lookup the name of the maximum post size. */ public static final String MAX_POST = "FileUpload.MaximumPostSize"; private static final Log log = Log.getInstance(DefaultMultipartWrapperFactory.class); // Instance level fields private Configuration configuration; private Class<? extends MultipartWrapper> multipartClass; private long maxPostSizeInBytes = 1024 * 1024 * 10; // Defaults to 10MB private File temporaryDirectory; /** Get the configuration object that was passed into {@link #init(Configuration)}. */ protected Configuration getConfiguration() { return configuration; } /** * Invoked directly after instantiation to allow the configured component to perform one time * initialization. Components are expected to fail loudly if they are not going to be in a * valid state after initialization. * * @param config the Configuration object being used by Stripes * @throws Exception should be thrown if the component cannot be configured well enough to use. */ @SuppressWarnings("unchecked") public void init(Configuration config) throws Exception { this.configuration = config; // Determine which class we're using this.multipartClass = config.getBootstrapPropertyResolver().getClassProperty(WRAPPER_CLASS_NAME, MultipartWrapper.class); if (this.multipartClass == null) { // It wasn't defined in web.xml so we'll try the bundled MultipartWrappers for (String className : BUNDLED_IMPLEMENTATIONS) { try { this.multipartClass = ((Class<? extends MultipartWrapper>) Class .forName(className)); break; } catch (Throwable t) { log.debug(getClass().getSimpleName(), " not using ", className, " because it failed to load. This likely means the supporting ", "file upload library is not present on the classpath."); } } } // Log the name of the class we'll be using or a warning if none could be loaded if (this.multipartClass == null) { log.warn("No ", MultipartWrapper.class.getSimpleName(), " implementation could be loaded"); } else { log.info("Using ", this.multipartClass.getName(), " as ", MultipartWrapper.class .getSimpleName(), " implementation."); } // Figure out where the temp directory is, and store that info File tempDir = (File) config.getServletContext().getAttribute("javax.servlet.context.tempdir"); if (tempDir != null) { this.temporaryDirectory = tempDir; } else { String tmpDir = System.getProperty("java.io.tmpdir"); if (tmpDir != null) { this.temporaryDirectory = new File(tmpDir).getAbsoluteFile(); } else { log.warn("The tmpdir system property was null! File uploads will probably fail. ", "This is normal if you are running on Google App Engine as it doesn't allow ", "file system write access."); } } // See if a maximum post size was configured String limit = config.getBootstrapPropertyResolver().getProperty(MAX_POST); if (limit != null) { Pattern pattern = Pattern.compile("([\\d,]+)([kKmMgG]?).*"); Matcher matcher = pattern.matcher(limit); if (!matcher.matches()) { log.error("Did not understand value of configuration parameter ", MAX_POST, " You supplied: ", limit, ". Valid values are any string of numbers ", "optionally followed by (case insensitive) [k|kb|m|mb|g|gb]. ", "Default value of ", this.maxPostSizeInBytes, " bytes will be used instead."); } else { String digits = matcher.group(1); String suffix = matcher.group(2).toLowerCase(); - int number = Integer.parseInt(digits); + long number = Long.parseLong(digits); if ("k".equals(suffix)) { number = number * 1024; } else if ("m".equals(suffix)) { number = number * 1024 * 1024; } else if ("g".equals(suffix)) { number = number * 1024 * 1024 * 1024; } this.maxPostSizeInBytes = number; log.info("Configured file upload post size limit: ", number, " bytes."); } } } /** * Wraps the request in an appropriate implementation of MultipartWrapper that is capable of * providing access to request parameters and any file parts contained within the request. * * @param request an active HttpServletRequest * @return an implementation of the appropriate wrapper * @throws IOException if encountered when consuming the contents of the request * @throws FileUploadLimitExceededException if the post size of the request exceeds any * configured limits */ public MultipartWrapper wrap(HttpServletRequest request) throws IOException, FileUploadLimitExceededException { try { MultipartWrapper wrapper = getConfiguration().getObjectFactory().newInstance( this.multipartClass); wrapper.build(request, this.temporaryDirectory, this.maxPostSizeInBytes); return wrapper; } catch (IOException ioe) { throw ioe; } catch (FileUploadLimitExceededException fulee) { throw fulee; } catch (Exception e) { throw new StripesRuntimeException ("Could not construct a MultipartWrapper for the current request.", e); } } }
true
true
public void init(Configuration config) throws Exception { this.configuration = config; // Determine which class we're using this.multipartClass = config.getBootstrapPropertyResolver().getClassProperty(WRAPPER_CLASS_NAME, MultipartWrapper.class); if (this.multipartClass == null) { // It wasn't defined in web.xml so we'll try the bundled MultipartWrappers for (String className : BUNDLED_IMPLEMENTATIONS) { try { this.multipartClass = ((Class<? extends MultipartWrapper>) Class .forName(className)); break; } catch (Throwable t) { log.debug(getClass().getSimpleName(), " not using ", className, " because it failed to load. This likely means the supporting ", "file upload library is not present on the classpath."); } } } // Log the name of the class we'll be using or a warning if none could be loaded if (this.multipartClass == null) { log.warn("No ", MultipartWrapper.class.getSimpleName(), " implementation could be loaded"); } else { log.info("Using ", this.multipartClass.getName(), " as ", MultipartWrapper.class .getSimpleName(), " implementation."); } // Figure out where the temp directory is, and store that info File tempDir = (File) config.getServletContext().getAttribute("javax.servlet.context.tempdir"); if (tempDir != null) { this.temporaryDirectory = tempDir; } else { String tmpDir = System.getProperty("java.io.tmpdir"); if (tmpDir != null) { this.temporaryDirectory = new File(tmpDir).getAbsoluteFile(); } else { log.warn("The tmpdir system property was null! File uploads will probably fail. ", "This is normal if you are running on Google App Engine as it doesn't allow ", "file system write access."); } } // See if a maximum post size was configured String limit = config.getBootstrapPropertyResolver().getProperty(MAX_POST); if (limit != null) { Pattern pattern = Pattern.compile("([\\d,]+)([kKmMgG]?).*"); Matcher matcher = pattern.matcher(limit); if (!matcher.matches()) { log.error("Did not understand value of configuration parameter ", MAX_POST, " You supplied: ", limit, ". Valid values are any string of numbers ", "optionally followed by (case insensitive) [k|kb|m|mb|g|gb]. ", "Default value of ", this.maxPostSizeInBytes, " bytes will be used instead."); } else { String digits = matcher.group(1); String suffix = matcher.group(2).toLowerCase(); int number = Integer.parseInt(digits); if ("k".equals(suffix)) { number = number * 1024; } else if ("m".equals(suffix)) { number = number * 1024 * 1024; } else if ("g".equals(suffix)) { number = number * 1024 * 1024 * 1024; } this.maxPostSizeInBytes = number; log.info("Configured file upload post size limit: ", number, " bytes."); } } }
public void init(Configuration config) throws Exception { this.configuration = config; // Determine which class we're using this.multipartClass = config.getBootstrapPropertyResolver().getClassProperty(WRAPPER_CLASS_NAME, MultipartWrapper.class); if (this.multipartClass == null) { // It wasn't defined in web.xml so we'll try the bundled MultipartWrappers for (String className : BUNDLED_IMPLEMENTATIONS) { try { this.multipartClass = ((Class<? extends MultipartWrapper>) Class .forName(className)); break; } catch (Throwable t) { log.debug(getClass().getSimpleName(), " not using ", className, " because it failed to load. This likely means the supporting ", "file upload library is not present on the classpath."); } } } // Log the name of the class we'll be using or a warning if none could be loaded if (this.multipartClass == null) { log.warn("No ", MultipartWrapper.class.getSimpleName(), " implementation could be loaded"); } else { log.info("Using ", this.multipartClass.getName(), " as ", MultipartWrapper.class .getSimpleName(), " implementation."); } // Figure out where the temp directory is, and store that info File tempDir = (File) config.getServletContext().getAttribute("javax.servlet.context.tempdir"); if (tempDir != null) { this.temporaryDirectory = tempDir; } else { String tmpDir = System.getProperty("java.io.tmpdir"); if (tmpDir != null) { this.temporaryDirectory = new File(tmpDir).getAbsoluteFile(); } else { log.warn("The tmpdir system property was null! File uploads will probably fail. ", "This is normal if you are running on Google App Engine as it doesn't allow ", "file system write access."); } } // See if a maximum post size was configured String limit = config.getBootstrapPropertyResolver().getProperty(MAX_POST); if (limit != null) { Pattern pattern = Pattern.compile("([\\d,]+)([kKmMgG]?).*"); Matcher matcher = pattern.matcher(limit); if (!matcher.matches()) { log.error("Did not understand value of configuration parameter ", MAX_POST, " You supplied: ", limit, ". Valid values are any string of numbers ", "optionally followed by (case insensitive) [k|kb|m|mb|g|gb]. ", "Default value of ", this.maxPostSizeInBytes, " bytes will be used instead."); } else { String digits = matcher.group(1); String suffix = matcher.group(2).toLowerCase(); long number = Long.parseLong(digits); if ("k".equals(suffix)) { number = number * 1024; } else if ("m".equals(suffix)) { number = number * 1024 * 1024; } else if ("g".equals(suffix)) { number = number * 1024 * 1024 * 1024; } this.maxPostSizeInBytes = number; log.info("Configured file upload post size limit: ", number, " bytes."); } } }
diff --git a/org.eclipse.mylyn.wikitext.ui/src/org/eclipse/mylyn/internal/wikitext/ui/WikiTextUiPlugin.java b/org.eclipse.mylyn.wikitext.ui/src/org/eclipse/mylyn/internal/wikitext/ui/WikiTextUiPlugin.java index 4f2ad7c8..570cc5f6 100644 --- a/org.eclipse.mylyn.wikitext.ui/src/org/eclipse/mylyn/internal/wikitext/ui/WikiTextUiPlugin.java +++ b/org.eclipse.mylyn.wikitext.ui/src/org/eclipse/mylyn/internal/wikitext/ui/WikiTextUiPlugin.java @@ -1,288 +1,288 @@ /******************************************************************************* * Copyright (c) 2007, 2008 David Green and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * David Green - initial API and implementation *******************************************************************************/ package org.eclipse.mylyn.internal.wikitext.ui; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.IExtensionPoint; import org.eclipse.core.runtime.ILog; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; import org.eclipse.jface.text.templates.Template; import org.eclipse.mylyn.internal.wikitext.ui.editor.assist.MarkupTemplateCompletionProcessor; import org.eclipse.mylyn.internal.wikitext.ui.editor.assist.Templates; import org.eclipse.mylyn.internal.wikitext.ui.editor.help.CheatSheetContent; import org.eclipse.mylyn.internal.wikitext.ui.editor.help.HelpContent; import org.eclipse.mylyn.internal.wikitext.ui.editor.preferences.Preferences; import org.eclipse.mylyn.wikitext.core.WikiTextPlugin; import org.eclipse.mylyn.wikitext.core.parser.markup.MarkupLanguage; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; /** * * * @author David Green */ public class WikiTextUiPlugin extends AbstractUIPlugin { private static final String EXTENSION_POINT_CHEAT_SHEET = "cheatSheet"; private static final String EXTENSION_POINT_CONTENT_ASSIST = "contentAssist"; private static final String EXTENSION_POINT_TEMPLATES = "templates"; private static final String EXTENSION_POINT_TEMPLATE = "template"; private static WikiTextUiPlugin plugin; private SortedMap<String, HelpContent> cheatSheets; private Map<String, Templates> templates; public WikiTextUiPlugin() { plugin = this; } @Override public void start(BundleContext context) throws Exception { super.start(context); } @Override public void stop(BundleContext context) throws Exception { plugin = null; super.stop(context); } /** * Returns the shared instance * * @return the shared instance */ public static WikiTextUiPlugin getDefault() { return plugin; } public void log(Throwable ce) { if (ce instanceof CoreException) { getLog().log(((CoreException) ce).getStatus()); } else { log(IStatus.ERROR, ce.getMessage(), ce); } } public void log(int severity, String message, Throwable exception) { if (message == null) { message = ""; } ILog log = getLog(); IStatus status = null; if (exception instanceof CoreException) { status = ((CoreException) exception).getStatus(); } if (status == null) { status = new Status(severity, getPluginId(), severity, message, exception); } log.log(status); } public String getPluginId() { return getBundle().getSymbolicName(); } public IStatus createStatus(int statusCode, Throwable exception) { return createStatus(null, statusCode, exception); } public IStatus createStatus(String message, int statusCode, Throwable exception) { if (message == null && exception != null) { message = exception.getClass().getName() + ": " + exception.getMessage(); } Status status = new Status(statusCode, getPluginId(), statusCode, message, exception); return status; } public Preferences getPreferences() { Preferences prefs = new Preferences(); prefs.load(getPreferenceStore()); return prefs; } public SortedMap<String, HelpContent> getCheatSheets() { if (cheatSheets == null) { SortedMap<String, HelpContent> cheatSheets = new TreeMap<String, HelpContent>(); IExtensionPoint extensionPoint = Platform.getExtensionRegistry().getExtensionPoint(getPluginId(), EXTENSION_POINT_CHEAT_SHEET); if (extensionPoint != null) { IConfigurationElement[] configurationElements = extensionPoint.getConfigurationElements(); for (IConfigurationElement element : configurationElements) { String declaringPluginId = element.getDeclaringExtension().getContributor().getName(); Bundle bundle = Platform.getBundle(declaringPluginId); String markupLanguage = element.getAttribute("markupLanguage"); String contentLanguage = element.getAttribute("contentLanguage"); String resource = element.getAttribute("resource"); try { if (markupLanguage == null) { throw new Exception("Must specify markupLanguage"); } else if (!WikiTextPlugin.getDefault().getMarkupLanguageNames().contains(markupLanguage)) { throw new Exception(String.format("'%s' is not a valid markupLanguage", markupLanguage)); } if (resource == null || resource.length() == 0) { throw new Exception("Must specify resource"); } HelpContent cheatSheet = new CheatSheetContent(bundle, resource, contentLanguage, markupLanguage); HelpContent previous = cheatSheets.put(cheatSheet.getMarkupLanguageName(), cheatSheet); if (previous != null) { cheatSheets.put(previous.getMarkupLanguageName(), previous); throw new Exception(String.format( "content for markupLanguage '%s' is already declared by plugin '%s'", previous.getMarkupLanguageName(), previous.getProvider().getSymbolicName())); } } catch (Exception e) { log(IStatus.ERROR, String.format("Plugin '%s' extension '%s' invalid: %s", declaringPluginId, EXTENSION_POINT_CHEAT_SHEET, e.getMessage()), e); } } } this.cheatSheets = Collections.unmodifiableSortedMap(cheatSheets); } return cheatSheets; } /** * get templates mapped by their markup language name * * @return the templates */ public Map<String, Templates> getTemplates() { if (templates == null) { Map<String, Templates> templates = new HashMap<String, Templates>(); IExtensionPoint extensionPoint = Platform.getExtensionRegistry().getExtensionPoint(getPluginId(), EXTENSION_POINT_CONTENT_ASSIST); if (extensionPoint != null) { IConfigurationElement[] configurationElements = extensionPoint.getConfigurationElements(); for (IConfigurationElement element : configurationElements) { String declaringPluginId = element.getDeclaringExtension().getContributor().getName(); if (EXTENSION_POINT_TEMPLATES.equals(element.getName())) { try { String markupLanguage = element.getAttribute("markupLanguage"); if (markupLanguage == null) { throw new Exception("Must specify markupLanguage"); } else if (!WikiTextPlugin.getDefault().getMarkupLanguageNames().contains(markupLanguage)) { throw new Exception(String.format("'%s' is not a valid markupLanguage", markupLanguage)); } Templates markupLanguageTemplates = new Templates(); markupLanguageTemplates.setMarkupLanguageName(markupLanguage); for (IConfigurationElement templatesChild : element.getChildren()) { if (EXTENSION_POINT_TEMPLATE.equals(templatesChild.getName())) { try { // process the template String name = templatesChild.getAttribute("name"); String description = templatesChild.getAttribute("description"); String content = templatesChild.getAttribute("content"); String autoInsert = templatesChild.getAttribute("autoInsert"); String block = templatesChild.getAttribute("block"); if (name == null || name.length() == 0) { - throw new Exception(String.format("Must specify %s/name", + throw new Exception(String.format("Must specify %s/@name", EXTENSION_POINT_TEMPLATE)); } if (description == null || description.length() == 0) { - throw new Exception(String.format("Must specify %s/description", + throw new Exception(String.format("Must specify %s/@description", EXTENSION_POINT_TEMPLATE)); } if (content == null || content.length() == 0) { - throw new Exception(String.format("Must specify %s/content", + throw new Exception(String.format("Must specify %s/@content", EXTENSION_POINT_TEMPLATE)); } content = content.replace("\\r\\n", Text.DELIMITER).replace("\\r", Text.DELIMITER).replace("\\n", Text.DELIMITER).replace("\\\\", "\\"); if (content.endsWith("$") && !(content.endsWith("\\$") || content.endsWith("$$"))) { content = content.substring(0, content.length() - 1); } content = content.replace("\\$", "$$"); markupLanguageTemplates.addTemplate(new Template(name, description, MarkupTemplateCompletionProcessor.CONTEXT_ID, content, autoInsert == null || !"false".equalsIgnoreCase(autoInsert)), block != null && "true".equalsIgnoreCase(block)); } catch (Exception e) { log(IStatus.ERROR, String.format("Plugin '%s' extension '%s' invalid: %s", declaringPluginId, EXTENSION_POINT_CONTENT_ASSIST, e.getMessage()), e); } } else { log(IStatus.ERROR, String.format( "Plugin '%s' extension '%s' unexpected element: %s", declaringPluginId, EXTENSION_POINT_CONTENT_ASSIST, templatesChild.getName()), null); } } Templates previous = templates.put(markupLanguageTemplates.getMarkupLanguageName(), markupLanguageTemplates); if (previous != null) { markupLanguageTemplates.addAll(previous); } } catch (Exception e) { log(IStatus.ERROR, String.format("Plugin '%s' extension '%s' invalid: %s", declaringPluginId, EXTENSION_POINT_TEMPLATES, e.getMessage()), e); } } else { log(IStatus.ERROR, String.format("Plugin '%s' extension '%s' unexpected element: %s", declaringPluginId, EXTENSION_POINT_CONTENT_ASSIST, element.getName()), null); } } } // now that we have the basic templates, check for language extensions and connect the hierarchy // first ensure that all language names have templates defined Set<String> languageNames = WikiTextPlugin.getDefault().getMarkupLanguageNames(); for (String languageName : languageNames) { Templates languageTemplates = templates.get(languageName); if (languageTemplates == null) { languageTemplates = new Templates(); templates.put(languageName, languageTemplates); } } // next connect the hierarchy for (String languageName : languageNames) { MarkupLanguage markupLanguage = WikiTextPlugin.getDefault().getMarkupLanguage(languageName); if (markupLanguage != null && markupLanguage.getExtendsLanguage() != null) { Templates languageTemplates = templates.get(languageName); Templates parentLanguageTemplates = templates.get(markupLanguage.getExtendsLanguage()); languageTemplates.setParent(parentLanguageTemplates); } } this.templates = Collections.unmodifiableMap(templates); } return templates; } }
false
true
public Map<String, Templates> getTemplates() { if (templates == null) { Map<String, Templates> templates = new HashMap<String, Templates>(); IExtensionPoint extensionPoint = Platform.getExtensionRegistry().getExtensionPoint(getPluginId(), EXTENSION_POINT_CONTENT_ASSIST); if (extensionPoint != null) { IConfigurationElement[] configurationElements = extensionPoint.getConfigurationElements(); for (IConfigurationElement element : configurationElements) { String declaringPluginId = element.getDeclaringExtension().getContributor().getName(); if (EXTENSION_POINT_TEMPLATES.equals(element.getName())) { try { String markupLanguage = element.getAttribute("markupLanguage"); if (markupLanguage == null) { throw new Exception("Must specify markupLanguage"); } else if (!WikiTextPlugin.getDefault().getMarkupLanguageNames().contains(markupLanguage)) { throw new Exception(String.format("'%s' is not a valid markupLanguage", markupLanguage)); } Templates markupLanguageTemplates = new Templates(); markupLanguageTemplates.setMarkupLanguageName(markupLanguage); for (IConfigurationElement templatesChild : element.getChildren()) { if (EXTENSION_POINT_TEMPLATE.equals(templatesChild.getName())) { try { // process the template String name = templatesChild.getAttribute("name"); String description = templatesChild.getAttribute("description"); String content = templatesChild.getAttribute("content"); String autoInsert = templatesChild.getAttribute("autoInsert"); String block = templatesChild.getAttribute("block"); if (name == null || name.length() == 0) { throw new Exception(String.format("Must specify %s/name", EXTENSION_POINT_TEMPLATE)); } if (description == null || description.length() == 0) { throw new Exception(String.format("Must specify %s/description", EXTENSION_POINT_TEMPLATE)); } if (content == null || content.length() == 0) { throw new Exception(String.format("Must specify %s/content", EXTENSION_POINT_TEMPLATE)); } content = content.replace("\\r\\n", Text.DELIMITER).replace("\\r", Text.DELIMITER).replace("\\n", Text.DELIMITER).replace("\\\\", "\\"); if (content.endsWith("$") && !(content.endsWith("\\$") || content.endsWith("$$"))) { content = content.substring(0, content.length() - 1); } content = content.replace("\\$", "$$"); markupLanguageTemplates.addTemplate(new Template(name, description, MarkupTemplateCompletionProcessor.CONTEXT_ID, content, autoInsert == null || !"false".equalsIgnoreCase(autoInsert)), block != null && "true".equalsIgnoreCase(block)); } catch (Exception e) { log(IStatus.ERROR, String.format("Plugin '%s' extension '%s' invalid: %s", declaringPluginId, EXTENSION_POINT_CONTENT_ASSIST, e.getMessage()), e); } } else { log(IStatus.ERROR, String.format( "Plugin '%s' extension '%s' unexpected element: %s", declaringPluginId, EXTENSION_POINT_CONTENT_ASSIST, templatesChild.getName()), null); } } Templates previous = templates.put(markupLanguageTemplates.getMarkupLanguageName(), markupLanguageTemplates); if (previous != null) { markupLanguageTemplates.addAll(previous); } } catch (Exception e) { log(IStatus.ERROR, String.format("Plugin '%s' extension '%s' invalid: %s", declaringPluginId, EXTENSION_POINT_TEMPLATES, e.getMessage()), e); } } else { log(IStatus.ERROR, String.format("Plugin '%s' extension '%s' unexpected element: %s", declaringPluginId, EXTENSION_POINT_CONTENT_ASSIST, element.getName()), null); } } } // now that we have the basic templates, check for language extensions and connect the hierarchy // first ensure that all language names have templates defined Set<String> languageNames = WikiTextPlugin.getDefault().getMarkupLanguageNames(); for (String languageName : languageNames) { Templates languageTemplates = templates.get(languageName); if (languageTemplates == null) { languageTemplates = new Templates(); templates.put(languageName, languageTemplates); } } // next connect the hierarchy for (String languageName : languageNames) { MarkupLanguage markupLanguage = WikiTextPlugin.getDefault().getMarkupLanguage(languageName); if (markupLanguage != null && markupLanguage.getExtendsLanguage() != null) { Templates languageTemplates = templates.get(languageName); Templates parentLanguageTemplates = templates.get(markupLanguage.getExtendsLanguage()); languageTemplates.setParent(parentLanguageTemplates); } } this.templates = Collections.unmodifiableMap(templates); } return templates; }
public Map<String, Templates> getTemplates() { if (templates == null) { Map<String, Templates> templates = new HashMap<String, Templates>(); IExtensionPoint extensionPoint = Platform.getExtensionRegistry().getExtensionPoint(getPluginId(), EXTENSION_POINT_CONTENT_ASSIST); if (extensionPoint != null) { IConfigurationElement[] configurationElements = extensionPoint.getConfigurationElements(); for (IConfigurationElement element : configurationElements) { String declaringPluginId = element.getDeclaringExtension().getContributor().getName(); if (EXTENSION_POINT_TEMPLATES.equals(element.getName())) { try { String markupLanguage = element.getAttribute("markupLanguage"); if (markupLanguage == null) { throw new Exception("Must specify markupLanguage"); } else if (!WikiTextPlugin.getDefault().getMarkupLanguageNames().contains(markupLanguage)) { throw new Exception(String.format("'%s' is not a valid markupLanguage", markupLanguage)); } Templates markupLanguageTemplates = new Templates(); markupLanguageTemplates.setMarkupLanguageName(markupLanguage); for (IConfigurationElement templatesChild : element.getChildren()) { if (EXTENSION_POINT_TEMPLATE.equals(templatesChild.getName())) { try { // process the template String name = templatesChild.getAttribute("name"); String description = templatesChild.getAttribute("description"); String content = templatesChild.getAttribute("content"); String autoInsert = templatesChild.getAttribute("autoInsert"); String block = templatesChild.getAttribute("block"); if (name == null || name.length() == 0) { throw new Exception(String.format("Must specify %s/@name", EXTENSION_POINT_TEMPLATE)); } if (description == null || description.length() == 0) { throw new Exception(String.format("Must specify %s/@description", EXTENSION_POINT_TEMPLATE)); } if (content == null || content.length() == 0) { throw new Exception(String.format("Must specify %s/@content", EXTENSION_POINT_TEMPLATE)); } content = content.replace("\\r\\n", Text.DELIMITER).replace("\\r", Text.DELIMITER).replace("\\n", Text.DELIMITER).replace("\\\\", "\\"); if (content.endsWith("$") && !(content.endsWith("\\$") || content.endsWith("$$"))) { content = content.substring(0, content.length() - 1); } content = content.replace("\\$", "$$"); markupLanguageTemplates.addTemplate(new Template(name, description, MarkupTemplateCompletionProcessor.CONTEXT_ID, content, autoInsert == null || !"false".equalsIgnoreCase(autoInsert)), block != null && "true".equalsIgnoreCase(block)); } catch (Exception e) { log(IStatus.ERROR, String.format("Plugin '%s' extension '%s' invalid: %s", declaringPluginId, EXTENSION_POINT_CONTENT_ASSIST, e.getMessage()), e); } } else { log(IStatus.ERROR, String.format( "Plugin '%s' extension '%s' unexpected element: %s", declaringPluginId, EXTENSION_POINT_CONTENT_ASSIST, templatesChild.getName()), null); } } Templates previous = templates.put(markupLanguageTemplates.getMarkupLanguageName(), markupLanguageTemplates); if (previous != null) { markupLanguageTemplates.addAll(previous); } } catch (Exception e) { log(IStatus.ERROR, String.format("Plugin '%s' extension '%s' invalid: %s", declaringPluginId, EXTENSION_POINT_TEMPLATES, e.getMessage()), e); } } else { log(IStatus.ERROR, String.format("Plugin '%s' extension '%s' unexpected element: %s", declaringPluginId, EXTENSION_POINT_CONTENT_ASSIST, element.getName()), null); } } } // now that we have the basic templates, check for language extensions and connect the hierarchy // first ensure that all language names have templates defined Set<String> languageNames = WikiTextPlugin.getDefault().getMarkupLanguageNames(); for (String languageName : languageNames) { Templates languageTemplates = templates.get(languageName); if (languageTemplates == null) { languageTemplates = new Templates(); templates.put(languageName, languageTemplates); } } // next connect the hierarchy for (String languageName : languageNames) { MarkupLanguage markupLanguage = WikiTextPlugin.getDefault().getMarkupLanguage(languageName); if (markupLanguage != null && markupLanguage.getExtendsLanguage() != null) { Templates languageTemplates = templates.get(languageName); Templates parentLanguageTemplates = templates.get(markupLanguage.getExtendsLanguage()); languageTemplates.setParent(parentLanguageTemplates); } } this.templates = Collections.unmodifiableMap(templates); } return templates; }
diff --git a/src/com/hyperactivity/android_app/activities/MainActivity.java b/src/com/hyperactivity/android_app/activities/MainActivity.java index 468fead..dcaadc2 100644 --- a/src/com/hyperactivity/android_app/activities/MainActivity.java +++ b/src/com/hyperactivity/android_app/activities/MainActivity.java @@ -1,86 +1,86 @@ package com.hyperactivity.android_app.activities; import java.util.ArrayList; import android.annotation.TargetApi; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import com.hyperactivity.android_app.R; import com.hyperactivity.android_app.core.ScrollPicker; import com.hyperactivity.android_app.forum.ForumThread; public class MainActivity extends FragmentActivity { private ScrollPicker scrollPicker; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); View view = findViewById(R.id.forum_categories_surface_view); scrollPicker = (ScrollPicker) view; scrollPicker.getThread().setState( ScrollPicker.ScrollPickerThread.STATE_READY); BitmapFactory.Options options = new BitmapFactory.Options(); options.inScaled = false; options.inDither = false; options.inPreferredConfig = Bitmap.Config.ARGB_8888; scrollPicker.getItemManager().addItem(BitmapFactory.decodeResource(getResources(), R.drawable.c_contact, options), "Kontakt", Color.BLACK); scrollPicker.getItemManager().addItem(BitmapFactory.decodeResource(getResources(), R.drawable.c_creativity, options), "Krativitet", Color.BLACK); scrollPicker.getItemManager().addItem(BitmapFactory.decodeResource(getResources(), R.drawable.c_general, options), "Generellt", Color.BLACK, true); scrollPicker.getItemManager().addItem(BitmapFactory.decodeResource(getResources(), R.drawable.c_hobby, options), "Hobby", Color.BLACK); scrollPicker.getItemManager().addItem(BitmapFactory.decodeResource(getResources(), R.drawable.c_medicine, options), "Medicin", Color.BLACK); scrollPicker.getItemManager().addItem(BitmapFactory.decodeResource(getResources(), R.drawable.c_school, options), "Skola", Color.BLACK); scrollPicker.getItemManager().addItem(BitmapFactory.decodeResource(getResources(), R.drawable.c_tips, options), "Tips", Color.BLACK); - scrollPicker.getItemManager().recalculateItems(); + //scrollPicker.getItemManager().recalculateItems(); // MAKES PROGRAM CRASH ArrayList<ForumThread> forumList = new ArrayList<ForumThread>(); forumList.add(new ForumThread(null, "test1", "test12")); forumList.add(new ForumThread(null, "test2", "test22")); forumList.add(new ForumThread(null, "test3", "test32")); ThreadListFragment threadListFragment = (ThreadListFragment) getSupportFragmentManager().findFragmentById(R.id.thread_list); threadListFragment.updateThreadList(forumList); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } /** * Triggers when an item in the menu is clicked such as "Settings" or "Help" */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_settings: // Settings has been clicked, check the android version to decide if // to use fragmented settings or not if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { startActivity(new Intent(this, SettingsActivity.class)); } else { startActivity(new Intent(this, SettingsActivityHoneycomb.class)); } return true; default: return super.onOptionsItemSelected(item); } } }
true
true
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); View view = findViewById(R.id.forum_categories_surface_view); scrollPicker = (ScrollPicker) view; scrollPicker.getThread().setState( ScrollPicker.ScrollPickerThread.STATE_READY); BitmapFactory.Options options = new BitmapFactory.Options(); options.inScaled = false; options.inDither = false; options.inPreferredConfig = Bitmap.Config.ARGB_8888; scrollPicker.getItemManager().addItem(BitmapFactory.decodeResource(getResources(), R.drawable.c_contact, options), "Kontakt", Color.BLACK); scrollPicker.getItemManager().addItem(BitmapFactory.decodeResource(getResources(), R.drawable.c_creativity, options), "Krativitet", Color.BLACK); scrollPicker.getItemManager().addItem(BitmapFactory.decodeResource(getResources(), R.drawable.c_general, options), "Generellt", Color.BLACK, true); scrollPicker.getItemManager().addItem(BitmapFactory.decodeResource(getResources(), R.drawable.c_hobby, options), "Hobby", Color.BLACK); scrollPicker.getItemManager().addItem(BitmapFactory.decodeResource(getResources(), R.drawable.c_medicine, options), "Medicin", Color.BLACK); scrollPicker.getItemManager().addItem(BitmapFactory.decodeResource(getResources(), R.drawable.c_school, options), "Skola", Color.BLACK); scrollPicker.getItemManager().addItem(BitmapFactory.decodeResource(getResources(), R.drawable.c_tips, options), "Tips", Color.BLACK); scrollPicker.getItemManager().recalculateItems(); ArrayList<ForumThread> forumList = new ArrayList<ForumThread>(); forumList.add(new ForumThread(null, "test1", "test12")); forumList.add(new ForumThread(null, "test2", "test22")); forumList.add(new ForumThread(null, "test3", "test32")); ThreadListFragment threadListFragment = (ThreadListFragment) getSupportFragmentManager().findFragmentById(R.id.thread_list); threadListFragment.updateThreadList(forumList); }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); View view = findViewById(R.id.forum_categories_surface_view); scrollPicker = (ScrollPicker) view; scrollPicker.getThread().setState( ScrollPicker.ScrollPickerThread.STATE_READY); BitmapFactory.Options options = new BitmapFactory.Options(); options.inScaled = false; options.inDither = false; options.inPreferredConfig = Bitmap.Config.ARGB_8888; scrollPicker.getItemManager().addItem(BitmapFactory.decodeResource(getResources(), R.drawable.c_contact, options), "Kontakt", Color.BLACK); scrollPicker.getItemManager().addItem(BitmapFactory.decodeResource(getResources(), R.drawable.c_creativity, options), "Krativitet", Color.BLACK); scrollPicker.getItemManager().addItem(BitmapFactory.decodeResource(getResources(), R.drawable.c_general, options), "Generellt", Color.BLACK, true); scrollPicker.getItemManager().addItem(BitmapFactory.decodeResource(getResources(), R.drawable.c_hobby, options), "Hobby", Color.BLACK); scrollPicker.getItemManager().addItem(BitmapFactory.decodeResource(getResources(), R.drawable.c_medicine, options), "Medicin", Color.BLACK); scrollPicker.getItemManager().addItem(BitmapFactory.decodeResource(getResources(), R.drawable.c_school, options), "Skola", Color.BLACK); scrollPicker.getItemManager().addItem(BitmapFactory.decodeResource(getResources(), R.drawable.c_tips, options), "Tips", Color.BLACK); //scrollPicker.getItemManager().recalculateItems(); // MAKES PROGRAM CRASH ArrayList<ForumThread> forumList = new ArrayList<ForumThread>(); forumList.add(new ForumThread(null, "test1", "test12")); forumList.add(new ForumThread(null, "test2", "test22")); forumList.add(new ForumThread(null, "test3", "test32")); ThreadListFragment threadListFragment = (ThreadListFragment) getSupportFragmentManager().findFragmentById(R.id.thread_list); threadListFragment.updateThreadList(forumList); }
diff --git a/src/main/java/ee/ignorance/transformiceapi/event/EventService.java b/src/main/java/ee/ignorance/transformiceapi/event/EventService.java index 6da62fb..6c0ddf1 100644 --- a/src/main/java/ee/ignorance/transformiceapi/event/EventService.java +++ b/src/main/java/ee/ignorance/transformiceapi/event/EventService.java @@ -1,30 +1,30 @@ package ee.ignorance.transformiceapi.event; import java.util.ArrayList; import java.util.List; public class EventService { private List<EventListener> listeners; public EventService() { listeners = new ArrayList<EventListener>(); } public void registerEventListener(EventListener listener) { listeners.add(listener); } public void unregisterEventListener(EventListener listener) { listeners.remove(listener); } - public void notifyListeners(Event e) { + public synchronized void notifyListeners(Event e) { for (EventListener listener : listeners) { if (listener.matches(e)) { listener.actionPerformed(e); } } } }
true
true
public void notifyListeners(Event e) { for (EventListener listener : listeners) { if (listener.matches(e)) { listener.actionPerformed(e); } } }
public synchronized void notifyListeners(Event e) { for (EventListener listener : listeners) { if (listener.matches(e)) { listener.actionPerformed(e); } } }
diff --git a/src/com/android/mms/data/Contact.java b/src/com/android/mms/data/Contact.java index f1c6bc1..2d725f0 100644 --- a/src/com/android/mms/data/Contact.java +++ b/src/com/android/mms/data/Contact.java @@ -1,488 +1,490 @@ package com.android.mms.data; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import android.content.ContentUris; import android.content.Context; import android.database.ContentObserver; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Handler; import android.provider.ContactsContract.Contacts; import android.provider.ContactsContract.Presence; import android.provider.Telephony.Mms; import android.telephony.PhoneNumberUtils; import android.text.TextUtils; import android.util.Log; import com.android.mms.ui.MessageUtils; import com.android.mms.util.ContactInfoCache; import com.android.mms.util.TaskStack; import com.android.mms.LogTag; public class Contact { private static final String TAG = "Contact"; private static final boolean V = false; private static final TaskStack sTaskStack = new TaskStack(); // private static final ContentObserver sContactsObserver = new ContentObserver(new Handler()) { // @Override // public void onChange(boolean selfUpdate) { // if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { // log("contact changed, invalidate cache"); // } // invalidateCache(); // } // }; private static final ContentObserver sPresenceObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfUpdate) { if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log("presence changed, invalidate cache"); } invalidateCache(); } }; private final HashSet<UpdateListener> mListeners = new HashSet<UpdateListener>(); private String mNumber; private String mName; private String mNameAndNumber; // for display, e.g. Fred Flintstone <670-782-1123> private boolean mNumberIsModified; // true if the number is modified private long mRecipientId; // used to find the Recipient cache entry private String mLabel; private long mPersonId; private int mPresenceResId; // TODO: make this a state instead of a res ID private String mPresenceText; private BitmapDrawable mAvatar; private boolean mIsStale; @Override public synchronized String toString() { return String.format("{ number=%s, name=%s, nameAndNumber=%s, label=%s, person_id=%d }", mNumber, mName, mNameAndNumber, mLabel, mPersonId); } public interface UpdateListener { public void onUpdate(Contact updated); } private Contact(String number) { mName = ""; setNumber(number); mNumberIsModified = false; mLabel = ""; mPersonId = 0; mPresenceResId = 0; mIsStale = true; } private static void logWithTrace(String msg, Object... format) { Thread current = Thread.currentThread(); StackTraceElement[] stack = current.getStackTrace(); StringBuilder sb = new StringBuilder(); sb.append("["); sb.append(current.getId()); sb.append("] "); sb.append(String.format(msg, format)); sb.append(" <- "); int stop = stack.length > 7 ? 7 : stack.length; for (int i = 3; i < stop; i++) { String methodName = stack[i].getMethodName(); sb.append(methodName); if ((i+1) != stop) { sb.append(" <- "); } } Log.d(TAG, sb.toString()); } public static Contact get(String number, boolean canBlock) { if (V) logWithTrace("get(%s, %s)", number, canBlock); if (TextUtils.isEmpty(number)) { throw new IllegalArgumentException("Contact.get called with null or empty number"); } Contact contact = Cache.get(number); if (contact == null) { contact = new Contact(number); Cache.put(contact); } if (contact.mIsStale) { asyncUpdateContact(contact, canBlock); } return contact; } public static void invalidateCache() { if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log("invalidateCache"); } // force invalidate the contact info cache, so we will query for fresh info again. // This is so we can get fresh presence info again on the screen, since the presence // info changes pretty quickly, and we can't get change notifications when presence is // updated in the ContactsProvider. ContactInfoCache.getInstance().invalidateCache(); // While invalidating our local Cache doesn't remove the contacts, it will mark them // stale so the next time we're asked for a particular contact, we'll return that // stale contact and at the same time, fire off an asyncUpdateContact to update // that contact's info in the background. UI elements using the contact typically // call addListener() so they immediately get notified when the contact has been // updated with the latest info. They redraw themselves when we call the // listener's onUpdate(). Cache.invalidate(); } private static String emptyIfNull(String s) { return (s != null ? s : ""); } private static boolean contactChanged(Contact orig, ContactInfoCache.CacheEntry newEntry) { // The phone number should never change, so don't bother checking. // TODO: Maybe update it if it has gotten longer, i.e. 650-234-5678 -> +16502345678? String oldName = emptyIfNull(orig.mName); String newName = emptyIfNull(newEntry.name); if (!oldName.equals(newName)) { if (V) Log.d(TAG, String.format("name changed: %s -> %s", oldName, newName)); return true; } String oldLabel = emptyIfNull(orig.mLabel); String newLabel = emptyIfNull(newEntry.phoneLabel); if (!oldLabel.equals(newLabel)) { if (V) Log.d(TAG, String.format("label changed: %s -> %s", oldLabel, newLabel)); return true; } if (orig.mPersonId != newEntry.person_id) { if (V) Log.d(TAG, "person id changed"); return true; } if (orig.mPresenceResId != newEntry.presenceResId) { if (V) Log.d(TAG, "presence changed"); return true; } return false; } /** * Handles the special case where the local ("Me") number is being looked up. * Updates the contact with the "me" name and returns true if it is the * local number, no-ops and returns false if it is not. */ private static boolean handleLocalNumber(Contact c) { if (MessageUtils.isLocalNumber(c.mNumber)) { c.mName = Cache.getContext().getString(com.android.internal.R.string.me); c.updateNameAndNumber(); return true; } return false; } private static void asyncUpdateContact(final Contact c, boolean canBlock) { if (c == null) { return; } if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log("asyncUpdateContact for " + c.toString() + " canBlock: " + canBlock + " isStale: " + c.mIsStale); } Runnable r = new Runnable() { public void run() { updateContact(c); } }; if (canBlock) { r.run(); } else { sTaskStack.push(r); } } private static void updateContact(final Contact c) { if (c == null) { return; } ContactInfoCache cache = ContactInfoCache.getInstance(); ContactInfoCache.CacheEntry entry = cache.getContactInfo(c.mNumber); synchronized (Cache.getInstance()) { if (contactChanged(c, entry)) { if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log("updateContact: contact changed for " + entry.name); } //c.mNumber = entry.phoneNumber; c.mName = entry.name; c.updateNameAndNumber(); c.mLabel = entry.phoneLabel; c.mPersonId = entry.person_id; c.mPresenceResId = entry.presenceResId; c.mPresenceText = entry.presenceText; c.mAvatar = entry.mAvatar; c.mIsStale = false; // Check to see if this is the local ("me") number and update the name. handleLocalNumber(c); for (UpdateListener l : c.mListeners) { if (V) Log.d(TAG, "updating " + l); l.onUpdate(c); } + } else { + c.mIsStale = false; } } } public static String formatNameAndNumber(String name, String number) { // Format like this: Mike Cleron <(650) 555-1234> // Erick Tseng <(650) 555-1212> // Tutankhamun <[email protected]> // (408) 555-1289 String formattedNumber = number; if (!Mms.isEmailAddress(number)) { formattedNumber = PhoneNumberUtils.formatNumber(number); } if (!TextUtils.isEmpty(name) && !name.equals(number)) { return name + " <" + formattedNumber + ">"; } else { return formattedNumber; } } public synchronized String getNumber() { return mNumber; } public synchronized void setNumber(String number) { mNumber = number; updateNameAndNumber(); mNumberIsModified = true; } public boolean isNumberModified() { return mNumberIsModified; } public void setIsNumberModified(boolean flag) { mNumberIsModified = flag; } public synchronized String getName() { if (TextUtils.isEmpty(mName)) { return mNumber; } else { return mName; } } public synchronized String getNameAndNumber() { return mNameAndNumber; } private void updateNameAndNumber() { mNameAndNumber = formatNameAndNumber(mName, mNumber); } public synchronized long getRecipientId() { return mRecipientId; } public synchronized void setRecipientId(long id) { mRecipientId = id; } public synchronized String getLabel() { return mLabel; } public synchronized Uri getUri() { return ContentUris.withAppendedId(Contacts.CONTENT_URI, mPersonId); } public long getPersonId() { return mPersonId; } public synchronized int getPresenceResId() { return mPresenceResId; } public synchronized boolean existsInDatabase() { return (mPersonId > 0); } public synchronized void addListener(UpdateListener l) { boolean added = mListeners.add(l); if (V && added) dumpListeners(); } public synchronized void removeListener(UpdateListener l) { boolean removed = mListeners.remove(l); if (V && removed) dumpListeners(); } public synchronized void dumpListeners() { int i=0; Log.i(TAG, "[Contact] dumpListeners(" + mNumber + ") size=" + mListeners.size()); for (UpdateListener listener : mListeners) { Log.i(TAG, "["+ (i++) + "]" + listener); } } public synchronized boolean isEmail() { return Mms.isEmailAddress(mNumber); } public String getPresenceText() { return mPresenceText; } public Drawable getAvatar(Drawable defaultValue) { return mAvatar != null ? mAvatar : defaultValue; } public static void init(final Context context) { Cache.init(context); RecipientIdCache.init(context); // it maybe too aggressive to listen for *any* contact changes, and rebuild MMS contact // cache each time that occurs. Unless we can get targeted updates for the contacts we // care about(which probably won't happen for a long time), we probably should just // invalidate cache peoridically, or surgically. /* context.getContentResolver().registerContentObserver( Contacts.CONTENT_URI, true, sContactsObserver); */ } public static void dump() { Cache.dump(); } public static void startPresenceObserver() { Cache.getContext().getContentResolver().registerContentObserver( Presence.CONTENT_URI, true, sPresenceObserver); } public static void stopPresenceObserver() { Cache.getContext().getContentResolver().unregisterContentObserver(sPresenceObserver); } private static class Cache { private static Cache sInstance; static Cache getInstance() { return sInstance; } private final List<Contact> mCache; private final Context mContext; private Cache(Context context) { mCache = new ArrayList<Contact>(); mContext = context; } static void init(Context context) { sInstance = new Cache(context); } static Context getContext() { return sInstance.mContext; } static void dump() { synchronized (sInstance) { Log.d(TAG, "**** Contact cache dump ****"); for (Contact c : sInstance.mCache) { Log.d(TAG, c.toString()); } } } private static Contact getEmail(String number) { synchronized (sInstance) { for (Contact c : sInstance.mCache) { if (number.equalsIgnoreCase(c.mNumber)) { return c; } } return null; } } static Contact get(String number) { if (Mms.isEmailAddress(number)) return getEmail(number); synchronized (sInstance) { for (Contact c : sInstance.mCache) { // if the numbers are an exact match (i.e. Google SMS), or if the phone // number comparison returns a match, return the contact. if (number.equals(c.mNumber) || PhoneNumberUtils.compare(number, c.mNumber)) { return c; } } return null; } } static void put(Contact c) { synchronized (sInstance) { // We update cache entries in place so people with long- // held references get updated. if (get(c.mNumber) != null) { throw new IllegalStateException("cache already contains " + c); } sInstance.mCache.add(c); } } static String[] getNumbers() { synchronized (sInstance) { String[] numbers = new String[sInstance.mCache.size()]; int i = 0; for (Contact c : sInstance.mCache) { numbers[i++] = c.getNumber(); } return numbers; } } static List<Contact> getContacts() { synchronized (sInstance) { return new ArrayList<Contact>(sInstance.mCache); } } static void invalidate() { // Don't remove the contacts. Just mark them stale so we'll update their // info, particularly their presence. synchronized (sInstance) { for (Contact c : sInstance.mCache) { c.mIsStale = true; } } } } private static void log(String msg) { Log.d(TAG, msg); } }
true
true
private static void updateContact(final Contact c) { if (c == null) { return; } ContactInfoCache cache = ContactInfoCache.getInstance(); ContactInfoCache.CacheEntry entry = cache.getContactInfo(c.mNumber); synchronized (Cache.getInstance()) { if (contactChanged(c, entry)) { if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log("updateContact: contact changed for " + entry.name); } //c.mNumber = entry.phoneNumber; c.mName = entry.name; c.updateNameAndNumber(); c.mLabel = entry.phoneLabel; c.mPersonId = entry.person_id; c.mPresenceResId = entry.presenceResId; c.mPresenceText = entry.presenceText; c.mAvatar = entry.mAvatar; c.mIsStale = false; // Check to see if this is the local ("me") number and update the name. handleLocalNumber(c); for (UpdateListener l : c.mListeners) { if (V) Log.d(TAG, "updating " + l); l.onUpdate(c); } } } }
private static void updateContact(final Contact c) { if (c == null) { return; } ContactInfoCache cache = ContactInfoCache.getInstance(); ContactInfoCache.CacheEntry entry = cache.getContactInfo(c.mNumber); synchronized (Cache.getInstance()) { if (contactChanged(c, entry)) { if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log("updateContact: contact changed for " + entry.name); } //c.mNumber = entry.phoneNumber; c.mName = entry.name; c.updateNameAndNumber(); c.mLabel = entry.phoneLabel; c.mPersonId = entry.person_id; c.mPresenceResId = entry.presenceResId; c.mPresenceText = entry.presenceText; c.mAvatar = entry.mAvatar; c.mIsStale = false; // Check to see if this is the local ("me") number and update the name. handleLocalNumber(c); for (UpdateListener l : c.mListeners) { if (V) Log.d(TAG, "updating " + l); l.onUpdate(c); } } else { c.mIsStale = false; } } }
diff --git a/ace/component/src/org/icefaces/ace/component/datetimeentry/DateTimeEntryRenderer.java b/ace/component/src/org/icefaces/ace/component/datetimeentry/DateTimeEntryRenderer.java index c5553bdb9..51a0b0532 100644 --- a/ace/component/src/org/icefaces/ace/component/datetimeentry/DateTimeEntryRenderer.java +++ b/ace/component/src/org/icefaces/ace/component/datetimeentry/DateTimeEntryRenderer.java @@ -1,295 +1,295 @@ /* * Original Code Copyright Prime Technology. * Subsequent Code Modifications Copyright 2011-2012 ICEsoft Technologies Canada Corp. (c) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * NOTE THIS CODE HAS BEEN MODIFIED FROM ORIGINAL FORM * * Subsequent Code Modifications have been made and contributed by ICEsoft Technologies Canada Corp. (c). * * Code Modification 1: Integrated with ICEfaces Advanced Component Environment. * Contributors: ICEsoft Technologies Canada Corp. (c) * * Code Modification 2: (ICE-6978) Used JSONBuilder to add the functionality of escaping JS output. * Contributors: ICEsoft Technologies Canada Corp. (c) * Contributors: ______________________ */ package org.icefaces.ace.component.datetimeentry; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Iterator; import java.util.Locale; import java.util.Map; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import javax.faces.convert.Converter; import javax.faces.convert.ConverterException; import org.icefaces.ace.renderkit.InputRenderer; import org.icefaces.ace.util.HTML; import org.icefaces.ace.util.JSONBuilder; import org.icefaces.render.MandatoryResourceComponent; @MandatoryResourceComponent(tagName="dateTimeEntry", value="org.icefaces.ace.component.datetimeentry.DateTimeEntry") public class DateTimeEntryRenderer extends InputRenderer { @Override public void decode(FacesContext context, UIComponent component) { // printParams(); DateTimeEntry dateTimeEntry = (DateTimeEntry) component; if(dateTimeEntry.isDisabled() || dateTimeEntry.isReadonly()) { return; } String clientId = dateTimeEntry.getClientId(context); Map<String, String> parameterMap = context.getExternalContext().getRequestParameterMap(); String submittedValue = parameterMap.get(clientId + "_input"); if (submittedValue == null && parameterMap.get(clientId + "_label") != null) { submittedValue = ""; } if(submittedValue != null) { dateTimeEntry.setSubmittedValue(submittedValue); } decodeBehaviors(context, dateTimeEntry); } @Override public void encodeEnd(FacesContext context, UIComponent component) throws IOException { DateTimeEntry dateTimeEntry = (DateTimeEntry) component; String value = DateTimeEntryUtils.getValueAsString(context, dateTimeEntry); Map<String, Object> labelAttributes = getLabelAttributes(component); encodeMarkup(context, dateTimeEntry, value, labelAttributes); } protected void encodeMarkup(FacesContext context, DateTimeEntry dateTimeEntry, String value, Map<String, Object> labelAttributes) throws IOException { ResponseWriter writer = context.getResponseWriter(); String clientId = dateTimeEntry.getClientId(context); String inputId = clientId + "_input"; boolean popup = dateTimeEntry.isPopup(); Map paramMap = context.getExternalContext().getRequestParameterMap(); String iceFocus = (String) paramMap.get("ice.focus"); writer.startElement("span", dateTimeEntry); writer.writeAttribute("id", clientId, null); String style = dateTimeEntry.getStyle(); if(style != null) writer.writeAttribute("style", style, null); String styleClass = dateTimeEntry.getStyleClass(); if(styleClass != null) writer.writeAttribute("class", styleClass, null); //inline container if(!popup) { writer.startElement("div", null); writer.writeAttribute("id", clientId + "_inline", null); writer.endElement("div"); } //input String type = popup ? "text" : "hidden"; if (popup) { writeLabelAndIndicatorBefore(labelAttributes); } writer.startElement("input", null); writer.writeAttribute("id", inputId, null); writer.writeAttribute("name", inputId, null); writer.writeAttribute("type", type, null); writer.writeAttribute("tabindex", dateTimeEntry.getTabindex(), null); String styleClasses = (themeForms() ? DateTimeEntry.INPUT_STYLE_CLASS : "") + getStateStyleClasses(dateTimeEntry); if(!isValueBlank(value)) { writer.writeAttribute("value", value, null); } else if (popup && !clientId.equals(iceFocus)) { String inFieldLabel = (String) labelAttributes.get("inFieldLabel"); if (!isValueBlank(inFieldLabel)) { writer.writeAttribute("name", clientId + "_label", null); writer.writeAttribute("value", inFieldLabel, null); styleClasses += " " + IN_FIELD_LABEL_STYLE_CLASS; labelAttributes.put("labelIsInField", true); } } if(popup) { if(!isValueBlank(styleClasses)) writer.writeAttribute("class", styleClasses, null); if(dateTimeEntry.isReadOnlyInputText()) writer.writeAttribute("readonly", "readonly", null); if(dateTimeEntry.isDisabled()) writer.writeAttribute("disabled", "disabled", null); int size = dateTimeEntry.getSize(); if (size <= 0) { String formattedDate; SimpleDateFormat dateFormat = new SimpleDateFormat(dateTimeEntry.getPattern(), dateTimeEntry.calculateLocale(context)); try { formattedDate = dateFormat.format(new SimpleDateFormat("yyy-M-d H:m:s:S z").parse("2012-12-21 20:12:12:212 MST")); } catch (ParseException e) { formattedDate = dateFormat.format(new Date()); } size = formattedDate.length(); } writer.writeAttribute("size", size, null); // renderPassThruAttributes(context, dateTimeEntry, HTML.INPUT_TEXT_ATTRS); } writer.endElement("input"); if (popup) { writeLabelAndIndicatorAfter(labelAttributes); } encodeScript(context, dateTimeEntry, value, labelAttributes); writer.endElement("span"); } protected void encodeScript(FacesContext context, DateTimeEntry dateTimeEntry, String value, Map<String, Object> labelAttributes) throws IOException { ResponseWriter writer = context.getResponseWriter(); String clientId = dateTimeEntry.getClientId(context); writer.startElement("script", null); writer.writeAttribute("type", "text/javascript", null); String showOn = dateTimeEntry.getShowOn(); boolean timeOnly = dateTimeEntry.isTimeOnly(); StringBuilder script = new StringBuilder(); JSONBuilder json = JSONBuilder.create(); script.append("ice.ace.jq(function(){").append(resolveWidgetVar(dateTimeEntry)).append(" = new "); json.beginFunction("ice.ace.Calendar"). item(clientId). beginMap(). entry("popup", dateTimeEntry.isPopup()). entry("locale", dateTimeEntry.calculateLocale(context).toString()); - if(!isValueBlank(value) && !timeOnly) json.entry("defaultDate", value); + if(!isValueBlank(value) && !timeOnly && dateTimeEntry.isValid()) json.entry("defaultDate", value); json.entryNonNullValue("pattern", DateTimeEntryUtils.convertPattern(dateTimeEntry.getPattern())); if(dateTimeEntry.getPages() != 1) json.entry("numberOfMonths", dateTimeEntry.getPages()); json.entryNonNullValue("minDate", DateTimeEntryUtils.getDateAsString(dateTimeEntry, dateTimeEntry.getMindate())). entryNonNullValue("maxDate", DateTimeEntryUtils.getDateAsString(dateTimeEntry, dateTimeEntry.getMaxdate())); json.entryNonNullValue("showButtonPanel", dateTimeEntry.isShowButtonPanel()); if(dateTimeEntry.isShowWeek()) json.entry("showWeek", true); if(dateTimeEntry.isDisabled()) json.entry("disabled", true); json.entryNonNullValue("yearRange", dateTimeEntry.getYearRange()); if(dateTimeEntry.isNavigator()) { json.entry("changeMonth", true). entry("changeYear", true); } if(dateTimeEntry.getEffect() != null) { json.entry("showAnim", dateTimeEntry.getEffect()). entry("duration", dateTimeEntry.getEffectDuration()); } if(!showOn.equalsIgnoreCase("focus")) { String iconSrc = dateTimeEntry.getPopupIcon() != null ? getResourceURL(context, dateTimeEntry.getPopupIcon()) : getResourceRequestPath(context, DateTimeEntry.POPUP_ICON); json.entry("showOn", showOn). entry("buttonImage", iconSrc). entry("buttonImageOnly", dateTimeEntry.isPopupIconOnly()); } if(dateTimeEntry.isShowOtherMonths()) { json.entry("showOtherMonths", true). entry("selectOtherMonths", dateTimeEntry.isSelectOtherMonths()); } //time if(dateTimeEntry.hasTime()) { json.entry("timeOnly", timeOnly). //step entry("stepHour", dateTimeEntry.getStepHour()). entry("stepMinute", dateTimeEntry.getStepMinute()). entry("stepSecond", dateTimeEntry.getStepSecond()). //minmax entry("hourMin", dateTimeEntry.getMinHour()). entry("hourMax", dateTimeEntry.getMaxHour()). entry("minuteMin", dateTimeEntry.getMinMinute()). entry("minuteMax", dateTimeEntry.getMaxMinute()). entry("secondMin", dateTimeEntry.getMinSecond()). entry("secondMax", dateTimeEntry.getMaxSecond()); } encodeClientBehaviors(context, dateTimeEntry, json); if(!themeForms()) { json.entry("theme", false); } json.entry("disableHoverStyling", dateTimeEntry.isDisableHoverStyling()); json.entry("showCurrentAtPos", 0 - dateTimeEntry.getLeftMonthOffset()); json.entry("clientId", clientId); json.entryNonNullValue("inFieldLabel", (String) labelAttributes.get("inFieldLabel")); json.entry("inFieldLabelStyleClass", IN_FIELD_LABEL_STYLE_CLASS); json.entry("labelIsInField", (Boolean) labelAttributes.get("labelIsInField")); json.endMap(); json.endFunction(); script.append(json.toString()).append("});"); // System.out.println(script); writer.write(script.toString()); writer.endElement("script"); } @Override public Object getConvertedValue(FacesContext context, UIComponent component, Object value) throws ConverterException { DateTimeEntry dateTimeEntry = (DateTimeEntry) component; String submittedValue = (String) value; Converter converter = dateTimeEntry.getConverter(); if(isValueBlank(submittedValue)) { return null; } //Delegate to user supplied converter if defined if(converter != null) { return converter.getAsObject(context, dateTimeEntry, submittedValue); } //Use built-in converter try { Date convertedValue; Locale locale = dateTimeEntry.calculateLocale(context); SimpleDateFormat format = new SimpleDateFormat(dateTimeEntry.getPattern(), locale); format.setTimeZone(dateTimeEntry.calculateTimeZone()); convertedValue = format.parse(submittedValue); return convertedValue; } catch (ParseException e) { throw new ConverterException(e); } } public static void printParams() { Map<String, String[]> paramValuesMap = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterValuesMap(); String key; String[] values; for (Map.Entry<String, String[]> entry : paramValuesMap.entrySet()) { key = entry.getKey(); values = entry.getValue(); System.out.print(key); System.out.print(" = "); for (String value : values) { System.out.print(value); System.out.print(", "); } System.out.println(); } } }
true
true
protected void encodeScript(FacesContext context, DateTimeEntry dateTimeEntry, String value, Map<String, Object> labelAttributes) throws IOException { ResponseWriter writer = context.getResponseWriter(); String clientId = dateTimeEntry.getClientId(context); writer.startElement("script", null); writer.writeAttribute("type", "text/javascript", null); String showOn = dateTimeEntry.getShowOn(); boolean timeOnly = dateTimeEntry.isTimeOnly(); StringBuilder script = new StringBuilder(); JSONBuilder json = JSONBuilder.create(); script.append("ice.ace.jq(function(){").append(resolveWidgetVar(dateTimeEntry)).append(" = new "); json.beginFunction("ice.ace.Calendar"). item(clientId). beginMap(). entry("popup", dateTimeEntry.isPopup()). entry("locale", dateTimeEntry.calculateLocale(context).toString()); if(!isValueBlank(value) && !timeOnly) json.entry("defaultDate", value); json.entryNonNullValue("pattern", DateTimeEntryUtils.convertPattern(dateTimeEntry.getPattern())); if(dateTimeEntry.getPages() != 1) json.entry("numberOfMonths", dateTimeEntry.getPages()); json.entryNonNullValue("minDate", DateTimeEntryUtils.getDateAsString(dateTimeEntry, dateTimeEntry.getMindate())). entryNonNullValue("maxDate", DateTimeEntryUtils.getDateAsString(dateTimeEntry, dateTimeEntry.getMaxdate())); json.entryNonNullValue("showButtonPanel", dateTimeEntry.isShowButtonPanel()); if(dateTimeEntry.isShowWeek()) json.entry("showWeek", true); if(dateTimeEntry.isDisabled()) json.entry("disabled", true); json.entryNonNullValue("yearRange", dateTimeEntry.getYearRange()); if(dateTimeEntry.isNavigator()) { json.entry("changeMonth", true). entry("changeYear", true); } if(dateTimeEntry.getEffect() != null) { json.entry("showAnim", dateTimeEntry.getEffect()). entry("duration", dateTimeEntry.getEffectDuration()); } if(!showOn.equalsIgnoreCase("focus")) { String iconSrc = dateTimeEntry.getPopupIcon() != null ? getResourceURL(context, dateTimeEntry.getPopupIcon()) : getResourceRequestPath(context, DateTimeEntry.POPUP_ICON); json.entry("showOn", showOn). entry("buttonImage", iconSrc). entry("buttonImageOnly", dateTimeEntry.isPopupIconOnly()); } if(dateTimeEntry.isShowOtherMonths()) { json.entry("showOtherMonths", true). entry("selectOtherMonths", dateTimeEntry.isSelectOtherMonths()); } //time if(dateTimeEntry.hasTime()) { json.entry("timeOnly", timeOnly). //step entry("stepHour", dateTimeEntry.getStepHour()). entry("stepMinute", dateTimeEntry.getStepMinute()). entry("stepSecond", dateTimeEntry.getStepSecond()). //minmax entry("hourMin", dateTimeEntry.getMinHour()). entry("hourMax", dateTimeEntry.getMaxHour()). entry("minuteMin", dateTimeEntry.getMinMinute()). entry("minuteMax", dateTimeEntry.getMaxMinute()). entry("secondMin", dateTimeEntry.getMinSecond()). entry("secondMax", dateTimeEntry.getMaxSecond()); } encodeClientBehaviors(context, dateTimeEntry, json); if(!themeForms()) { json.entry("theme", false); } json.entry("disableHoverStyling", dateTimeEntry.isDisableHoverStyling()); json.entry("showCurrentAtPos", 0 - dateTimeEntry.getLeftMonthOffset()); json.entry("clientId", clientId); json.entryNonNullValue("inFieldLabel", (String) labelAttributes.get("inFieldLabel")); json.entry("inFieldLabelStyleClass", IN_FIELD_LABEL_STYLE_CLASS); json.entry("labelIsInField", (Boolean) labelAttributes.get("labelIsInField")); json.endMap(); json.endFunction(); script.append(json.toString()).append("});"); // System.out.println(script); writer.write(script.toString()); writer.endElement("script"); }
protected void encodeScript(FacesContext context, DateTimeEntry dateTimeEntry, String value, Map<String, Object> labelAttributes) throws IOException { ResponseWriter writer = context.getResponseWriter(); String clientId = dateTimeEntry.getClientId(context); writer.startElement("script", null); writer.writeAttribute("type", "text/javascript", null); String showOn = dateTimeEntry.getShowOn(); boolean timeOnly = dateTimeEntry.isTimeOnly(); StringBuilder script = new StringBuilder(); JSONBuilder json = JSONBuilder.create(); script.append("ice.ace.jq(function(){").append(resolveWidgetVar(dateTimeEntry)).append(" = new "); json.beginFunction("ice.ace.Calendar"). item(clientId). beginMap(). entry("popup", dateTimeEntry.isPopup()). entry("locale", dateTimeEntry.calculateLocale(context).toString()); if(!isValueBlank(value) && !timeOnly && dateTimeEntry.isValid()) json.entry("defaultDate", value); json.entryNonNullValue("pattern", DateTimeEntryUtils.convertPattern(dateTimeEntry.getPattern())); if(dateTimeEntry.getPages() != 1) json.entry("numberOfMonths", dateTimeEntry.getPages()); json.entryNonNullValue("minDate", DateTimeEntryUtils.getDateAsString(dateTimeEntry, dateTimeEntry.getMindate())). entryNonNullValue("maxDate", DateTimeEntryUtils.getDateAsString(dateTimeEntry, dateTimeEntry.getMaxdate())); json.entryNonNullValue("showButtonPanel", dateTimeEntry.isShowButtonPanel()); if(dateTimeEntry.isShowWeek()) json.entry("showWeek", true); if(dateTimeEntry.isDisabled()) json.entry("disabled", true); json.entryNonNullValue("yearRange", dateTimeEntry.getYearRange()); if(dateTimeEntry.isNavigator()) { json.entry("changeMonth", true). entry("changeYear", true); } if(dateTimeEntry.getEffect() != null) { json.entry("showAnim", dateTimeEntry.getEffect()). entry("duration", dateTimeEntry.getEffectDuration()); } if(!showOn.equalsIgnoreCase("focus")) { String iconSrc = dateTimeEntry.getPopupIcon() != null ? getResourceURL(context, dateTimeEntry.getPopupIcon()) : getResourceRequestPath(context, DateTimeEntry.POPUP_ICON); json.entry("showOn", showOn). entry("buttonImage", iconSrc). entry("buttonImageOnly", dateTimeEntry.isPopupIconOnly()); } if(dateTimeEntry.isShowOtherMonths()) { json.entry("showOtherMonths", true). entry("selectOtherMonths", dateTimeEntry.isSelectOtherMonths()); } //time if(dateTimeEntry.hasTime()) { json.entry("timeOnly", timeOnly). //step entry("stepHour", dateTimeEntry.getStepHour()). entry("stepMinute", dateTimeEntry.getStepMinute()). entry("stepSecond", dateTimeEntry.getStepSecond()). //minmax entry("hourMin", dateTimeEntry.getMinHour()). entry("hourMax", dateTimeEntry.getMaxHour()). entry("minuteMin", dateTimeEntry.getMinMinute()). entry("minuteMax", dateTimeEntry.getMaxMinute()). entry("secondMin", dateTimeEntry.getMinSecond()). entry("secondMax", dateTimeEntry.getMaxSecond()); } encodeClientBehaviors(context, dateTimeEntry, json); if(!themeForms()) { json.entry("theme", false); } json.entry("disableHoverStyling", dateTimeEntry.isDisableHoverStyling()); json.entry("showCurrentAtPos", 0 - dateTimeEntry.getLeftMonthOffset()); json.entry("clientId", clientId); json.entryNonNullValue("inFieldLabel", (String) labelAttributes.get("inFieldLabel")); json.entry("inFieldLabelStyleClass", IN_FIELD_LABEL_STYLE_CLASS); json.entry("labelIsInField", (Boolean) labelAttributes.get("labelIsInField")); json.endMap(); json.endFunction(); script.append(json.toString()).append("});"); // System.out.println(script); writer.write(script.toString()); writer.endElement("script"); }
diff --git a/src/main/java/com/treasure_data/bulk_import/writer/FileWriter.java b/src/main/java/com/treasure_data/bulk_import/writer/FileWriter.java index fb2a244..31a330c 100644 --- a/src/main/java/com/treasure_data/bulk_import/writer/FileWriter.java +++ b/src/main/java/com/treasure_data/bulk_import/writer/FileWriter.java @@ -1,133 +1,133 @@ // // Treasure Data Bulk-Import Tool in Java // // Copyright (C) 2012 - 2013 Muga Nishizawa // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.treasure_data.bulk_import.writer; import java.io.Closeable; import java.io.IOException; import java.util.Set; import java.util.logging.Logger; import com.treasure_data.bulk_import.Configuration; import com.treasure_data.bulk_import.model.ColumnType; import com.treasure_data.bulk_import.model.DoubleColumnValue; import com.treasure_data.bulk_import.model.IntColumnValue; import com.treasure_data.bulk_import.model.LongColumnValue; import com.treasure_data.bulk_import.model.Row; import com.treasure_data.bulk_import.model.StringColumnValue; import com.treasure_data.bulk_import.model.TimeColumnValue; import com.treasure_data.bulk_import.prepare_parts.PrepareConfiguration; import com.treasure_data.bulk_import.prepare_parts.PreparePartsException; import com.treasure_data.bulk_import.prepare_parts.PrepareProcessor; public abstract class FileWriter implements Closeable { private static final Logger LOG = Logger .getLogger(FileWriter.class.getName()); protected PrepareConfiguration conf; protected PrepareProcessor.Task task; protected long rowNum = 0; protected String[] columnNames; protected ColumnType[] columnTypes; protected Set<Integer> skipColumns; protected FileWriter(PrepareConfiguration conf) { this.conf = conf; } public void setColumnNames(String[] columnNames) { this.columnNames = columnNames; } public void setColumnTypes(ColumnType[] columnTypes) { this.columnTypes = columnTypes; } public void setSkipColumns(Set<Integer> skipColumns) { this.skipColumns = skipColumns; } public void configure(PrepareProcessor.Task task) throws PreparePartsException { this.task = task; } public void next(Row row) throws PreparePartsException { int size = row.getValues().length; // begin writing if (row.needAdditionalTimeColumn()) { // if the row doesn't have 'time' column, new 'time' column needs // to be appended to it. - writeBeginRow(size + skipColumns.size() - 1); + writeBeginRow(size - skipColumns.size() - 1); } else { - writeBeginRow(size + skipColumns.size()); + writeBeginRow(size - skipColumns.size()); } // write columns for (int i = 0; i < size; i++) { if (skipColumns.contains(i)) { continue; } write(columnNames[i]); if (i == row.getTimeColumnIndex()) { row.getTimeColumnValue().write(row.getValue(i), this); } else { row.getValue(i).write(this); } } if (row.needAdditionalTimeColumn()) { write(Configuration.BI_PREPARE_PARTS_TIMECOLUMN_DEFAULTVALUE); TimeColumnValue tcValue = row.getTimeColumnValue(); tcValue.write(row.getValue(tcValue.getIndex()), this); } // end writeEndRow(); } public abstract void writeBeginRow(int size) throws PreparePartsException; public abstract void writeNil() throws PreparePartsException; public abstract void write(String v) throws PreparePartsException; public abstract void write(int v) throws PreparePartsException; public abstract void write(long v) throws PreparePartsException; public abstract void write(double v) throws PreparePartsException; public abstract void write(TimeColumnValue filter, StringColumnValue v) throws PreparePartsException; public abstract void write(TimeColumnValue filter, IntColumnValue v) throws PreparePartsException; public abstract void write(TimeColumnValue filter, LongColumnValue v) throws PreparePartsException; public abstract void write(TimeColumnValue filter, DoubleColumnValue v) throws PreparePartsException; public abstract void writeEndRow() throws PreparePartsException; public void resetRowNum() { rowNum = 0; } public void incrementRowNum() { rowNum++; } public long getRowNum() { return rowNum; } // Closeable#close() public abstract void close() throws IOException; }
false
true
public void next(Row row) throws PreparePartsException { int size = row.getValues().length; // begin writing if (row.needAdditionalTimeColumn()) { // if the row doesn't have 'time' column, new 'time' column needs // to be appended to it. writeBeginRow(size + skipColumns.size() - 1); } else { writeBeginRow(size + skipColumns.size()); } // write columns for (int i = 0; i < size; i++) { if (skipColumns.contains(i)) { continue; } write(columnNames[i]); if (i == row.getTimeColumnIndex()) { row.getTimeColumnValue().write(row.getValue(i), this); } else { row.getValue(i).write(this); } } if (row.needAdditionalTimeColumn()) { write(Configuration.BI_PREPARE_PARTS_TIMECOLUMN_DEFAULTVALUE); TimeColumnValue tcValue = row.getTimeColumnValue(); tcValue.write(row.getValue(tcValue.getIndex()), this); } // end writeEndRow(); }
public void next(Row row) throws PreparePartsException { int size = row.getValues().length; // begin writing if (row.needAdditionalTimeColumn()) { // if the row doesn't have 'time' column, new 'time' column needs // to be appended to it. writeBeginRow(size - skipColumns.size() - 1); } else { writeBeginRow(size - skipColumns.size()); } // write columns for (int i = 0; i < size; i++) { if (skipColumns.contains(i)) { continue; } write(columnNames[i]); if (i == row.getTimeColumnIndex()) { row.getTimeColumnValue().write(row.getValue(i), this); } else { row.getValue(i).write(this); } } if (row.needAdditionalTimeColumn()) { write(Configuration.BI_PREPARE_PARTS_TIMECOLUMN_DEFAULTVALUE); TimeColumnValue tcValue = row.getTimeColumnValue(); tcValue.write(row.getValue(tcValue.getIndex()), this); } // end writeEndRow(); }
diff --git a/src/main/java/org/spoutcraft/launcher/technic/skin/LauncherOptions.java b/src/main/java/org/spoutcraft/launcher/technic/skin/LauncherOptions.java index d1f0a31..1589260 100644 --- a/src/main/java/org/spoutcraft/launcher/technic/skin/LauncherOptions.java +++ b/src/main/java/org/spoutcraft/launcher/technic/skin/LauncherOptions.java @@ -1,281 +1,283 @@ /* * This file is part of Technic Launcher. * * Copyright (c) 2013-2013, Technic <http://www.technicpack.net/> * Technic Launcher is licensed under the Spout License Version 1. * * Technic Launcher is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * In addition, 180 days after any changes are published, you can use the * software, incorporating those changes, under the terms of the MIT license, * as described in the Spout License Version 1. * * Technic Launcher is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License, * the MIT license and the Spout License Version 1 along with this program. * If not, see <http://www.gnu.org/licenses/> for the GNU Lesser General Public * License and see <http://www.spout.org/SpoutDevLicenseV1.txt> for the full license, * including the MIT license. */ package org.spoutcraft.launcher.technic.skin; import java.awt.Color; import java.awt.Container; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.io.File; import java.lang.management.ManagementFactory; import java.lang.management.OperatingSystemMXBean; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.SwingConstants; import org.spoutcraft.launcher.Memory; import org.spoutcraft.launcher.Settings; import org.spoutcraft.launcher.entrypoint.SpoutcraftLauncher; import org.spoutcraft.launcher.skin.MetroLoginFrame; import org.spoutcraft.launcher.skin.components.LiteButton; import org.spoutcraft.launcher.util.Compatibility; import org.spoutcraft.launcher.util.Utils; public class LauncherOptions extends JDialog implements ActionListener, MouseListener, MouseMotionListener { private static final long serialVersionUID = 1L; private static final int FRAME_WIDTH = 300; private static final int FRAME_HEIGHT = 300; private static final String QUIT_ACTION = "quit"; private static final String SAVE_ACTION = "save"; private static final String LOGS_ACTION = "logs"; private static final String CONSOLE_ACTION = "console"; private JLabel background; private JLabel build; private LiteButton logs; private JComboBox memory; private JCheckBox permgen; private int mouseX = 0, mouseY = 0; public LauncherOptions() { setTitle("Launcher Options"); setSize(FRAME_WIDTH, FRAME_HEIGHT); addMouseListener(this); addMouseMotionListener(this); setResizable(false); setUndecorated(true); initComponents(); } private void initComponents() { Font minecraft = MetroLoginFrame.getMinecraftFont(12); background = new JLabel(); background.setBounds(0,0, FRAME_WIDTH, FRAME_HEIGHT); MetroLoginFrame.setIcon(background, "optionsBackground.png", background.getWidth(), background.getHeight()); ImageButton optionsQuit = new ImageButton(MetroLoginFrame.getIcon("quit.png", 28, 28), MetroLoginFrame.getIcon("quit.png", 28, 28)); optionsQuit.setRolloverIcon(MetroLoginFrame.getIcon("quitHover.png", 28, 28)); optionsQuit.setBounds(FRAME_WIDTH - 38, 10, 28, 28); optionsQuit.setActionCommand(QUIT_ACTION); optionsQuit.addActionListener(this); JLabel title = new JLabel("Launcher Options"); title.setFont(minecraft.deriveFont(14F)); title.setBounds(50, 10, 200, 20); title.setForeground(Color.WHITE); title.setHorizontalAlignment(SwingConstants.CENTER); JLabel memoryLabel = new JLabel("Memory: "); memoryLabel.setFont(minecraft); memoryLabel.setBounds(50, 100, 75, 25); memoryLabel.setForeground(Color.WHITE); memory = new JComboBox(); memory.setBounds(150, 100, 100, 25); populateMemory(memory); permgen = new JCheckBox("Increase PermGen Size"); permgen.setFont(minecraft); permgen.setBounds(50, 150, 200, 25); permgen.setSelected(Settings.getPermGen()); permgen.setBorderPainted(false); permgen.setFocusPainted(false); + permgen.setContentAreaFilled(false); + permgen.setForeground(Color.WHITE); LiteButton save = new LiteButton("Save"); save.setFont(minecraft.deriveFont(14F)); save.setBounds(FRAME_WIDTH - 90 - 10, FRAME_HEIGHT - 60, 90, 30); save.setActionCommand(SAVE_ACTION); save.addActionListener(this); logs = new LiteButton("Logs"); logs.setFont(minecraft.deriveFont(14F)); logs.setBounds(FRAME_WIDTH / 2 - 45, FRAME_HEIGHT - 60, 90, 30); logs.setForeground(Color.WHITE); logs.setActionCommand(LOGS_ACTION); logs.addActionListener(this); LiteButton console = new LiteButton("Console"); console.setFont(minecraft.deriveFont(14F)); console.setBounds(10, FRAME_HEIGHT - 60, 90, 30); console.setForeground(Color.WHITE); console.setActionCommand(CONSOLE_ACTION); console.addActionListener(this); build = new JLabel("Launcher Build: " + Settings.getLauncherBuild()); build.setBounds(10, FRAME_HEIGHT - 25, 150, 20); build.setFont(minecraft); build.setForeground(Color.WHITE); Container contentPane = getContentPane(); contentPane.add(permgen); contentPane.add(build); contentPane.add(logs); contentPane.add(console); contentPane.add(optionsQuit); contentPane.add(title); contentPane.add(memory); contentPane.add(memoryLabel); contentPane.add(save); contentPane.add(background); setLocationRelativeTo(this.getOwner()); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof JComponent) { action(e.getActionCommand(), (JComponent) e.getSource()); } } public void action(String action, JComponent c) { if (action.equals(QUIT_ACTION)) { dispose(); } else if (action.equals(SAVE_ACTION)) { int oldMem = Settings.getMemory(); int mem = Memory.memoryOptions[memory.getSelectedIndex()].getSettingsId(); Settings.setMemory(mem); boolean oldperm = Settings.getPermGen(); boolean perm = permgen.isSelected(); Settings.setPermGen(perm); Settings.getYAML().save(); if (mem != oldMem || oldperm != perm) { int result = JOptionPane.showConfirmDialog(c, "Restart required for settings to take effect. Would you like to restart?", "Restart Required", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); if (result == JOptionPane.YES_OPTION) { SpoutcraftLauncher.relaunch(true); } } dispose(); } else if (action.equals(LOGS_ACTION)) { File logDirectory = new File(Utils.getLauncherDirectory(), "logs"); Compatibility.open(logDirectory); } else if (action.equals(CONSOLE_ACTION)) { SpoutcraftLauncher.setupConsole(); dispose(); } } @SuppressWarnings("restriction") private void populateMemory(JComboBox memory) { long maxMemory = 1024; String architecture = System.getProperty("sun.arch.data.model", "32"); boolean bit64 = architecture.equals("64"); try { OperatingSystemMXBean osInfo = ManagementFactory.getOperatingSystemMXBean(); if (osInfo instanceof com.sun.management.OperatingSystemMXBean) { maxMemory = ((com.sun.management.OperatingSystemMXBean) osInfo).getTotalPhysicalMemorySize() / 1024 / 1024; } } catch (Throwable t) { } maxMemory = Math.max(512, maxMemory); if (maxMemory >= Memory.MAX_32_BIT_MEMORY && !bit64) { memory.setToolTipText("<html>Sets the amount of memory assigned to Minecraft<br/>" + "You have more than 1.5GB of memory available, but<br/>" + "you must have 64bit java installed to use it.</html>"); } else { memory.setToolTipText("<html>Sets the amount of memory assigned to Minecraft<br/>" + "More memory is not always better.<br/>" + "More memory will also cause your CPU to work more.</html>"); } if (!bit64) { maxMemory = Math.min(Memory.MAX_32_BIT_MEMORY, maxMemory); } System.out.println("Maximum usable memory detected: " + maxMemory + " mb"); for (Memory mem : Memory.memoryOptions) { if (maxMemory >= mem.getMemoryMB()) { memory.addItem(mem.getDescription()); } } int memoryOption = Settings.getMemory(); try { Settings.setMemory(memoryOption); memory.setSelectedIndex(Memory.getMemoryIndexFromId(memoryOption)); } catch (IllegalArgumentException e) { memory.removeAllItems(); memory.addItem(String.valueOf(Memory.memoryOptions[0])); Settings.setMemory(1); // 512 == 1 memory.setSelectedIndex(0); // 1st element } } @Override public void mouseDragged(MouseEvent e) { this.setLocation(e.getXOnScreen() - mouseX, e.getYOnScreen() - mouseY); } @Override public void mouseMoved(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseClicked(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent e) { mouseX = e.getX(); mouseY = e.getY(); } @Override public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub } }
true
true
private void initComponents() { Font minecraft = MetroLoginFrame.getMinecraftFont(12); background = new JLabel(); background.setBounds(0,0, FRAME_WIDTH, FRAME_HEIGHT); MetroLoginFrame.setIcon(background, "optionsBackground.png", background.getWidth(), background.getHeight()); ImageButton optionsQuit = new ImageButton(MetroLoginFrame.getIcon("quit.png", 28, 28), MetroLoginFrame.getIcon("quit.png", 28, 28)); optionsQuit.setRolloverIcon(MetroLoginFrame.getIcon("quitHover.png", 28, 28)); optionsQuit.setBounds(FRAME_WIDTH - 38, 10, 28, 28); optionsQuit.setActionCommand(QUIT_ACTION); optionsQuit.addActionListener(this); JLabel title = new JLabel("Launcher Options"); title.setFont(minecraft.deriveFont(14F)); title.setBounds(50, 10, 200, 20); title.setForeground(Color.WHITE); title.setHorizontalAlignment(SwingConstants.CENTER); JLabel memoryLabel = new JLabel("Memory: "); memoryLabel.setFont(minecraft); memoryLabel.setBounds(50, 100, 75, 25); memoryLabel.setForeground(Color.WHITE); memory = new JComboBox(); memory.setBounds(150, 100, 100, 25); populateMemory(memory); permgen = new JCheckBox("Increase PermGen Size"); permgen.setFont(minecraft); permgen.setBounds(50, 150, 200, 25); permgen.setSelected(Settings.getPermGen()); permgen.setBorderPainted(false); permgen.setFocusPainted(false); LiteButton save = new LiteButton("Save"); save.setFont(minecraft.deriveFont(14F)); save.setBounds(FRAME_WIDTH - 90 - 10, FRAME_HEIGHT - 60, 90, 30); save.setActionCommand(SAVE_ACTION); save.addActionListener(this); logs = new LiteButton("Logs"); logs.setFont(minecraft.deriveFont(14F)); logs.setBounds(FRAME_WIDTH / 2 - 45, FRAME_HEIGHT - 60, 90, 30); logs.setForeground(Color.WHITE); logs.setActionCommand(LOGS_ACTION); logs.addActionListener(this); LiteButton console = new LiteButton("Console"); console.setFont(minecraft.deriveFont(14F)); console.setBounds(10, FRAME_HEIGHT - 60, 90, 30); console.setForeground(Color.WHITE); console.setActionCommand(CONSOLE_ACTION); console.addActionListener(this); build = new JLabel("Launcher Build: " + Settings.getLauncherBuild()); build.setBounds(10, FRAME_HEIGHT - 25, 150, 20); build.setFont(minecraft); build.setForeground(Color.WHITE); Container contentPane = getContentPane(); contentPane.add(permgen); contentPane.add(build); contentPane.add(logs); contentPane.add(console); contentPane.add(optionsQuit); contentPane.add(title); contentPane.add(memory); contentPane.add(memoryLabel); contentPane.add(save); contentPane.add(background); setLocationRelativeTo(this.getOwner()); }
private void initComponents() { Font minecraft = MetroLoginFrame.getMinecraftFont(12); background = new JLabel(); background.setBounds(0,0, FRAME_WIDTH, FRAME_HEIGHT); MetroLoginFrame.setIcon(background, "optionsBackground.png", background.getWidth(), background.getHeight()); ImageButton optionsQuit = new ImageButton(MetroLoginFrame.getIcon("quit.png", 28, 28), MetroLoginFrame.getIcon("quit.png", 28, 28)); optionsQuit.setRolloverIcon(MetroLoginFrame.getIcon("quitHover.png", 28, 28)); optionsQuit.setBounds(FRAME_WIDTH - 38, 10, 28, 28); optionsQuit.setActionCommand(QUIT_ACTION); optionsQuit.addActionListener(this); JLabel title = new JLabel("Launcher Options"); title.setFont(minecraft.deriveFont(14F)); title.setBounds(50, 10, 200, 20); title.setForeground(Color.WHITE); title.setHorizontalAlignment(SwingConstants.CENTER); JLabel memoryLabel = new JLabel("Memory: "); memoryLabel.setFont(minecraft); memoryLabel.setBounds(50, 100, 75, 25); memoryLabel.setForeground(Color.WHITE); memory = new JComboBox(); memory.setBounds(150, 100, 100, 25); populateMemory(memory); permgen = new JCheckBox("Increase PermGen Size"); permgen.setFont(minecraft); permgen.setBounds(50, 150, 200, 25); permgen.setSelected(Settings.getPermGen()); permgen.setBorderPainted(false); permgen.setFocusPainted(false); permgen.setContentAreaFilled(false); permgen.setForeground(Color.WHITE); LiteButton save = new LiteButton("Save"); save.setFont(minecraft.deriveFont(14F)); save.setBounds(FRAME_WIDTH - 90 - 10, FRAME_HEIGHT - 60, 90, 30); save.setActionCommand(SAVE_ACTION); save.addActionListener(this); logs = new LiteButton("Logs"); logs.setFont(minecraft.deriveFont(14F)); logs.setBounds(FRAME_WIDTH / 2 - 45, FRAME_HEIGHT - 60, 90, 30); logs.setForeground(Color.WHITE); logs.setActionCommand(LOGS_ACTION); logs.addActionListener(this); LiteButton console = new LiteButton("Console"); console.setFont(minecraft.deriveFont(14F)); console.setBounds(10, FRAME_HEIGHT - 60, 90, 30); console.setForeground(Color.WHITE); console.setActionCommand(CONSOLE_ACTION); console.addActionListener(this); build = new JLabel("Launcher Build: " + Settings.getLauncherBuild()); build.setBounds(10, FRAME_HEIGHT - 25, 150, 20); build.setFont(minecraft); build.setForeground(Color.WHITE); Container contentPane = getContentPane(); contentPane.add(permgen); contentPane.add(build); contentPane.add(logs); contentPane.add(console); contentPane.add(optionsQuit); contentPane.add(title); contentPane.add(memory); contentPane.add(memoryLabel); contentPane.add(save); contentPane.add(background); setLocationRelativeTo(this.getOwner()); }
diff --git a/ev/util/debian/Main.java b/ev/util/debian/Main.java index 516590b4..33c5e310 100644 --- a/ev/util/debian/Main.java +++ b/ev/util/debian/Main.java @@ -1,480 +1,482 @@ /*** * Copyright (C) 2010 Johan Henriksson * This code is under the Endrov / BSD license. See www.endrov.net * for the full text and how to cite. */ package util.debian; import java.io.*; import java.nio.channels.FileChannel; import java.util.*; import endrov.util.EvFileUtil; /** * Take all-platform release and turn into .deb * * All code and jars should be dumped into: * /usr/share/endrov/ * * docs is put into * /usr/share/doc/endrov/ * * other files * /usr/share/man/man1/endrov.1.gz * /usr/share/menu/endrov * /usr/share/pixmaps/endrov.xpm * * http://freedesktop.org/wiki/Specifications/desktop-entry-spec?action=show&redirect=Standards%2Fdesktop-entry-spec * * * * ============ goals ======== * turn libraries into dependencies * delete plugins that are specicific to other OS' * integrate endrov into debian desktop * ======= debian guidelines ==== * separate packaging system from project. this is why * this is a separate project. * automatic upgrades by downloading source * -> later problem * * @author Johan Henriksson * */ public class Main { public static void main(String[] args) { try { File zip=null; if(args.length==1) zip=new File(args[0]); else { System.out.println("Argument: zip-file of release"); System.exit(1); } File dPkg=new File("/tmp/endrov"); File dUsr=new File(dPkg,"usr"); //File dEtc=new File(dPkg,"etc"); File dShare=new File(dUsr,"share"); File dEndrov=new File(dShare,"endrov"); File dEndrovLibs=new File(dEndrov,"libs"); //File dMan=new File(dShare,"man/man1"); //File dMenu=new File(dShare,"menu"); File dControl=new File(dPkg,"DEBIAN"); File dZipTemp=new File("/tmp/unzip"); File dShareDoc=new File(dShare,"doc"); //File dSharePixmaps=new File(dShare,"pixmaps"); File dUsrBin=new File(dUsr,"bin"); //File dShareApplications=new File(dShare,"applications"); //File dEtcBash=new File(dEtc,"bash_completion.d"); File dRes=new File("util/debian"); File fUsrBinEndrov=new File(dUsrBin,"endrov"); //File fIcon=new File(dSharePixmaps,"endrov.xpm"); //File fUsrShareMenuEndrov=new File(dMenu,"endrov"); //File fUsrShareApplicationsEndrov=new File(dShareApplications,"endrov.desktop"); //Clean dirs if(dPkg.exists()) recursiveDelete(dPkg); if(dZipTemp.exists()) recursiveDelete(dZipTemp); //Make dirs dShare.mkdirs(); dControl.mkdirs(); dShareDoc.mkdirs(); //dMan.mkdirs(); //dMenu.mkdirs(); dUsrBin.mkdirs(); //dSharePixmaps.mkdirs(); //dShareApplications.mkdirs(); //Extract files System.out.println("unzipping "+zip.getPath()); dZipTemp.mkdirs(); Process proc=Runtime.getRuntime().exec(new String[]{"/usr/bin/unzip",zip.getPath(),"-d",dZipTemp.getPath()}); BufferedReader os=new BufferedReader(new InputStreamReader(proc.getInputStream())); while(os.readLine()!=null); proc.waitFor(); System.out.println("unzip done"); System.out.println("Moving into place, "+dZipTemp.listFiles()[0]+" ---> "+dEndrov); dZipTemp.listFiles()[0].renameTo(dEndrov); new File(dEndrov,"docs").renameTo(new File(dShareDoc,"endrov")); /*copyFile(new File(dRes,"endrov.1"), new File(dMan,"endrov.1")); copyFile(new File(dRes,"icon.xpm"), fIcon); copyFile(new File(dRes,"endrov.sh"),fUsrBinEndrov); copyFile(new File(dRes,"usrShareMenuEndrov"),fUsrShareMenuEndrov); copyFile(new File(dRes,"endrov.desktop"),fUsrShareApplicationsEndrov); copyFile(new File(dRes,"bash_completion"),new File(dEtcBash,"endrov"));*/ copyRecursive(new File(dRes,"root"), dPkg); setExec(fUsrBinEndrov); + setExec(new File(dControl,"postinst")); + setExec(new File(dControl,"postrm")); //fUsrEndrov.setExecutable(true); System.out.println("Cleaning out windows/mac specific files"); for(File f:dEndrov.listFiles()) if(f.getName().startsWith("libmmgr_dal") || f.getName().endsWith(".jnilib") || f.getName().endsWith(".dll") || f.getName().startsWith("hs_err")) f.delete(); System.out.println("Set up package dependencies"); //Packages //maybe do pattern match instead? List<DebPackage> pkgs=new LinkedList<DebPackage>(); pkgs.add(new DebPackage("java2-runtime",null,new String[]{"linux.paths"})); pkgs.add(new DebPackage("bsh",new String[]{"bsh-2.0b5.jar"},new String[]{"bsh-2.0b5.jar"})); pkgs.add(new DebPackage("junit",new String[]{"junit.jar"},new String[]{"junit.jar"})); pkgs.add(new DebPackage("libpg-java",new String[]{"postgresql.jar"},new String[]{"postgresql-8.2-505.jdbc3.jar"})); //pkgs.add(new DebPackage("libvecmath1.2-java",new String[]{"vecmath1.2.jar"},new String[]{"vecmath.jar"})); pkgs.add(new DebPackage("libbcel-java",new String[]{"bcel.jar"},new String[]{"bcel-5.2.jar"})); pkgs.add(new DebPackage("libservlet2.3-java",new String[]{"servlet-2.3.jar"},new String[]{"servlet.jar"})); //2.4 also exists pkgs.add(new DebPackage("libxalan2-java",new String[]{"xalan2.jar"},new String[]{"xalan.jar","xerces.jar","xml-apis.jar"})); pkgs.add(new DebPackage("libjdom1-java",new String[]{"jdom1.jar"},new String[]{"jdom.jar"})); //any overlap here? pkgs.add(new DebPackage("libjfreechart-java",new String[]{"jfreechart.jar"},new String[]{"jfreechart-1.0.5.jar"})); pkgs.add(new DebPackage("libjakarta-poi-java",new String[]{"jakarta-poi-contrib.jar","jakarta-poi.jar","jakarta-poi-scratchpad.jar"},new String[]{"poi-contrib-3.0.1-FINAL-20070705.jar","poi-3.0.1-FINAL-20070705.jar","poi-scratchpad-3.0.1-FINAL-20070705.jar"})); pkgs.add(new DebPackage("libjaxen-java",new String[]{"jaxen.jar"},new String[]{"jaxen-core.jar","jaxen-jdom.jar","saxpath.jar"})); //jogl2 must get into the repos! //pkgs.add(new DebPackage("libjogl-java",new String[]{"jogl.jar","gluegen-rt.jar"},new String[]{"gluegen-rt.jar","jogl.jar","libgluegen-rt.so","libjogl_awt.so","libjogl_cg.so","libjogl.so"})); //the system jutils seems to clash badly with the one needed by jogl2, hence jinput has to go for now //pkgs.add(DebPackage.recommends("libjinput-java",new String[]{"jinput.jar"},new String[]{"libjinput-linux.so","jinput.jar","jinput-test.jar"})); pkgs.add(new DebPackage("qhull-bin",new String[]{},new String[]{})); pkgs.add(DebPackage.recommends("micromanager",new String[]{},new String[]{"umanager_inc"})); //rely on inc-file to add jar files //JAI, seems to work without //the filter system might need some operations, not sure //pkgs.add(new DebPackage(null,null,new String[]{"jai_codec.jar","jai_core.jar","mlibwrapper_jai.jar","libmlib_jai.so"})); //Specialty for micro-manager // File dLibs=new File(dEndrov,"libs"); // EvFileUtil.writeFile(new File(dLibs,"umanager.paths"), "b:/usr/lib/micro-manager"); //For OME http://trac.openmicroscopy.org.uk/omero/wiki/OmeroClientLibrary //Consider a separate OME package to reduce dependencies pkgs.add(new DebPackage("liblog4j1.2-java",new String[]{"log4j-1.2.jar"},new String[]{"log4j-1.2.14.jar"})); pkgs.add(new DebPackage("libjboss-aop-java",new String[]{"jboss-aop.jar"},new String[]{"jboss-aop-jdk50-4.2.1.GA.jar","jboss-aop-jdk50-client-4.2.1.GA.jar"})); pkgs.add(new DebPackage("libjboss-aspects-java",new String[]{"jboss-aspects.jar"},new String[]{"jboss-aspect-library-jdk50-4.2.1.GA.jar"})); pkgs.add(new DebPackage("libjboss-ejb3-java",new String[]{"jboss-ejb3.jar"},new String[]{"jboss-ejb3-4.2.1.GA.jar"})); pkgs.add(new DebPackage("libjboss-ejb3x-java",new String[]{"jboss-ejb3x.jar"},new String[]{"jboss-ejb3x-4.2.1.GA.jar"})); pkgs.add(new DebPackage("libjcommon-java",new String[]{"jcommon.jar"},new String[]{"jcommon-1.0.9.jar"})); pkgs.add(new DebPackage("libcommons-codec-java",new String[]{"commons-codec.jar"},new String[]{"commons-codec-1.3.jar"})); pkgs.add(new DebPackage("libcommons-httpclient-java",new String[]{"commons-httpclient.jar"},new String[]{"commons-httpclient-3.0.1.jar"})); pkgs.add(new DebPackage("libcommons-logging-java",new String[]{"commons-logging.jar"},new String[]{"commons-logging-1.0.4.jar"})); pkgs.add(DebPackage.recommends("ffmpeg",null,null)); //Unused //pkgs.add(new DebPackage("lib-jline-java",new String[]{"jline-0.9.94.jar"})); //pkgs.add(new DebPackage("libjsch-java",new String[]{"jsch-0.1.34.jar"})); /* _jboss_remoting.jar jbossall-client-4.2.1.GA.jar spring-2.0.6.jar jboss-annotations-ejb3-4.2.1.GA.jar jbossas4 libjboss-cluster-java libjboss-connector-java libjboss-deployment-java libjboss-j2ee-java libjboss-jms-java libjboss-jmx-java libjboss-management-java libjboss-messaging-java libjboss-naming-java libjboss-security-java libjboss-server-java libjboss-system-java libjboss-test-java libjboss-transaction-java libjboss-webservices-java */ System.out.println("Deleting binary files not for linux"); deleteBinDirs(dEndrov); deleteExt(dEndrov, ".app"); //Mac APP-bundles //Check which packages are present for(DebPackage pkg:new LinkedList<DebPackage>(pkgs)) { for(String jar:pkg.linkJars) { File jarfile=new File("/usr/share/java",jar); if(!jarfile.exists()) { System.out.println("System jar does not exist: "+jarfile+", excluding package "+pkg.name); pkgs.remove(pkg); } } //TODO check that files exist //for(String jar:pkg.providesFiles) } System.out.println("Extracting packages"); deletePkgFiles(pkgs, dEndrovLibs); File manifestFile=File.createTempFile("MANIFEST", ""); StringBuffer manifestContent=new StringBuffer(); manifestContent.append("Manifest-Version: 1.0\n"); manifestContent.append("Class-Path: \n"); for(DebPackage pkg:pkgs) for(String jar:pkg.linkJars) { File jarfile=new File("/usr/share/java",jar); manifestContent.append(" "+jarfile.getAbsolutePath()+" \n"); } manifestContent.append("\n"); EvFileUtil.writeFile(manifestFile, manifestContent.toString()); runUntilQuit(new String[]{"/usr/bin/jar","cmf",manifestFile.getAbsolutePath(),new File(dEndrovLibs,"debian.jar").getAbsolutePath()}); System.out.println("Writing control file"); Scanner scanner = new Scanner(EvFileUtil.readFile(new File(dEndrov,"endrov/ev/version.txt"))); String version=scanner.nextLine(); int totalSize=(int)Math.ceil((recursiveSize(dUsr)+100000)/1000000.0); String controlFile=EvFileUtil.readFile(new File(dRes,"debiancontrol-TEMPLATE")). replace("DEPENDENCIES", makeDeps(pkgs)). replace("RECOMMENDS", makeRecommends(pkgs)). replace("SUGGESTS", makeSuggests(pkgs)). replace("VERSION",version). replace("SIZE",""+totalSize); System.out.println("--------------------------------------"); System.out.println(controlFile); System.out.println("--------------------------------------"); EvFileUtil.writeFile(new File(dControl,"control"), controlFile); System.out.println("Debianizing"); String datepart=zip.getName().substring(2,8); // File outDeb=new File(zip.getParentFile(),zip.getName().replace(".zip", ".deb")); File outDeb=new File(zip.getParentFile(),"endrov-"+version+"-"+datepart+".deb"); if(outDeb.exists()) outDeb.delete(); runUntilQuit(new String[]{"/usr/bin/dpkg-deb","-b","/tmp/endrov"}); //dpkg-deb -b endrov runUntilQuit(new String[]{"/bin/mv","/tmp/endrov.deb",outDeb.toString()}); //boolean moveOk=new File("/tmp/endrov.deb").renameTo(outDeb); System.out.println(outDeb); System.out.println("Done"); } catch (Exception e) { e.printStackTrace(); } } public static void setExec(File file) { System.out.println("set exec "+file); runUntilQuit(new String[]{"/bin/chmod","+x",file.getPath()}); } public static void runUntilQuit(String[] arg) { try { Process proc=Runtime.getRuntime().exec(arg); BufferedReader os=new BufferedReader(new InputStreamReader(proc.getInputStream())); while(os.readLine()!=null); proc.waitFor(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } public static String makeDeps(List<DebPackage> pkgs) throws Exception { StringBuffer sb=new StringBuffer(); boolean first=true; for(DebPackage p:pkgs) if(p.name!=null && p.isDepends) { if(!first) sb.append(","); sb.append(p.name); first=false; } return sb.toString(); } public static String makeSuggests(List<DebPackage> pkgs) throws Exception { StringBuffer sb=new StringBuffer(); boolean first=true; for(DebPackage p:pkgs) if(p.name!=null && p.isSuggestion) { if(!first) sb.append(","); sb.append(p.name); first=false; } return sb.toString(); } public static String makeRecommends(List<DebPackage> pkgs) throws Exception { StringBuffer sb=new StringBuffer(); boolean first=true; for(DebPackage p:pkgs) if(p.name!=null && p.isRecommended) { if(!first) sb.append(","); sb.append(p.name); first=false; } return sb.toString(); } public static void deletePkgFiles(List<DebPackage> pkgs, File root) { boolean toDel=false; String fname=root.getName(); for(DebPackage p:pkgs) if(p.providesFiles.contains(fname)) { toDel=true; break; } if(toDel) recursiveDelete(root); else { if(root.isDirectory()) for(File child:root.listFiles()) deletePkgFiles(pkgs, child); } } public static void deleteExt(File root, String ext) { for(File child:root.listFiles()) if(child.getName().endsWith(ext)) recursiveDelete(child); else if(child.isDirectory()) deleteExt(child, ext); } public static void deleteBinDirs(File root) { for(File child:root.listFiles()) { if(child.isDirectory() && child.getName().startsWith("bin_")) { String osName=child.getName().substring(4); if(!osName.equals("linux")) recursiveDelete(child); } else if(child.isDirectory()) deleteBinDirs(child); } } public static void copyFile(File in, File out) throws IOException { //limitation http://forums.sun.com/thread.jspa?threadID=439695&messageID=2917510 out.getParentFile().mkdirs(); FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try{inChannel.transferTo(0, inChannel.size(), outChannel);} catch (IOException e){throw e;} finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } public static void copyRecursive(File in, File out) throws IOException { if(in.isDirectory()) { for(File c:in.listFiles()) if(!c.getName().equals(".") && !c.getName().equals("..")) { File outc=new File(out,c.getName()); if(c.isDirectory()) outc.mkdirs(); copyRecursive(c, outc); } } else copyFile(in,out); } public static void recursiveDelete(File root) { //System.out.println("delete "+root); if(root.isDirectory()) for(File child:root.listFiles()) recursiveDelete(child); root.delete(); } public static long recursiveSize(File root) { //System.out.println("delete "+root); if(root.isDirectory()) { long size=0; for(File child:root.listFiles()) size+=recursiveSize(child); return size; } else return root.length(); } } /* String line; while((line=os.readLine())!=null) System.out.println(line);*/ //ProcessBuilder pb=new ProcessBuilder("/usr/bin/unzip",zip.getPath(),"-d","/tmp"); //pb.start().waitFor();
true
true
public static void main(String[] args) { try { File zip=null; if(args.length==1) zip=new File(args[0]); else { System.out.println("Argument: zip-file of release"); System.exit(1); } File dPkg=new File("/tmp/endrov"); File dUsr=new File(dPkg,"usr"); //File dEtc=new File(dPkg,"etc"); File dShare=new File(dUsr,"share"); File dEndrov=new File(dShare,"endrov"); File dEndrovLibs=new File(dEndrov,"libs"); //File dMan=new File(dShare,"man/man1"); //File dMenu=new File(dShare,"menu"); File dControl=new File(dPkg,"DEBIAN"); File dZipTemp=new File("/tmp/unzip"); File dShareDoc=new File(dShare,"doc"); //File dSharePixmaps=new File(dShare,"pixmaps"); File dUsrBin=new File(dUsr,"bin"); //File dShareApplications=new File(dShare,"applications"); //File dEtcBash=new File(dEtc,"bash_completion.d"); File dRes=new File("util/debian"); File fUsrBinEndrov=new File(dUsrBin,"endrov"); //File fIcon=new File(dSharePixmaps,"endrov.xpm"); //File fUsrShareMenuEndrov=new File(dMenu,"endrov"); //File fUsrShareApplicationsEndrov=new File(dShareApplications,"endrov.desktop"); //Clean dirs if(dPkg.exists()) recursiveDelete(dPkg); if(dZipTemp.exists()) recursiveDelete(dZipTemp); //Make dirs dShare.mkdirs(); dControl.mkdirs(); dShareDoc.mkdirs(); //dMan.mkdirs(); //dMenu.mkdirs(); dUsrBin.mkdirs(); //dSharePixmaps.mkdirs(); //dShareApplications.mkdirs(); //Extract files System.out.println("unzipping "+zip.getPath()); dZipTemp.mkdirs(); Process proc=Runtime.getRuntime().exec(new String[]{"/usr/bin/unzip",zip.getPath(),"-d",dZipTemp.getPath()}); BufferedReader os=new BufferedReader(new InputStreamReader(proc.getInputStream())); while(os.readLine()!=null); proc.waitFor(); System.out.println("unzip done"); System.out.println("Moving into place, "+dZipTemp.listFiles()[0]+" ---> "+dEndrov); dZipTemp.listFiles()[0].renameTo(dEndrov); new File(dEndrov,"docs").renameTo(new File(dShareDoc,"endrov")); /*copyFile(new File(dRes,"endrov.1"), new File(dMan,"endrov.1")); copyFile(new File(dRes,"icon.xpm"), fIcon); copyFile(new File(dRes,"endrov.sh"),fUsrBinEndrov); copyFile(new File(dRes,"usrShareMenuEndrov"),fUsrShareMenuEndrov); copyFile(new File(dRes,"endrov.desktop"),fUsrShareApplicationsEndrov); copyFile(new File(dRes,"bash_completion"),new File(dEtcBash,"endrov"));*/ copyRecursive(new File(dRes,"root"), dPkg); setExec(fUsrBinEndrov); //fUsrEndrov.setExecutable(true); System.out.println("Cleaning out windows/mac specific files"); for(File f:dEndrov.listFiles()) if(f.getName().startsWith("libmmgr_dal") || f.getName().endsWith(".jnilib") || f.getName().endsWith(".dll") || f.getName().startsWith("hs_err")) f.delete(); System.out.println("Set up package dependencies"); //Packages //maybe do pattern match instead? List<DebPackage> pkgs=new LinkedList<DebPackage>(); pkgs.add(new DebPackage("java2-runtime",null,new String[]{"linux.paths"})); pkgs.add(new DebPackage("bsh",new String[]{"bsh-2.0b5.jar"},new String[]{"bsh-2.0b5.jar"}));
public static void main(String[] args) { try { File zip=null; if(args.length==1) zip=new File(args[0]); else { System.out.println("Argument: zip-file of release"); System.exit(1); } File dPkg=new File("/tmp/endrov"); File dUsr=new File(dPkg,"usr"); //File dEtc=new File(dPkg,"etc"); File dShare=new File(dUsr,"share"); File dEndrov=new File(dShare,"endrov"); File dEndrovLibs=new File(dEndrov,"libs"); //File dMan=new File(dShare,"man/man1"); //File dMenu=new File(dShare,"menu"); File dControl=new File(dPkg,"DEBIAN"); File dZipTemp=new File("/tmp/unzip"); File dShareDoc=new File(dShare,"doc"); //File dSharePixmaps=new File(dShare,"pixmaps"); File dUsrBin=new File(dUsr,"bin"); //File dShareApplications=new File(dShare,"applications"); //File dEtcBash=new File(dEtc,"bash_completion.d"); File dRes=new File("util/debian"); File fUsrBinEndrov=new File(dUsrBin,"endrov"); //File fIcon=new File(dSharePixmaps,"endrov.xpm"); //File fUsrShareMenuEndrov=new File(dMenu,"endrov"); //File fUsrShareApplicationsEndrov=new File(dShareApplications,"endrov.desktop"); //Clean dirs if(dPkg.exists()) recursiveDelete(dPkg); if(dZipTemp.exists()) recursiveDelete(dZipTemp); //Make dirs dShare.mkdirs(); dControl.mkdirs(); dShareDoc.mkdirs(); //dMan.mkdirs(); //dMenu.mkdirs(); dUsrBin.mkdirs(); //dSharePixmaps.mkdirs(); //dShareApplications.mkdirs(); //Extract files System.out.println("unzipping "+zip.getPath()); dZipTemp.mkdirs(); Process proc=Runtime.getRuntime().exec(new String[]{"/usr/bin/unzip",zip.getPath(),"-d",dZipTemp.getPath()}); BufferedReader os=new BufferedReader(new InputStreamReader(proc.getInputStream())); while(os.readLine()!=null); proc.waitFor(); System.out.println("unzip done"); System.out.println("Moving into place, "+dZipTemp.listFiles()[0]+" ---> "+dEndrov); dZipTemp.listFiles()[0].renameTo(dEndrov); new File(dEndrov,"docs").renameTo(new File(dShareDoc,"endrov")); /*copyFile(new File(dRes,"endrov.1"), new File(dMan,"endrov.1")); copyFile(new File(dRes,"icon.xpm"), fIcon); copyFile(new File(dRes,"endrov.sh"),fUsrBinEndrov); copyFile(new File(dRes,"usrShareMenuEndrov"),fUsrShareMenuEndrov); copyFile(new File(dRes,"endrov.desktop"),fUsrShareApplicationsEndrov); copyFile(new File(dRes,"bash_completion"),new File(dEtcBash,"endrov"));*/ copyRecursive(new File(dRes,"root"), dPkg); setExec(fUsrBinEndrov); setExec(new File(dControl,"postinst")); setExec(new File(dControl,"postrm")); //fUsrEndrov.setExecutable(true); System.out.println("Cleaning out windows/mac specific files"); for(File f:dEndrov.listFiles()) if(f.getName().startsWith("libmmgr_dal") || f.getName().endsWith(".jnilib") || f.getName().endsWith(".dll") || f.getName().startsWith("hs_err")) f.delete(); System.out.println("Set up package dependencies"); //Packages //maybe do pattern match instead? List<DebPackage> pkgs=new LinkedList<DebPackage>(); pkgs.add(new DebPackage("java2-runtime",null,new String[]{"linux.paths"})); pkgs.add(new DebPackage("bsh",new String[]{"bsh-2.0b5.jar"},new String[]{"bsh-2.0b5.jar"}));
diff --git a/src/test/java/com/youdevise/test/narrative/GivenTest.java b/src/test/java/com/youdevise/test/narrative/GivenTest.java index e41626d..73ef11d 100644 --- a/src/test/java/com/youdevise/test/narrative/GivenTest.java +++ b/src/test/java/com/youdevise/test/narrative/GivenTest.java @@ -1,44 +1,44 @@ package com.youdevise.test.narrative; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.Sequence; import org.jmock.integration.junit4.JMock; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(JMock.class) public class GivenTest { private Mockery context = new Mockery(); @SuppressWarnings("unchecked") @Test public void usesTheActorToPerformTheAction() { final StringActor actor = context.mock(StringActor.class); final Action<String, StringActor> action = context.mock(Action.class); context.checking(new Expectations() {{ oneOf(actor).perform(action); }}); Given.the(actor).was_able_to(action); } @SuppressWarnings("unchecked") @Test public void - canPerformanManyActionsInARow() { + canPerformManyActionsInARow() { final StringActor actor = context.mock(StringActor.class); final Action<String, StringActor> action = context.mock(Action.class, "first action"); final Action<String, StringActor> otherAction = context.mock(Action.class, "second action"); final Sequence orderOfActions = context.sequence("Order of the actions"); context.checking(new Expectations() {{ oneOf(actor).perform(action); inSequence(orderOfActions); oneOf(actor).perform(otherAction); inSequence(orderOfActions); }}); Given.the(actor).was_able_to(action) .was_able_to(otherAction); } }
true
true
@Test public void canPerformanManyActionsInARow() { final StringActor actor = context.mock(StringActor.class); final Action<String, StringActor> action = context.mock(Action.class, "first action"); final Action<String, StringActor> otherAction = context.mock(Action.class, "second action"); final Sequence orderOfActions = context.sequence("Order of the actions"); context.checking(new Expectations() {{ oneOf(actor).perform(action); inSequence(orderOfActions); oneOf(actor).perform(otherAction); inSequence(orderOfActions); }}); Given.the(actor).was_able_to(action) .was_able_to(otherAction); }
@Test public void canPerformManyActionsInARow() { final StringActor actor = context.mock(StringActor.class); final Action<String, StringActor> action = context.mock(Action.class, "first action"); final Action<String, StringActor> otherAction = context.mock(Action.class, "second action"); final Sequence orderOfActions = context.sequence("Order of the actions"); context.checking(new Expectations() {{ oneOf(actor).perform(action); inSequence(orderOfActions); oneOf(actor).perform(otherAction); inSequence(orderOfActions); }}); Given.the(actor).was_able_to(action) .was_able_to(otherAction); }
diff --git a/bank-logic/src/main/java/com/midtrans/bank/logic/transaction/FindTransaction.java b/bank-logic/src/main/java/com/midtrans/bank/logic/transaction/FindTransaction.java index aae6339..de4ba0b 100644 --- a/bank-logic/src/main/java/com/midtrans/bank/logic/transaction/FindTransaction.java +++ b/bank-logic/src/main/java/com/midtrans/bank/logic/transaction/FindTransaction.java @@ -1,62 +1,62 @@ package com.midtrans.bank.logic.transaction; import com.midtrans.bank.core.model.Terminal; import com.midtrans.bank.core.model.Transaction; import com.midtrans.bank.core.model.VoidTxn; import com.midtrans.bank.core.transaction.BankTxnSupport; import com.midtrans.bank.logic.dao.impl.TransactionDao; import org.jpos.ee.DB; import org.jpos.transaction.Context; import java.util.Date; /** * Created with IntelliJ IDEA. * User: shaddiqa * Date: 9/6/13 * Time: 11:04 AM * To change this template use File | Settings | File Templates. */ public class FindTransaction extends BankTxnSupport { TransactionDao dao; @Override protected int doPrepare(long id, Context ctx) throws Exception { DB db = openDB(ctx); dao = new TransactionDao(db); String cardNumber = ctx.getString(CARD_NUMBER); Long amount = (Long) ctx.get(AMOUNT); String cardExpire = ctx.getString(CARD_EXPIRE); Terminal terminal = (Terminal) ctx.get(TERMINAL); String command = ctx.getString(COMMAND); Date txnTime = (Date) ctx.get(TXN_TIME); String referenceNumber = ctx.getString(REFERENCE_NUMBER); String responseCode = ctx.getString(RCODE); String batchNumber = ctx.getString(BATCH_NUMBER); Integer traceNumber = (Integer) ctx.get(TRACE_NUMBER); Transaction txn = null; - if("Void".equals(command)) { + if("void".equals(command)) { txn = dao.findBy(cardNumber, amount, cardExpire, terminal, txnTime, referenceNumber); - } else if ("BatchUpload".equals(command)) { + } else if ("batchupload".equals(command)) { txn = dao.findBy(cardNumber, amount, Integer.valueOf(batchNumber.substring(4,10)), cardExpire, terminal, txnTime, referenceNumber, responseCode); - } else if("ReversalSale".equals(command)) { + } else if("reversalsale".equals(command)) { txn = dao.findBy(cardNumber, amount, traceNumber, terminal); - } else if("ReversalVoid".equals(command)) { + } else if("reversalvoid".equals(command)) { VoidTxn voidTxn = (VoidTxn) ctx.get(VOID_TXN); txn = voidTxn.getTransaction(); } assertNotNull(txn, "12"); ctx.put(VALBEFORE, txn.calcSettleAmount()); ctx.put(TXN, txn); closeDB(ctx); return PREPARED | NO_JOIN; } }
false
true
protected int doPrepare(long id, Context ctx) throws Exception { DB db = openDB(ctx); dao = new TransactionDao(db); String cardNumber = ctx.getString(CARD_NUMBER); Long amount = (Long) ctx.get(AMOUNT); String cardExpire = ctx.getString(CARD_EXPIRE); Terminal terminal = (Terminal) ctx.get(TERMINAL); String command = ctx.getString(COMMAND); Date txnTime = (Date) ctx.get(TXN_TIME); String referenceNumber = ctx.getString(REFERENCE_NUMBER); String responseCode = ctx.getString(RCODE); String batchNumber = ctx.getString(BATCH_NUMBER); Integer traceNumber = (Integer) ctx.get(TRACE_NUMBER); Transaction txn = null; if("Void".equals(command)) { txn = dao.findBy(cardNumber, amount, cardExpire, terminal, txnTime, referenceNumber); } else if ("BatchUpload".equals(command)) { txn = dao.findBy(cardNumber, amount, Integer.valueOf(batchNumber.substring(4,10)), cardExpire, terminal, txnTime, referenceNumber, responseCode); } else if("ReversalSale".equals(command)) { txn = dao.findBy(cardNumber, amount, traceNumber, terminal); } else if("ReversalVoid".equals(command)) { VoidTxn voidTxn = (VoidTxn) ctx.get(VOID_TXN); txn = voidTxn.getTransaction(); } assertNotNull(txn, "12"); ctx.put(VALBEFORE, txn.calcSettleAmount()); ctx.put(TXN, txn); closeDB(ctx); return PREPARED | NO_JOIN; }
protected int doPrepare(long id, Context ctx) throws Exception { DB db = openDB(ctx); dao = new TransactionDao(db); String cardNumber = ctx.getString(CARD_NUMBER); Long amount = (Long) ctx.get(AMOUNT); String cardExpire = ctx.getString(CARD_EXPIRE); Terminal terminal = (Terminal) ctx.get(TERMINAL); String command = ctx.getString(COMMAND); Date txnTime = (Date) ctx.get(TXN_TIME); String referenceNumber = ctx.getString(REFERENCE_NUMBER); String responseCode = ctx.getString(RCODE); String batchNumber = ctx.getString(BATCH_NUMBER); Integer traceNumber = (Integer) ctx.get(TRACE_NUMBER); Transaction txn = null; if("void".equals(command)) { txn = dao.findBy(cardNumber, amount, cardExpire, terminal, txnTime, referenceNumber); } else if ("batchupload".equals(command)) { txn = dao.findBy(cardNumber, amount, Integer.valueOf(batchNumber.substring(4,10)), cardExpire, terminal, txnTime, referenceNumber, responseCode); } else if("reversalsale".equals(command)) { txn = dao.findBy(cardNumber, amount, traceNumber, terminal); } else if("reversalvoid".equals(command)) { VoidTxn voidTxn = (VoidTxn) ctx.get(VOID_TXN); txn = voidTxn.getTransaction(); } assertNotNull(txn, "12"); ctx.put(VALBEFORE, txn.calcSettleAmount()); ctx.put(TXN, txn); closeDB(ctx); return PREPARED | NO_JOIN; }
diff --git a/core/plugins/org.eclipse.dltk.core/model/org/eclipse/dltk/core/ScriptContentDescriber.java b/core/plugins/org.eclipse.dltk.core/model/org/eclipse/dltk/core/ScriptContentDescriber.java index c8b295b55..12324df9c 100644 --- a/core/plugins/org.eclipse.dltk.core/model/org/eclipse/dltk/core/ScriptContentDescriber.java +++ b/core/plugins/org.eclipse.dltk.core/model/org/eclipse/dltk/core/ScriptContentDescriber.java @@ -1,166 +1,168 @@ package org.eclipse.dltk.core; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.RandomAccessFile; import java.io.Reader; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.eclipse.core.runtime.QualifiedName; import org.eclipse.core.runtime.content.IContentDescription; import org.eclipse.core.runtime.content.ITextContentDescriber; public abstract class ScriptContentDescriber implements ITextContentDescriber { public static final QualifiedName DLTK_VALID = new QualifiedName( DLTKCore.PLUGIN_ID, "valid"); //$NON-NLS-1$ public static final Boolean TRUE = new Boolean(true); public static final Boolean FALSE = new Boolean(true); public QualifiedName[] getSupportedOptions() { return new QualifiedName[] { DLTK_VALID }; } private final static int BUFFER_LENGTH = 2 * 1024; private final static int HEADER_LENGTH = 4 * 1024; private final static int FOOTER_LENGTH = 4 * 1024; private static boolean checkHeader(File file, Pattern[] headerPatterns, Pattern[] footerPatterns) throws FileNotFoundException, IOException { FileInputStream reader = null; try { reader = new FileInputStream(file); byte buf[] = new byte[BUFFER_LENGTH + 1]; int res = reader.read(buf); if (res == -1 || res == 0) { return false; } String header = new String(buf); if (checkBufferForPatterns(header, headerPatterns)) { return true; } if (file.length() < BUFFER_LENGTH && footerPatterns != null) { if (checkBufferForPatterns(header, footerPatterns)) { return true; } } return false; } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { } } } } private static boolean checkFooter(File file, Pattern[] footerPatterns) throws FileNotFoundException, IOException { RandomAccessFile raFile = new RandomAccessFile(file, "r"); //$NON-NLS-1$ try { long len = BUFFER_LENGTH; long fileSize = raFile.length(); long offset = fileSize - len; if (offset < 0) { offset = 0; } raFile.seek(offset); byte buf[] = new byte[BUFFER_LENGTH + 1]; int code = raFile.read(buf); if (code != -1) { String content = new String(buf, 0, code); if (checkBufferForPatterns(content, footerPatterns)) { return true; } } return false; } finally { raFile.close(); } } private static boolean checkBufferForPatterns(CharSequence header, Pattern[] patterns) { if (patterns == null) { return false; } for (int i = 0; i < patterns.length; i++) { Matcher m = patterns[i].matcher(header); if (m.find()) { return true; } } return false; } public static boolean checkPatterns(File file, Pattern[] headerPatterns, Pattern[] footerPatterns) { try { if (checkHeader(file, headerPatterns, footerPatterns)) { return true; } if (footerPatterns != null && file.length() > BUFFER_LENGTH && checkFooter(file, footerPatterns)) { return true; } } catch (FileNotFoundException e) { return false; } catch (IOException e) { return false; } return false; } public static boolean checkPatterns(Reader stream, Pattern[] headerPatterns, Pattern[] footerPatterns) { BufferedReader reader = new BufferedReader(stream); StringBuffer buffer = new StringBuffer(); + char buff[] = new char[8096]; while (true) { try { - String line = reader.readLine(); - buffer.append(line).append("\n"); //$NON-NLS-1$ - if (line == null) { + int len = reader.read(buff); + if (len != -1) { + buffer.append(buff, 0, len); + } else { break; } } catch (IOException e) { if (DLTKCore.DEBUG) { e.printStackTrace(); } break; } } String content = buffer.toString(); String header = content; if (header.length() > HEADER_LENGTH) { header = header.substring(0, HEADER_LENGTH); } String footer = content; if (footer.length() > FOOTER_LENGTH) { footer = footer.substring(footer.length() - FOOTER_LENGTH, footer .length() - 1); } if (checkBufferForPatterns(header, headerPatterns)) { return true; } if (checkBufferForPatterns(footer, footerPatterns)) { return true; } return false; } public int describe(InputStream contents, IContentDescription description) throws IOException { return describe(new InputStreamReader(contents), description); } }
false
true
public static boolean checkPatterns(Reader stream, Pattern[] headerPatterns, Pattern[] footerPatterns) { BufferedReader reader = new BufferedReader(stream); StringBuffer buffer = new StringBuffer(); while (true) { try { String line = reader.readLine(); buffer.append(line).append("\n"); //$NON-NLS-1$ if (line == null) { break; } } catch (IOException e) { if (DLTKCore.DEBUG) { e.printStackTrace(); } break; } } String content = buffer.toString(); String header = content; if (header.length() > HEADER_LENGTH) { header = header.substring(0, HEADER_LENGTH); } String footer = content; if (footer.length() > FOOTER_LENGTH) { footer = footer.substring(footer.length() - FOOTER_LENGTH, footer .length() - 1); } if (checkBufferForPatterns(header, headerPatterns)) { return true; } if (checkBufferForPatterns(footer, footerPatterns)) { return true; } return false; }
public static boolean checkPatterns(Reader stream, Pattern[] headerPatterns, Pattern[] footerPatterns) { BufferedReader reader = new BufferedReader(stream); StringBuffer buffer = new StringBuffer(); char buff[] = new char[8096]; while (true) { try { int len = reader.read(buff); if (len != -1) { buffer.append(buff, 0, len); } else { break; } } catch (IOException e) { if (DLTKCore.DEBUG) { e.printStackTrace(); } break; } } String content = buffer.toString(); String header = content; if (header.length() > HEADER_LENGTH) { header = header.substring(0, HEADER_LENGTH); } String footer = content; if (footer.length() > FOOTER_LENGTH) { footer = footer.substring(footer.length() - FOOTER_LENGTH, footer .length() - 1); } if (checkBufferForPatterns(header, headerPatterns)) { return true; } if (checkBufferForPatterns(footer, footerPatterns)) { return true; } return false; }
diff --git a/netbout/netbout-rest/src/main/java/com/netbout/rest/auth/NbRs.java b/netbout/netbout-rest/src/main/java/com/netbout/rest/auth/NbRs.java index f1228ccfc..ff32ab3e2 100644 --- a/netbout/netbout-rest/src/main/java/com/netbout/rest/auth/NbRs.java +++ b/netbout/netbout-rest/src/main/java/com/netbout/rest/auth/NbRs.java @@ -1,126 +1,131 @@ /** * Copyright (c) 2009-2012, Netbout.com * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are PROHIBITED without prior written permission from * the author. This product may NOT be used anywhere and on any computer * except the server platform of netBout Inc. located at www.netbout.com. * Federal copyright law prohibits unauthorized reproduction by any means * and imposes fines up to $25,000 for violation. If you received * this code occasionally and without intent to use it, please report this * incident to the author by email. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ package com.netbout.rest.auth; import com.netbout.rest.BaseRs; import com.netbout.rest.LoginRequiredException; import com.netbout.rest.NbPage; import com.netbout.spi.Identity; import com.netbout.spi.Urn; import com.netbout.spi.text.SecureString; import com.rexsl.page.PageBuilder; import java.net.URL; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; /** * Authorizer of "urn:netbout:..." identities. * * @author Yegor Bugayenko ([email protected]) * @version $Id$ */ @Path("/nb") public final class NbRs extends BaseRs { /** * Authentication page. * @param iname Name of identity * @param secret The secret code * @return The JAX-RS response * @todo #158 Path annotation: http://java.net/jira/browse/JERSEY-739 */ @GET @Path("/") public Response auth(@QueryParam("identity") final Urn iname, @QueryParam("secret") final String secret) { return new PageBuilder() .build(NbPage.class) .init(this) .render() .authenticated(this.authenticate(iname, secret)) .build(); } /** * Validate them. * @param iname Name of identity * @param secret The secret code * @return The identity just authenticated */ private Identity authenticate(final Urn iname, final String secret) { if ((iname == null) || (secret == null)) { throw new LoginRequiredException( this, "Both 'identity' and 'secret' query params are mandatory" ); } if (!"netbout".equals(iname.nid())) { throw new LoginRequiredException( this, String.format("Bad namespace '%s' in '%s'", iname.nid(), iname) ); } if (!iname.nss().matches("[a-z]{2,32}")) { throw new LoginRequiredException( this, String.format("Invalid name '%s' in '%s'", iname.nss(), iname) ); } try { if (!SecureString.valueOf(secret).text().equals(iname.toString())) { throw new LoginRequiredException( this, - String.format("Wrong secret '%s' for '%s'", secret, iname) + String.format( + "Wrong secret '%s' (%s) for '%s'", + secret, + SecureString.valueOf(secret).text(), + iname + ) ); } } catch (com.netbout.spi.text.StringDecryptionException ex) { throw new LoginRequiredException(this, ex); } Identity identity; try { identity = new ResolvedIdentity( this.base().path("/nb").build().toURL(), iname ); identity.profile().setPhoto( new URL( String.format( "http://cdn.netbout.com/nb/%s.png", iname.nss() ) ) ); } catch (java.net.MalformedURLException ex) { throw new IllegalArgumentException(ex); } identity.profile().alias(iname.nss()); return identity; } }
true
true
private Identity authenticate(final Urn iname, final String secret) { if ((iname == null) || (secret == null)) { throw new LoginRequiredException( this, "Both 'identity' and 'secret' query params are mandatory" ); } if (!"netbout".equals(iname.nid())) { throw new LoginRequiredException( this, String.format("Bad namespace '%s' in '%s'", iname.nid(), iname) ); } if (!iname.nss().matches("[a-z]{2,32}")) { throw new LoginRequiredException( this, String.format("Invalid name '%s' in '%s'", iname.nss(), iname) ); } try { if (!SecureString.valueOf(secret).text().equals(iname.toString())) { throw new LoginRequiredException( this, String.format("Wrong secret '%s' for '%s'", secret, iname) ); } } catch (com.netbout.spi.text.StringDecryptionException ex) { throw new LoginRequiredException(this, ex); } Identity identity; try { identity = new ResolvedIdentity( this.base().path("/nb").build().toURL(), iname ); identity.profile().setPhoto( new URL( String.format( "http://cdn.netbout.com/nb/%s.png", iname.nss() ) ) ); } catch (java.net.MalformedURLException ex) { throw new IllegalArgumentException(ex); } identity.profile().alias(iname.nss()); return identity; }
private Identity authenticate(final Urn iname, final String secret) { if ((iname == null) || (secret == null)) { throw new LoginRequiredException( this, "Both 'identity' and 'secret' query params are mandatory" ); } if (!"netbout".equals(iname.nid())) { throw new LoginRequiredException( this, String.format("Bad namespace '%s' in '%s'", iname.nid(), iname) ); } if (!iname.nss().matches("[a-z]{2,32}")) { throw new LoginRequiredException( this, String.format("Invalid name '%s' in '%s'", iname.nss(), iname) ); } try { if (!SecureString.valueOf(secret).text().equals(iname.toString())) { throw new LoginRequiredException( this, String.format( "Wrong secret '%s' (%s) for '%s'", secret, SecureString.valueOf(secret).text(), iname ) ); } } catch (com.netbout.spi.text.StringDecryptionException ex) { throw new LoginRequiredException(this, ex); } Identity identity; try { identity = new ResolvedIdentity( this.base().path("/nb").build().toURL(), iname ); identity.profile().setPhoto( new URL( String.format( "http://cdn.netbout.com/nb/%s.png", iname.nss() ) ) ); } catch (java.net.MalformedURLException ex) { throw new IllegalArgumentException(ex); } identity.profile().alias(iname.nss()); return identity; }
diff --git a/library/src/de/passsy/holocircularprogressbar/HoloCircularProgressBar.java b/library/src/de/passsy/holocircularprogressbar/HoloCircularProgressBar.java index d24993e..603da16 100644 --- a/library/src/de/passsy/holocircularprogressbar/HoloCircularProgressBar.java +++ b/library/src/de/passsy/holocircularprogressbar/HoloCircularProgressBar.java @@ -1,509 +1,509 @@ /** * */ package de.passsy.holocircularprogressbar; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RectF; import android.os.Build; import android.os.Bundle; import android.os.Parcelable; import android.util.AttributeSet; import android.view.Gravity; import android.view.View; /** * The Class HoloCircularProgressBar. * * @author Pascal.Welsch * @since 05.03.2013 */ public class HoloCircularProgressBar extends View { /** * The Constant TAG. */ private static final String TAG = "CircularProgressBar"; /** * used to save the super state on configuration change */ private static final String INSTNACE_STATE_SAVEDSTATE = "saved_state"; /** * used to save the progress on configuration changes */ private static final String INSTNACE_STATE_PROGRESS = "progress"; /** * used to save the marker progress on configuration changes */ private static final String INSTNACE_STATE_MARKER_PROGRESS = "marker_progress"; /** * true if not all properties are set. then the view isn't drawn and there * are no errors in the LayoutEditor */ private boolean mIsInitializing = true; /** * the paint for the background. */ private Paint mBackgroundColorPaint = new Paint(); /** * The stroke width used to paint the circle. */ private int mCircleStrokeWidth = 10; /** * The pointer width (in pixels). */ private int mThumbRadius = 20; /** * The rectangle enclosing the circle. */ private final RectF mCircleBounds = new RectF(); /** * Radius of the circle * * <p> * Note: (Re)calculated in {@link #onMeasure(int, int)}. * </p> */ private float mRadius; /** * the color of the progress. */ private int mProgressColor; /** * paint for the progress. */ private final Paint mProgressColorPaint; /** * The color of the progress background. */ private int mProgressBackgroundColor; /** * The current progress. */ private float mProgress = 0.3f; /** * The Thumb color paint. */ private Paint mThumbColorPaint = new Paint(); /** * The Marker progress. */ private float mMarkerProgress = 0.0f; /** * The Marker color paint. */ private final Paint mMarkerColorPaint; /** * flag if the marker should be visible */ private boolean mIsMarkerEnabled = false; /** * The gravity of the view. Where should the Circle be drawn within the * given bounds * * {@link #computeInsets(int, int)} */ private final int mGravity; /** * The Horizontal inset calcualted in {@link #computeInsets(int, int)} * depends on {@link #mGravity}. */ private int mHorizontalInset = 0; /** * The Vertical inset calcualted in {@link #computeInsets(int, int)} depends * on {@link #mGravity}.. */ private int mVerticalInset = 0; /** * The Translation offset x which gives us the ability to use our own * coordinates system. */ private float mTranslationOffsetX; /** * The Translation offset y which gives us the ability to use our own * coordinates system. */ private float mTranslationOffsetY; /** * The Thumb pos x. * * Care. the position is not the position of the rotated thumb. The position * is only calculated in {@link #onMeasure(int, int)} */ private float mThumbPosX; /** * The Thumb pos y. * * Care. the position is not the position of the rotated thumb. The position * is only calculated in {@link #onMeasure(int, int)} */ private float mThumbPosY; /** * the overdraw is true if the progress is over 1.0. * */ private boolean mOverrdraw = false; /** * Instantiates a new holo circular progress bar. * * @param context * the context */ public HoloCircularProgressBar(final Context context) { this(context, null); } /** * Instantiates a new holo circular progress bar. * * @param context * the context * @param attrs * the attrs */ public HoloCircularProgressBar(final Context context, final AttributeSet attrs) { this(context, attrs, R.attr.circularProgressBarStyle); } /** * Instantiates a new holo circular progress bar. * * @param context * the context * @param attrs * the attrs * @param defStyle * the def style */ public HoloCircularProgressBar(final Context context, final AttributeSet attrs, final int defStyle) { super(context, attrs, defStyle); // load the styled attributes and set their properties final TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.HoloCircularProgressBar, defStyle, 0); setProgressColor(attributes.getColor(R.styleable.HoloCircularProgressBar_progress_color, Color.CYAN)); setProgressBackgroundColor(attributes.getColor(R.styleable.HoloCircularProgressBar_progress_background_color, Color.MAGENTA)); setProgress(attributes.getFloat(R.styleable.HoloCircularProgressBar_progress, 0.0f)); setMarkerProgress(attributes.getFloat(R.styleable.HoloCircularProgressBar_marker_progress, 0.0f)); setWheelSize((int) attributes.getDimension(R.styleable.HoloCircularProgressBar_stroke_width, 10)); - mGravity = attributes.getInt(R.styleable.HoloCircularProgressBar_gravity, Gravity.CENTER); + mGravity = attributes.getInt(R.styleable.HoloCircularProgressBar_android_gravity, Gravity.CENTER); attributes.recycle(); mThumbRadius = mCircleStrokeWidth * 2; mBackgroundColorPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mBackgroundColorPaint.setColor(mProgressBackgroundColor); mBackgroundColorPaint.setStyle(Paint.Style.STROKE); mBackgroundColorPaint.setStrokeWidth(mCircleStrokeWidth); mMarkerColorPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mMarkerColorPaint.setColor(mProgressBackgroundColor); mMarkerColorPaint.setStyle(Paint.Style.STROKE); mMarkerColorPaint.setStrokeWidth(mCircleStrokeWidth / 2); mProgressColorPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mProgressColorPaint.setColor(mProgressColor); mProgressColorPaint.setStyle(Paint.Style.STROKE); mProgressColorPaint.setStrokeWidth(mCircleStrokeWidth); mThumbColorPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mThumbColorPaint.setColor(mProgressColor); mThumbColorPaint.setStyle(Paint.Style.FILL_AND_STROKE); mThumbColorPaint.setStrokeWidth(mCircleStrokeWidth); // the view has now all properties and can be drawn mIsInitializing = false; } /* (non-Javadoc) * @see android.view.View#onDraw(android.graphics.Canvas) */ @Override protected void onDraw(final Canvas canvas) { // All of our positions are using our internal coordinate system. // Instead of translating // them we let Canvas do the work for us. canvas.translate(mTranslationOffsetX, mTranslationOffsetY); final float progressRotation = getCurrentRotation(); // draw the background if (!mOverrdraw) { canvas.drawArc(mCircleBounds, 270, -(360 - progressRotation), false, mBackgroundColorPaint); } // draw the progress or a full circle if overdraw is true canvas.drawArc(mCircleBounds, 270, mOverrdraw ? 360 : progressRotation, false, mProgressColorPaint); // draw the marker at the correct rotated position if (mIsMarkerEnabled) { final float markerRotation = getMarkerRotation(); canvas.save(); canvas.rotate(markerRotation - 90); canvas.drawLine((float) (mThumbPosX + mThumbRadius / 2 * 1.4), mThumbPosY, (float) (mThumbPosX - mThumbRadius / 2 * 1.4), mThumbPosY, mMarkerColorPaint); canvas.restore(); } // draw the thumb square at the correct rotated position canvas.save(); canvas.rotate(progressRotation - 90); // rotate the square by 45 degrees canvas.rotate(45, mThumbPosX, mThumbPosY); final RectF rect = new RectF(); rect.left = mThumbPosX - mThumbRadius / 3; rect.right = mThumbPosX + mThumbRadius / 3; rect.top = mThumbPosY - mThumbRadius / 3; rect.bottom = mThumbPosY + mThumbRadius / 3; canvas.drawRect(rect, mThumbColorPaint); canvas.restore(); } /* (non-Javadoc) * @see android.view.View#onMeasure(int, int) */ @Override protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) { final int height = getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec); final int width = getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec); final int min = Math.min(width, height); setMeasuredDimension(min, height); final float halfWidth = min * 0.5f; mRadius = halfWidth - mThumbRadius; mCircleBounds.set(-mRadius, -mRadius, mRadius, mRadius); mThumbPosX = (float) (mRadius * Math.cos(0)); mThumbPosY = (float) (mRadius * Math.sin(0)); computeInsets(width - min, height - min); mTranslationOffsetX = halfWidth + mHorizontalInset; mTranslationOffsetY = halfWidth + mVerticalInset; } /* (non-Javadoc) * @see android.view.View#onRestoreInstanceState(android.os.Parcelable) */ @Override protected void onRestoreInstanceState(final Parcelable state) { if (state instanceof Bundle) { final Bundle bundle = (Bundle) state; setProgress(bundle.getFloat(INSTNACE_STATE_PROGRESS)); setMarkerProgress(bundle.getFloat(INSTNACE_STATE_MARKER_PROGRESS)); super.onRestoreInstanceState(bundle.getParcelable(INSTNACE_STATE_SAVEDSTATE)); return; } super.onRestoreInstanceState(state); } /* (non-Javadoc) * @see android.view.View#onSaveInstanceState() */ @Override protected Parcelable onSaveInstanceState() { final Bundle bundle = new Bundle(); bundle.putParcelable(INSTNACE_STATE_SAVEDSTATE, super.onSaveInstanceState()); bundle.putFloat(INSTNACE_STATE_PROGRESS, mProgress); bundle.putFloat(INSTNACE_STATE_MARKER_PROGRESS, mMarkerProgress); return bundle; } /** * Compute insets. * _______________________ * |_________dx/2_________| * |......|.�''''`.|......| * |-dx/2-|| View ||-dx/2-| * |______|`.____.�|______| * |________ dx/2_________| * * @param dx * the dx the horizontal unfilled space * @param dy * the dy the horizontal unfilled space */ private void computeInsets(final int dx, final int dy) { final int layoutDirection; int absoluteGravity = mGravity; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { layoutDirection = getLayoutDirection(); absoluteGravity = Gravity.getAbsoluteGravity(mGravity, layoutDirection); } switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) { case Gravity.LEFT: mHorizontalInset = 0; break; case Gravity.RIGHT: mHorizontalInset = dx; break; case Gravity.CENTER_HORIZONTAL: default: mHorizontalInset = dx / 2; break; } switch (absoluteGravity & Gravity.VERTICAL_GRAVITY_MASK) { case Gravity.TOP: mVerticalInset = 0; break; case Gravity.BOTTOM: mVerticalInset = dy; break; case Gravity.CENTER_VERTICAL: default: mVerticalInset = dy / 2; break; } } /** * Gets the current rotation. * * @return the current rotation */ private float getCurrentRotation() { return 360 * mProgress; } /** * Gets the marker rotation. * * @return the marker rotation */ private float getMarkerRotation() { return 360 * mMarkerProgress; } /** * Sets the progress background color. * * @param color * the new progress background color */ private void setProgressBackgroundColor(final int color) { mProgressBackgroundColor = color; } /** * Sets the progress color. * * @param color * the new progress color */ private void setProgressColor(final int color) { mProgressColor = color; } /** * Sets the wheel size. * * @param dimension * the new wheel size */ private void setWheelSize(final int dimension) { mCircleStrokeWidth = dimension; } public float getMarkerProgress() { return mMarkerProgress; } public float getProgress() { return mProgress; } /** * Gets the progress color. * * @return the progress color */ public int getProgressColor() { return mProgressColor; } /** * Sets the marker enabled. * * @param enabled * the new marker enabled */ public void setMarkerEnabled(final boolean enabled) { mIsMarkerEnabled = enabled; } /** * Sets the marker progress. * * @param progress * the new marker progress */ public void setMarkerProgress(final float progress) { mIsMarkerEnabled = true; mMarkerProgress = progress; } /** * Sets the progress. * * @param progress * the new progress */ public void setProgress(final float progress) { if (progress == mProgress) { return; } mProgress = progress % 1.0f; if (progress >= 1) { mOverrdraw = true; } else { mOverrdraw = false; } if (!mIsInitializing) { invalidate(); } } }
true
true
public HoloCircularProgressBar(final Context context, final AttributeSet attrs, final int defStyle) { super(context, attrs, defStyle); // load the styled attributes and set their properties final TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.HoloCircularProgressBar, defStyle, 0); setProgressColor(attributes.getColor(R.styleable.HoloCircularProgressBar_progress_color, Color.CYAN)); setProgressBackgroundColor(attributes.getColor(R.styleable.HoloCircularProgressBar_progress_background_color, Color.MAGENTA)); setProgress(attributes.getFloat(R.styleable.HoloCircularProgressBar_progress, 0.0f)); setMarkerProgress(attributes.getFloat(R.styleable.HoloCircularProgressBar_marker_progress, 0.0f)); setWheelSize((int) attributes.getDimension(R.styleable.HoloCircularProgressBar_stroke_width, 10)); mGravity = attributes.getInt(R.styleable.HoloCircularProgressBar_gravity, Gravity.CENTER); attributes.recycle(); mThumbRadius = mCircleStrokeWidth * 2; mBackgroundColorPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mBackgroundColorPaint.setColor(mProgressBackgroundColor); mBackgroundColorPaint.setStyle(Paint.Style.STROKE); mBackgroundColorPaint.setStrokeWidth(mCircleStrokeWidth); mMarkerColorPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mMarkerColorPaint.setColor(mProgressBackgroundColor); mMarkerColorPaint.setStyle(Paint.Style.STROKE); mMarkerColorPaint.setStrokeWidth(mCircleStrokeWidth / 2); mProgressColorPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mProgressColorPaint.setColor(mProgressColor); mProgressColorPaint.setStyle(Paint.Style.STROKE); mProgressColorPaint.setStrokeWidth(mCircleStrokeWidth); mThumbColorPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mThumbColorPaint.setColor(mProgressColor); mThumbColorPaint.setStyle(Paint.Style.FILL_AND_STROKE); mThumbColorPaint.setStrokeWidth(mCircleStrokeWidth); // the view has now all properties and can be drawn mIsInitializing = false; }
public HoloCircularProgressBar(final Context context, final AttributeSet attrs, final int defStyle) { super(context, attrs, defStyle); // load the styled attributes and set their properties final TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.HoloCircularProgressBar, defStyle, 0); setProgressColor(attributes.getColor(R.styleable.HoloCircularProgressBar_progress_color, Color.CYAN)); setProgressBackgroundColor(attributes.getColor(R.styleable.HoloCircularProgressBar_progress_background_color, Color.MAGENTA)); setProgress(attributes.getFloat(R.styleable.HoloCircularProgressBar_progress, 0.0f)); setMarkerProgress(attributes.getFloat(R.styleable.HoloCircularProgressBar_marker_progress, 0.0f)); setWheelSize((int) attributes.getDimension(R.styleable.HoloCircularProgressBar_stroke_width, 10)); mGravity = attributes.getInt(R.styleable.HoloCircularProgressBar_android_gravity, Gravity.CENTER); attributes.recycle(); mThumbRadius = mCircleStrokeWidth * 2; mBackgroundColorPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mBackgroundColorPaint.setColor(mProgressBackgroundColor); mBackgroundColorPaint.setStyle(Paint.Style.STROKE); mBackgroundColorPaint.setStrokeWidth(mCircleStrokeWidth); mMarkerColorPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mMarkerColorPaint.setColor(mProgressBackgroundColor); mMarkerColorPaint.setStyle(Paint.Style.STROKE); mMarkerColorPaint.setStrokeWidth(mCircleStrokeWidth / 2); mProgressColorPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mProgressColorPaint.setColor(mProgressColor); mProgressColorPaint.setStyle(Paint.Style.STROKE); mProgressColorPaint.setStrokeWidth(mCircleStrokeWidth); mThumbColorPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mThumbColorPaint.setColor(mProgressColor); mThumbColorPaint.setStyle(Paint.Style.FILL_AND_STROKE); mThumbColorPaint.setStrokeWidth(mCircleStrokeWidth); // the view has now all properties and can be drawn mIsInitializing = false; }
diff --git a/src/gov/nih/nci/rembrandt/web/helper/RembrandtImageFileHandler.java b/src/gov/nih/nci/rembrandt/web/helper/RembrandtImageFileHandler.java index 10bfdfc8..6b3d583a 100755 --- a/src/gov/nih/nci/rembrandt/web/helper/RembrandtImageFileHandler.java +++ b/src/gov/nih/nci/rembrandt/web/helper/RembrandtImageFileHandler.java @@ -1,121 +1,121 @@ package gov.nih.nci.rembrandt.web.helper; import java.io.File; import org.apache.log4j.Logger; import gov.nih.nci.caintegrator.ui.graphing.util.FileDeleter; import gov.nih.nci.rembrandt.cache.RembrandtContextListener; /** * This class handles image files for the rembrandt application. Since this * effort should be application specific, it is named RembrandtImageFileHandler. * When given a user session, and image extension, and an image size, it will * creat all the necessary strings and directories for handling dynamically * created images for the application. * * @author DBauer * */ public class RembrandtImageFileHandler { private String URLPath; private String chartName; //default values private int imageHeight = 400; private int imageWidth = 600; //The specific temp directory for the application private static String tempDir = ""; private static Logger logger = Logger.getLogger(RembrandtImageFileHandler.class); public RembrandtImageFileHandler(String userSessionId,String imageTypeExtension, int width, int height) { if(tempDir.equals("")) { /** * TOTAL HACK! Since I am not sure how to handle dynamic * image content when running in a compressed war I am grabbing * the temp directory from JBoss and walking through the directories * until I either find the expanded Rembrandt war or nothing. This is * always assuming that I am running in JBoss for now (but should be moved * out later). If the expanded archive is not found, then it just sets * the temp directory to the Context. */ String jbossTempDirPath = System.getProperty("jboss.server.temp.dir"); String jbossTempDeployDirPath = jbossTempDirPath+"/deploy/"; File directory = new File(jbossTempDeployDirPath); String[] list = directory.list(); File[] fileList = directory.listFiles(); for(File file:fileList) { if(file.isDirectory()) { if(file.getName().contains("rembrandt")&&file.getName().contains(".war")){ tempDir = file.getPath(); break; } } } if(tempDir.equals("")) { tempDir = RembrandtContextListener.getContextPath(); } } if(width!=0&&height!=0) { imageWidth = width; imageHeight = height; } //Path that will be used in the <img /> tag without the file name - URLPath = "\\images\\"+userSessionId+"\\"; + URLPath = "images\\"+userSessionId+"\\"; //the actual unique chart name chartName = createUniqueChartName(imageTypeExtension); /* * Creates the session image temp folder if the * folder does not already exist */ File dir = new File(getSessionWebAppImagePath()); boolean dirCreated = dir.mkdir(); /* * Cleans out the session image temp folder if it did already * exist. However, because of threading issues it appears to work * intermitently, but it does work. */ if(!dirCreated) { FileDeleter fd = new FileDeleter(); //This could probably be a * but I am not sure just yet, need to test //fd.deleteFiles(getSessionWebAppImagePath(), imageTypeExtension); } } public String createUniqueChartName(String extension) { double time = (double)System.currentTimeMillis(); double random = (1-Math.random()); String one = String.valueOf(random*time); String finalAnswer = one.substring(10); return finalAnswer+"."+extension; } public String createUniqueMapName() { double time = (double)System.currentTimeMillis(); double random = (1-Math.random()); String one = String.valueOf(random*time); String finalAnswer = one.substring(10); return finalAnswer; } /** * @return Returns the uRLPath. */ public String getURLPath() { return URLPath; } public String getSessionWebAppImagePath() { return tempDir+URLPath; } public String getFinalPath() { // TODO Auto-generated method stub return getSessionWebAppImagePath() + chartName; } public String getFinalURLPath() { return URLPath+chartName; } public String getImageTag() { return "<img src=\""+getFinalURLPath()+"\" width="+imageWidth+" height="+imageHeight+" border=0>"; } public String getImageTag(String mapFileName){ return "<img src=\""+getFinalURLPath()+"\" usemap=\"#"+mapFileName + "\"" + "id=\"geneChart\"" + " border=0>"; } }
true
true
public RembrandtImageFileHandler(String userSessionId,String imageTypeExtension, int width, int height) { if(tempDir.equals("")) { /** * TOTAL HACK! Since I am not sure how to handle dynamic * image content when running in a compressed war I am grabbing * the temp directory from JBoss and walking through the directories * until I either find the expanded Rembrandt war or nothing. This is * always assuming that I am running in JBoss for now (but should be moved * out later). If the expanded archive is not found, then it just sets * the temp directory to the Context. */ String jbossTempDirPath = System.getProperty("jboss.server.temp.dir"); String jbossTempDeployDirPath = jbossTempDirPath+"/deploy/"; File directory = new File(jbossTempDeployDirPath); String[] list = directory.list(); File[] fileList = directory.listFiles(); for(File file:fileList) { if(file.isDirectory()) { if(file.getName().contains("rembrandt")&&file.getName().contains(".war")){ tempDir = file.getPath(); break; } } } if(tempDir.equals("")) { tempDir = RembrandtContextListener.getContextPath(); } } if(width!=0&&height!=0) { imageWidth = width; imageHeight = height; } //Path that will be used in the <img /> tag without the file name URLPath = "\\images\\"+userSessionId+"\\"; //the actual unique chart name chartName = createUniqueChartName(imageTypeExtension); /* * Creates the session image temp folder if the * folder does not already exist */ File dir = new File(getSessionWebAppImagePath()); boolean dirCreated = dir.mkdir(); /* * Cleans out the session image temp folder if it did already * exist. However, because of threading issues it appears to work * intermitently, but it does work. */ if(!dirCreated) { FileDeleter fd = new FileDeleter(); //This could probably be a * but I am not sure just yet, need to test //fd.deleteFiles(getSessionWebAppImagePath(), imageTypeExtension); } }
public RembrandtImageFileHandler(String userSessionId,String imageTypeExtension, int width, int height) { if(tempDir.equals("")) { /** * TOTAL HACK! Since I am not sure how to handle dynamic * image content when running in a compressed war I am grabbing * the temp directory from JBoss and walking through the directories * until I either find the expanded Rembrandt war or nothing. This is * always assuming that I am running in JBoss for now (but should be moved * out later). If the expanded archive is not found, then it just sets * the temp directory to the Context. */ String jbossTempDirPath = System.getProperty("jboss.server.temp.dir"); String jbossTempDeployDirPath = jbossTempDirPath+"/deploy/"; File directory = new File(jbossTempDeployDirPath); String[] list = directory.list(); File[] fileList = directory.listFiles(); for(File file:fileList) { if(file.isDirectory()) { if(file.getName().contains("rembrandt")&&file.getName().contains(".war")){ tempDir = file.getPath(); break; } } } if(tempDir.equals("")) { tempDir = RembrandtContextListener.getContextPath(); } } if(width!=0&&height!=0) { imageWidth = width; imageHeight = height; } //Path that will be used in the <img /> tag without the file name URLPath = "images\\"+userSessionId+"\\"; //the actual unique chart name chartName = createUniqueChartName(imageTypeExtension); /* * Creates the session image temp folder if the * folder does not already exist */ File dir = new File(getSessionWebAppImagePath()); boolean dirCreated = dir.mkdir(); /* * Cleans out the session image temp folder if it did already * exist. However, because of threading issues it appears to work * intermitently, but it does work. */ if(!dirCreated) { FileDeleter fd = new FileDeleter(); //This could probably be a * but I am not sure just yet, need to test //fd.deleteFiles(getSessionWebAppImagePath(), imageTypeExtension); } }
diff --git a/org.caleydo.view.tourguide/src/org/caleydo/view/tourguide/internal/stratomex/AddWizardElement.java b/org.caleydo.view.tourguide/src/org/caleydo/view/tourguide/internal/stratomex/AddWizardElement.java index 2c06b8b23..bf32544e3 100644 --- a/org.caleydo.view.tourguide/src/org/caleydo/view/tourguide/internal/stratomex/AddWizardElement.java +++ b/org.caleydo.view.tourguide/src/org/caleydo/view/tourguide/internal/stratomex/AddWizardElement.java @@ -1,284 +1,286 @@ /******************************************************************************* * Caleydo - visualization for molecular biology - http://caleydo.org * * Copyright(C) 2005, 2012 Graz University of Technology, Marc Streit, Alexander * Lex, Christian Partl, Johannes Kepler University Linz </p> * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/> *******************************************************************************/ package org.caleydo.view.tourguide.internal.stratomex; import java.util.Collection; import java.util.List; import javax.media.opengl.GL2; import org.caleydo.core.data.perspective.table.TablePerspective; import org.caleydo.core.data.virtualarray.group.Group; import org.caleydo.core.event.EventListenerManager.DeepScan; import org.caleydo.core.event.EventPublisher; import org.caleydo.core.io.gui.dataimport.widget.ICallback; import org.caleydo.core.util.base.ILabeled; import org.caleydo.core.util.collection.Pair; import org.caleydo.core.view.opengl.canvas.AGLView; import org.caleydo.core.view.opengl.canvas.PixelGLConverter; import org.caleydo.core.view.opengl.layout.ALayoutRenderer; import org.caleydo.core.view.opengl.layout.Column.VAlign; import org.caleydo.core.view.opengl.layout.util.multiform.MultiFormRenderer; import org.caleydo.core.view.opengl.layout2.GLContextLocal; import org.caleydo.core.view.opengl.layout2.GLGraphics; import org.caleydo.core.view.opengl.picking.Pick; import org.caleydo.core.view.opengl.util.text.TextUtils; import org.caleydo.view.stratomex.brick.configurer.IBrickConfigurer; import org.caleydo.view.stratomex.tourguide.AAddWizardElement; import org.caleydo.view.stratomex.tourguide.IStratomexAdapter; import org.caleydo.view.stratomex.tourguide.event.UpdateNumericalPreviewEvent; import org.caleydo.view.stratomex.tourguide.event.UpdatePathwayPreviewEvent; import org.caleydo.view.stratomex.tourguide.event.UpdateStratificationPreviewEvent; import org.caleydo.view.tourguide.api.query.EDataDomainQueryMode; import org.caleydo.view.tourguide.api.state.ABrowseState; import org.caleydo.view.tourguide.api.state.ISelectGroupState; import org.caleydo.view.tourguide.api.state.ISelectReaction; import org.caleydo.view.tourguide.api.state.ISelectStratificationState; import org.caleydo.view.tourguide.api.state.IState; import org.caleydo.view.tourguide.api.state.ITransition; import org.caleydo.view.tourguide.internal.Activator; import org.caleydo.view.tourguide.internal.OpenViewHandler; import org.caleydo.view.tourguide.internal.RcpGLTourGuideView; import org.caleydo.view.tourguide.internal.event.AddScoreColumnEvent; import org.caleydo.view.tourguide.internal.score.ScoreFactories; import org.caleydo.view.tourguide.internal.stratomex.event.WizardEndedEvent; import org.caleydo.view.tourguide.internal.view.GLTourGuideView; import org.caleydo.view.tourguide.spi.score.IScore; /** * @author Samuel Gratzl * */ public class AddWizardElement extends AAddWizardElement implements ICallback<IState>, ISelectReaction { @DeepScan private StateMachineImpl stateMachine; private final AGLView view; private GLContextLocal contextLocal; private int hovered = -1; public AddWizardElement(AGLView view, IStratomexAdapter adapter) { super(adapter); contextLocal = new GLContextLocal(view.getTextRenderer(), view.getTextureManager(), Activator.getResourceLocator()); this.view = view; this.stateMachine = createStateMachine(adapter, adapter.getVisibleTablePerspectives()); this.stateMachine.getCurrent().onEnter(); } private StateMachineImpl createStateMachine(Object receiver, List<TablePerspective> existing) { StateMachineImpl state = StateMachineImpl.create(receiver, existing); ScoreFactories.fillStateMachine(state, receiver, existing); return state; } /** * @param pick */ @Override public void onPick(Pick pick) { switch (pick.getPickingMode()) { case CLICKED: IState current = stateMachine.getCurrent(); List<ITransition> transitions = stateMachine.getTransitions(current); transitions.get(pick.getObjectID()).apply(this); repaint(); break; case MOUSE_OVER: hovered = pick.getObjectID(); repaint(); break; case MOUSE_OUT: hovered = -1; repaint(); break; default: break; } } private void repaint() { setDisplayListDirty(true); layoutManager.setRenderingDirty(); } @Override public void on(IState target) { stateMachine.getCurrent().onLeave(); stateMachine.move(target); target.onEnter(); Collection<ITransition> transitions = stateMachine.getTransitions(target); // automatically switch single transitions if (transitions.size() == 1) { transitions.iterator().next().apply(this); return; } if (target instanceof ISelectStratificationState) adapter.selectStratification((ISelectStratificationState)target); else if (target instanceof ISelectGroupState) adapter.selectGroup((ISelectGroupState) target); } @Override protected void renderContent(GL2 gl) { final GLGraphics g = new GLGraphics(gl, contextLocal, false, 0); final float w = x; final float h = y; final PixelGLConverter converter = view.getPixelGLConverter(); final float h_header = converter.getGLHeightForPixelHeight(100); final float gap = h_header * 0.1f; IState current = stateMachine.getCurrent(); Collection<ITransition> transitions = stateMachine.getTransitions(current); if (transitions.isEmpty()) { drawMultiLineText(g, current, 0, 0, w, h); } else { drawMultiLineText(g, current, 0, h - h_header, w, h_header); float hi = (h - h_header - transitions.size() * gap) / (transitions.size()); float y = h_header+gap; int i = 0; + g.incZ(); for (ITransition t : transitions) { g.pushName(getPickingID(i)); if (hovered == i) g.color(0.85f); else g.color(0.90f); g.fillRect(gap, h - y - hi, w - 2 * gap, hi); g.popName(); drawMultiLineText(g, t, gap, h - y - hi, w - 2 * gap, hi); y += hi + gap; i++; } + g.decZ(); } } private int getPickingID(int i) { return view.getPickingManager().getPickingID(view.getID(), PICKING_TYPE, i); } private void drawMultiLineText(GLGraphics g, ILabeled item, float x, float y, float w, float h) { if (item.getLabel().isEmpty()) return; final float lineHeight = view.getPixelGLConverter().getGLHeightForPixelHeight(14); List<String> lines = TextUtils.wrap(g.text, item.getLabel(), w, lineHeight); g.drawText(lines, x, y + (h - lineHeight * lines.size()) * 0.5f, w, lineHeight * lines.size(), 0, VAlign.CENTER); } @Override protected boolean permitsWrappingDisplayLists() { return true; } @Override public void onUpdate(UpdateStratificationPreviewEvent event) { if (stateMachine.getCurrent() instanceof ABrowseState) { ((ABrowseState) stateMachine.getCurrent()).onUpdate(event, this); } } @Override public void onUpdate(UpdatePathwayPreviewEvent event) { if (stateMachine.getCurrent() instanceof ABrowseState) { ((ABrowseState) stateMachine.getCurrent()).onUpdate(event, this); } } @Override public void onUpdate(UpdateNumericalPreviewEvent event) { if (stateMachine.getCurrent() instanceof ABrowseState) { ((ABrowseState) stateMachine.getCurrent()).onUpdate(event, this); } } @Override public boolean onSelected(TablePerspective tablePerspective) { if (stateMachine.getCurrent() instanceof ISelectStratificationState) { ISelectStratificationState s = ((ISelectStratificationState) stateMachine.getCurrent()); if (!s.apply(tablePerspective)) return false; s.select(tablePerspective, this); return true; } return false; } @Override public boolean onSelected(TablePerspective tablePerspective, Group group) { if (stateMachine.getCurrent() instanceof ISelectGroupState) { ISelectGroupState s = ((ISelectGroupState) stateMachine.getCurrent()); if (!s.apply(Pair.make(tablePerspective, group))) return false; s.select(tablePerspective, group, this); return true; } return false; } @Override public void switchTo(IState target) { on(target); } @Override public void addScoreToTourGuide(EDataDomainQueryMode mode, IScore... scores) { RcpGLTourGuideView tourGuide = OpenViewHandler.showTourGuide(mode); GLTourGuideView receiver = tourGuide.getView(); // direct as not yet registered AddScoreColumnEvent event = new AddScoreColumnEvent(scores).setReplaceLeadingScoreColumns(true); event.to(receiver).from(this); receiver.onAddColumn(event); } @Override public void done(boolean confirmed) { EventPublisher.trigger(new WizardEndedEvent()); super.done(confirmed); } @Override public void replaceTemplate(ALayoutRenderer renderer) { adapter.replaceTemplate(renderer); } @Override public void replaceTemplate(TablePerspective with, IBrickConfigurer configurer) { adapter.replaceTemplate(with, configurer); } @Override public MultiFormRenderer createPreview(TablePerspective tablePerspective) { return adapter.createPreviewRenderer(tablePerspective); } }
false
true
protected void renderContent(GL2 gl) { final GLGraphics g = new GLGraphics(gl, contextLocal, false, 0); final float w = x; final float h = y; final PixelGLConverter converter = view.getPixelGLConverter(); final float h_header = converter.getGLHeightForPixelHeight(100); final float gap = h_header * 0.1f; IState current = stateMachine.getCurrent(); Collection<ITransition> transitions = stateMachine.getTransitions(current); if (transitions.isEmpty()) { drawMultiLineText(g, current, 0, 0, w, h); } else { drawMultiLineText(g, current, 0, h - h_header, w, h_header); float hi = (h - h_header - transitions.size() * gap) / (transitions.size()); float y = h_header+gap; int i = 0; for (ITransition t : transitions) { g.pushName(getPickingID(i)); if (hovered == i) g.color(0.85f); else g.color(0.90f); g.fillRect(gap, h - y - hi, w - 2 * gap, hi); g.popName(); drawMultiLineText(g, t, gap, h - y - hi, w - 2 * gap, hi); y += hi + gap; i++; } } }
protected void renderContent(GL2 gl) { final GLGraphics g = new GLGraphics(gl, contextLocal, false, 0); final float w = x; final float h = y; final PixelGLConverter converter = view.getPixelGLConverter(); final float h_header = converter.getGLHeightForPixelHeight(100); final float gap = h_header * 0.1f; IState current = stateMachine.getCurrent(); Collection<ITransition> transitions = stateMachine.getTransitions(current); if (transitions.isEmpty()) { drawMultiLineText(g, current, 0, 0, w, h); } else { drawMultiLineText(g, current, 0, h - h_header, w, h_header); float hi = (h - h_header - transitions.size() * gap) / (transitions.size()); float y = h_header+gap; int i = 0; g.incZ(); for (ITransition t : transitions) { g.pushName(getPickingID(i)); if (hovered == i) g.color(0.85f); else g.color(0.90f); g.fillRect(gap, h - y - hi, w - 2 * gap, hi); g.popName(); drawMultiLineText(g, t, gap, h - y - hi, w - 2 * gap, hi); y += hi + gap; i++; } g.decZ(); } }
diff --git a/grails/src/web/org/codehaus/groovy/grails/web/mapping/RegexUrlMapping.java b/grails/src/web/org/codehaus/groovy/grails/web/mapping/RegexUrlMapping.java index 5910343e1..483402b04 100644 --- a/grails/src/web/org/codehaus/groovy/grails/web/mapping/RegexUrlMapping.java +++ b/grails/src/web/org/codehaus/groovy/grails/web/mapping/RegexUrlMapping.java @@ -1,504 +1,504 @@ /* Copyright 2004-2005 Graeme Rocher * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.grails.web.mapping; import groovy.lang.Closure; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.codehaus.groovy.grails.commons.GrailsControllerClass; import org.codehaus.groovy.grails.validation.ConstrainedProperty; import org.codehaus.groovy.grails.web.mapping.exceptions.UrlMappingException; import org.codehaus.groovy.grails.web.servlet.mvc.GrailsWebRequest; import org.codehaus.groovy.grails.web.servlet.mvc.exceptions.ControllerExecutionException; import org.springframework.validation.Errors; import org.springframework.validation.MapBindingResult; import org.springframework.web.context.request.RequestContextHolder; import javax.servlet.ServletContext; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; /** * <p>A UrlMapping implementation that takes a Grails URL pattern and turns it into a regex matcher so that * URLs can be matched and information captured from the match.</p> * <p/> * <p>A Grails URL pattern is not a regex, but is an extension to the form defined by Apache Ant and used by * Spring AntPathMatcher. Unlike regular Ant paths Grails URL patterns allow for capturing groups in the form:</p> * <p/> * <code>/blog/(*)/**</code> * <p/> * <p>The parenthesis define a capturing group. This implementation transforms regular Ant paths into regular expressions * that are able to use capturing groups</p> * * @author Graeme Rocher * @see org.springframework.util.AntPathMatcher * @since 0.5 * <p/> * <p/> * Created: Feb 28, 2007 * Time: 6:12:52 PM */ public class RegexUrlMapping extends AbstractUrlMapping implements UrlMapping { private Pattern[] patterns; private UrlMappingData urlData; private static final String WILDCARD = "*"; private static final String CAPTURED_WILDCARD = "(*)"; private static final String SLASH = "/"; private static final char QUESTION_MARK = '?'; private static final String ENTITY_AMPERSAND = "&amp;"; private static final char AMPERSAND = '&'; private static final String DOUBLE_WILDCARD = "**"; private static final String DEFAULT_ENCODING = "UTF-8"; private static final String CAPTURED_DOUBLE_WILDCARD = "(**)"; private static final Log LOG = LogFactory.getLog(RegexUrlMapping.class); /** * Constructs a new RegexUrlMapping for the given pattern, controller name, action name and constraints. * * @param data An instance of the UrlMappingData class that holds necessary information of the URL mapping * @param controllerName The name of the controller the URL maps to (required) * @param actionName The name of the action the URL maps to * @param viewName The name of the view as an alternative to the name of the action. If the action is specified it takes precedence over the view name during mapping * @param constraints A list of ConstrainedProperty instances that relate to tokens in the URL * @param servletContext * @see org.codehaus.groovy.grails.validation.ConstrainedProperty */ public RegexUrlMapping(UrlMappingData data, Object controllerName, Object actionName, Object viewName, ConstrainedProperty[] constraints, ServletContext servletContext) { super(controllerName, actionName, viewName, constraints != null ? constraints : new ConstrainedProperty[0], servletContext); parse(data, constraints); } private void parse(UrlMappingData data, ConstrainedProperty[] constraints) { if (data == null) throw new IllegalArgumentException("Argument [pattern] cannot be null"); String[] urls = data.getLogicalUrls(); this.urlData = data; this.patterns = new Pattern[urls.length]; for (int i = 0; i < urls.length; i++) { String url = urls[i]; Pattern pattern = convertToRegex(url); if (pattern == null) throw new IllegalStateException("Cannot use null pattern in regular expression mapping for url [" + data.getUrlPattern() + "]"); this.patterns[i] = pattern; } if (constraints != null) { for (int i = 0; i < constraints.length; i++) { ConstrainedProperty constraint = constraints[i]; if (data.isOptional(i)) { constraint.setNullable(true); } } } } /** * Converst a Grails URL provides via the UrlMappingData interface to a regular expression * * @param url The URL to convert * @return A regex Pattern objet */ protected Pattern convertToRegex(String url) { Pattern regex; String pattern = null; try { pattern = "^" + url.replaceAll("([^\\*])\\*([^\\*])", "$1[^/]+$2").replaceAll("([^\\*])\\*$", "$1[^/]+").replaceAll("\\*\\*", ".*"); pattern += "/??$"; regex = Pattern.compile(pattern); } catch (PatternSyntaxException pse) { throw new UrlMappingException("Error evaluating mapping for pattern [" + pattern + "] from Grails URL mappings: " + pse.getMessage(), pse); } return regex; } /** * Matches the given URI and returns a DefaultUrlMappingInfo instance or null * * @param uri The URI to match * @return A UrlMappingInfo instance or null * @see org.codehaus.groovy.grails.web.mapping.UrlMappingInfo */ public UrlMappingInfo match(String uri) { for (int i = 0; i < patterns.length; i++) { Pattern pattern = patterns[i]; Matcher m = pattern.matcher(uri); if (m.matches()) { UrlMappingInfo urlInfo = createUrlMappingInfo(uri, m); if (urlInfo != null) { return urlInfo; } } } return null; } /** * @see org.codehaus.groovy.grails.web.mapping.UrlMapping */ public String createURL(Map parameterValues, String encoding) { return createURLInternal(parameterValues, encoding, true); } private String createURLInternal(Map parameterValues, String encoding, boolean includeContextPath) { if (encoding == null) encoding = "utf-8"; String contextPath = ""; if (includeContextPath) { GrailsWebRequest webRequest = (GrailsWebRequest) RequestContextHolder.getRequestAttributes(); if (webRequest != null) { contextPath = webRequest.getAttributes().getApplicationUri(webRequest.getCurrentRequest()); } } if (parameterValues == null) parameterValues = Collections.EMPTY_MAP; StringBuffer uri = new StringBuffer(contextPath); Set usedParams = new HashSet(); String[] tokens = urlData.getTokens(); int paramIndex = 0; for (int i = 0; i < tokens.length; i++) { String token = tokens[i]; if (CAPTURED_WILDCARD.equals(token) || CAPTURED_DOUBLE_WILDCARD.equals(token)) { ConstrainedProperty prop = this.constraints[paramIndex++]; String propName = prop.getPropertyName(); Object value = parameterValues.get(propName); usedParams.add(propName); if (value == null && !prop.isNullable()) throw new UrlMappingException("Unable to create URL for mapping [" + this + "] and parameters [" + parameterValues + "]. Parameter [" + prop.getPropertyName() + "] is required, but was not specified!"); else if (value == null) break; try { String v = value.toString(); - if (v.contains(SLASH) + if (v.indexOf(SLASH) > -1 && CAPTURED_DOUBLE_WILDCARD.equals(token)) { // individually URL encode path segments if (v.startsWith(SLASH)) { // get rid of leading slash v = v.substring(SLASH.length()); } String[] segs = v.split(SLASH); for (int s = 0; s < segs.length; s++) { String segment = segs[s]; uri.append(SLASH).append(URLEncoder.encode(segment, encoding)); } } else { // original behavior uri.append(SLASH).append(URLEncoder.encode(v, encoding)); } } catch (UnsupportedEncodingException e) { throw new ControllerExecutionException("Error creating URL for parameters [" + parameterValues + "], problem encoding URL part [" + value + "]: " + e.getMessage(), e); } } else { uri.append(SLASH).append(token); } } populateParameterList(parameterValues, encoding, uri, usedParams); if (LOG.isDebugEnabled()) { LOG.debug("Created reverse URL mapping [" + uri.toString() + "] for parameters [" + parameterValues + "]"); } return uri.toString(); } public String createURL(Map parameterValues, String encoding, String fragment) { String url = createURL(parameterValues, encoding); return createUrlWithFragment(url, fragment, encoding); } public String createURL(String controller, String action, Map parameterValues, String encoding) { return createURLInternal(controller, action, parameterValues, encoding, true); } private String createURLInternal(String controller, String action, Map parameterValues, String encoding, boolean includeContextPath) { if (parameterValues == null) parameterValues = new HashMap(); boolean hasController = !StringUtils.isBlank(controller); boolean hasAction = !StringUtils.isBlank(action); try { if (hasController) parameterValues.put(CONTROLLER, controller); if (hasAction) parameterValues.put(ACTION, action); return createURLInternal(parameterValues, encoding, includeContextPath); } finally { if (hasController) parameterValues.remove(CONTROLLER); if (hasAction) parameterValues.remove(ACTION); } } public String createRelativeURL(String controller, String action, Map parameterValues, String encoding) { return createURLInternal(controller, action, parameterValues, encoding, false); } public String createURL(String controller, String action, Map parameterValues, String encoding, String fragment) { String url = createURL(controller, action, parameterValues, encoding); return createUrlWithFragment(url, fragment, encoding); } private String createUrlWithFragment(String url, String fragment, String encoding) { if (fragment != null) { // A 'null' encoding will cause an exception, so default to 'UTF-8'. if (encoding == null) { encoding = DEFAULT_ENCODING; } try { return url + '#' + URLEncoder.encode(fragment, encoding); } catch (UnsupportedEncodingException ex) { throw new ControllerExecutionException("Error creating URL [" + url + "], problem encoding URL fragment [" + fragment + "]: " + ex.getMessage(), ex); } } else { return url; } } private void populateParameterList(Map parameterValues, String encoding, StringBuffer uri, Set usedParams) { boolean addedParams = false; usedParams.add("controller"); usedParams.add("action"); // A 'null' encoding will cause an exception, so default to 'UTF-8'. if (encoding == null) { encoding = DEFAULT_ENCODING; } for (Iterator i = parameterValues.keySet().iterator(); i.hasNext();) { String name = i.next().toString(); if (!usedParams.contains(name)) { if (!addedParams) { uri.append(QUESTION_MARK); addedParams = true; } else { uri.append(AMPERSAND); } Object value = parameterValues.get(name); if (value != null && value instanceof Collection) { Collection multiValues = (Collection) value; for (Iterator j = multiValues.iterator(); j.hasNext();) { Object o = j.next(); appendValueToURI(encoding, uri, name, o); if (j.hasNext()) { uri.append(AMPERSAND); } } } else if (value != null && value.getClass().isArray()) { Object[] multiValues = (Object[]) value; for (int j = 0; j < multiValues.length; j++) { Object o = multiValues[j]; appendValueToURI(encoding, uri, name, o); if (j + 1 < multiValues.length) { uri.append(AMPERSAND); } } } else { appendValueToURI(encoding, uri, name, value); } } } } private void appendValueToURI(String encoding, StringBuffer uri, String name, Object value) { try { uri.append(URLEncoder.encode(name, encoding)).append('=') .append(URLEncoder.encode(value != null ? value.toString() : "", encoding)); } catch (UnsupportedEncodingException e) { throw new ControllerExecutionException("Error redirecting request for url [" + name + ":" + value + "]: " + e.getMessage(), e); } } public UrlMappingData getUrlData() { return this.urlData; } private UrlMappingInfo createUrlMappingInfo(String uri, Matcher m) { Map params = new HashMap(); Errors errors = new MapBindingResult(params, "urlMapping"); String lastGroup = null; for (int i = 0; i < m.groupCount(); i++) { lastGroup = m.group(i + 1); int j = lastGroup.indexOf('?'); if (j > -1) { lastGroup = lastGroup.substring(0, j); } if (constraints.length > i) { ConstrainedProperty cp = constraints[i]; cp.validate(this, lastGroup, errors); if (errors.hasErrors()) return null; else { params.put(cp.getPropertyName(), lastGroup); } } } if (lastGroup != null) { String remainingUri = uri.substring(uri.lastIndexOf(lastGroup) + lastGroup.length()); if (remainingUri.length() > 0) { if (remainingUri.startsWith(SLASH)) remainingUri = remainingUri.substring(1); String[] tokens = remainingUri.split(SLASH); for (int i = 0; i < tokens.length; i = i + 2) { String token = tokens[i]; if ((i + 1) < tokens.length) { params.put(token, tokens[i + 1]); } } } } for (Iterator i = this.parameterValues.keySet().iterator(); i.hasNext();) { Object key = i.next(); params.put(key, this.parameterValues.get(key)); } if (controllerName == null) { this.controllerName = createRuntimeConstraintEvaluator(GrailsControllerClass.CONTROLLER, this.constraints); } if (actionName == null) { this.actionName = createRuntimeConstraintEvaluator(GrailsControllerClass.ACTION, this.constraints); } if (viewName == null) { this.viewName = createRuntimeConstraintEvaluator(GrailsControllerClass.VIEW, this.constraints); } if (viewName != null && this.controllerName == null) { return new DefaultUrlMappingInfo(viewName, params, this.urlData, servletContext); } else { return new DefaultUrlMappingInfo(this.controllerName, this.actionName, getViewName(), params, this.urlData, servletContext); } } /** * This method will look for a constraint for the given name and return a closure that when executed will * attempt to evaluate its value from the bound request parameters at runtime. * * @param name The name of the constrained property * @param constraints The array of current ConstrainedProperty instances * @return Either a Closure or null */ private Object createRuntimeConstraintEvaluator(final String name, ConstrainedProperty[] constraints) { if (constraints == null) return null; for (int i = 0; i < constraints.length; i++) { ConstrainedProperty constraint = constraints[i]; if (constraint.getPropertyName().equals(name)) { return new Closure(this) { public Object call(Object[] objects) { GrailsWebRequest webRequest = (GrailsWebRequest) RequestContextHolder.currentRequestAttributes(); return webRequest.getParams().get(name); } }; } } return null; } public String[] getLogicalMappings() { return this.urlData.getLogicalUrls(); } /** * Compares this UrlMapping instance with the specified UrlMapping instance and deals with URL mapping precedence rules. * * @param o An instance of the UrlMapping interface * @return 1 if this UrlMapping should match before the specified UrlMapping. 0 if they are equal or -1 if this UrlMapping should match after the given UrlMapping */ public int compareTo(Object o) { if (!(o instanceof UrlMapping)) throw new IllegalArgumentException("Cannot compare with Object [" + o + "]. It is not an instance of UrlMapping!"); UrlMapping other = (UrlMapping) o; String[] otherTokens = other .getUrlData() .getTokens(); String[] tokens = getUrlData().getTokens(); if (isWildcard(this) && !isWildcard(other)) return -1; if (!isWildcard(this) && isWildcard(other)) return 1; if (tokens.length < otherTokens.length) { return -1; } else if (tokens.length > otherTokens.length) { return 1; } int result = 0; for (int i = 0; i < tokens.length; i++) { String token = tokens[i]; if (otherTokens.length > i) { String otherToken = otherTokens[i]; if (isWildcard(token) && !isWildcard(otherToken)) { result = -1; break; } else if (!isWildcard(token) && isWildcard(otherToken)) { result = 1; break; } } else { break; } } return result; } private boolean isWildcard(UrlMapping mapping) { String[] tokens = mapping.getUrlData().getTokens(); for (int i = 0; i < tokens.length; i++) { if (isWildcard(tokens[i])) return true; } return false; } private boolean isWildcard(String token) { return WILDCARD.equals(token) || CAPTURED_WILDCARD.equals(token) || DOUBLE_WILDCARD.equals(token) || CAPTURED_DOUBLE_WILDCARD.equals(token); } public String toString() { return this.urlData.getUrlPattern(); } }
true
true
private String createURLInternal(Map parameterValues, String encoding, boolean includeContextPath) { if (encoding == null) encoding = "utf-8"; String contextPath = ""; if (includeContextPath) { GrailsWebRequest webRequest = (GrailsWebRequest) RequestContextHolder.getRequestAttributes(); if (webRequest != null) { contextPath = webRequest.getAttributes().getApplicationUri(webRequest.getCurrentRequest()); } } if (parameterValues == null) parameterValues = Collections.EMPTY_MAP; StringBuffer uri = new StringBuffer(contextPath); Set usedParams = new HashSet(); String[] tokens = urlData.getTokens(); int paramIndex = 0; for (int i = 0; i < tokens.length; i++) { String token = tokens[i]; if (CAPTURED_WILDCARD.equals(token) || CAPTURED_DOUBLE_WILDCARD.equals(token)) { ConstrainedProperty prop = this.constraints[paramIndex++]; String propName = prop.getPropertyName(); Object value = parameterValues.get(propName); usedParams.add(propName); if (value == null && !prop.isNullable()) throw new UrlMappingException("Unable to create URL for mapping [" + this + "] and parameters [" + parameterValues + "]. Parameter [" + prop.getPropertyName() + "] is required, but was not specified!"); else if (value == null) break; try { String v = value.toString(); if (v.contains(SLASH) && CAPTURED_DOUBLE_WILDCARD.equals(token)) { // individually URL encode path segments if (v.startsWith(SLASH)) { // get rid of leading slash v = v.substring(SLASH.length()); } String[] segs = v.split(SLASH); for (int s = 0; s < segs.length; s++) { String segment = segs[s]; uri.append(SLASH).append(URLEncoder.encode(segment, encoding)); } } else { // original behavior uri.append(SLASH).append(URLEncoder.encode(v, encoding)); } } catch (UnsupportedEncodingException e) { throw new ControllerExecutionException("Error creating URL for parameters [" + parameterValues + "], problem encoding URL part [" + value + "]: " + e.getMessage(), e); } } else { uri.append(SLASH).append(token); } } populateParameterList(parameterValues, encoding, uri, usedParams); if (LOG.isDebugEnabled()) { LOG.debug("Created reverse URL mapping [" + uri.toString() + "] for parameters [" + parameterValues + "]"); } return uri.toString(); }
private String createURLInternal(Map parameterValues, String encoding, boolean includeContextPath) { if (encoding == null) encoding = "utf-8"; String contextPath = ""; if (includeContextPath) { GrailsWebRequest webRequest = (GrailsWebRequest) RequestContextHolder.getRequestAttributes(); if (webRequest != null) { contextPath = webRequest.getAttributes().getApplicationUri(webRequest.getCurrentRequest()); } } if (parameterValues == null) parameterValues = Collections.EMPTY_MAP; StringBuffer uri = new StringBuffer(contextPath); Set usedParams = new HashSet(); String[] tokens = urlData.getTokens(); int paramIndex = 0; for (int i = 0; i < tokens.length; i++) { String token = tokens[i]; if (CAPTURED_WILDCARD.equals(token) || CAPTURED_DOUBLE_WILDCARD.equals(token)) { ConstrainedProperty prop = this.constraints[paramIndex++]; String propName = prop.getPropertyName(); Object value = parameterValues.get(propName); usedParams.add(propName); if (value == null && !prop.isNullable()) throw new UrlMappingException("Unable to create URL for mapping [" + this + "] and parameters [" + parameterValues + "]. Parameter [" + prop.getPropertyName() + "] is required, but was not specified!"); else if (value == null) break; try { String v = value.toString(); if (v.indexOf(SLASH) > -1 && CAPTURED_DOUBLE_WILDCARD.equals(token)) { // individually URL encode path segments if (v.startsWith(SLASH)) { // get rid of leading slash v = v.substring(SLASH.length()); } String[] segs = v.split(SLASH); for (int s = 0; s < segs.length; s++) { String segment = segs[s]; uri.append(SLASH).append(URLEncoder.encode(segment, encoding)); } } else { // original behavior uri.append(SLASH).append(URLEncoder.encode(v, encoding)); } } catch (UnsupportedEncodingException e) { throw new ControllerExecutionException("Error creating URL for parameters [" + parameterValues + "], problem encoding URL part [" + value + "]: " + e.getMessage(), e); } } else { uri.append(SLASH).append(token); } } populateParameterList(parameterValues, encoding, uri, usedParams); if (LOG.isDebugEnabled()) { LOG.debug("Created reverse URL mapping [" + uri.toString() + "] for parameters [" + parameterValues + "]"); } return uri.toString(); }
diff --git a/sal-crowd-plugin/src/main/java/com/atlassian/sal/crowd/lifecycle/ApplicationReadyListener.java b/sal-crowd-plugin/src/main/java/com/atlassian/sal/crowd/lifecycle/ApplicationReadyListener.java index b00261b6..b56eec5f 100644 --- a/sal-crowd-plugin/src/main/java/com/atlassian/sal/crowd/lifecycle/ApplicationReadyListener.java +++ b/sal-crowd-plugin/src/main/java/com/atlassian/sal/crowd/lifecycle/ApplicationReadyListener.java @@ -1,30 +1,30 @@ package com.atlassian.sal.crowd.lifecycle; import com.atlassian.config.lifecycle.events.ApplicationStartedEvent; import com.atlassian.event.Event; import com.atlassian.event.EventListener; import com.atlassian.sal.api.component.ComponentLocator; import com.atlassian.sal.api.lifecycle.LifecycleManager; /** * Listens to ApplicationStartedEvent and notifies lifecycle manager. */ public class ApplicationReadyListener implements EventListener { @SuppressWarnings("unchecked") public Class[] getHandledEventClasses() { return new Class[]{ApplicationStartedEvent.class}; } public void handleEvent(Event event) { if (event instanceof ApplicationStartedEvent) { - //final LifecycleManager lifecycleManager = ComponentLocator.getComponent(LifecycleManager.class); - //lifecycleManager.start(); + final LifecycleManager lifecycleManager = ComponentLocator.getComponent(LifecycleManager.class); + lifecycleManager.start(); } } }
true
true
public void handleEvent(Event event) { if (event instanceof ApplicationStartedEvent) { //final LifecycleManager lifecycleManager = ComponentLocator.getComponent(LifecycleManager.class); //lifecycleManager.start(); } }
public void handleEvent(Event event) { if (event instanceof ApplicationStartedEvent) { final LifecycleManager lifecycleManager = ComponentLocator.getComponent(LifecycleManager.class); lifecycleManager.start(); } }
diff --git a/src/main/java/org/encog/workbench/process/EncogAnalystWizard.java b/src/main/java/org/encog/workbench/process/EncogAnalystWizard.java index 4b68b23f..9dec4b10 100644 --- a/src/main/java/org/encog/workbench/process/EncogAnalystWizard.java +++ b/src/main/java/org/encog/workbench/process/EncogAnalystWizard.java @@ -1,246 +1,244 @@ /* * Encog(tm) Workbanch v3.1 - Java Version * http://www.heatonresearch.com/encog/ * http://code.google.com/p/encog-java/ * Copyright 2008-2012 Heaton Research, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package org.encog.workbench.process; import java.io.File; import org.encog.EncogError; import org.encog.app.analyst.AnalystFileFormat; import org.encog.app.analyst.AnalystGoal; import org.encog.app.analyst.EncogAnalyst; import org.encog.app.analyst.missing.DiscardMissing; import org.encog.app.analyst.missing.MeanAndModeMissing; import org.encog.app.analyst.missing.NegateMissing; import org.encog.app.analyst.wizard.AnalystWizard; import org.encog.app.analyst.wizard.WizardMethodType; import org.encog.workbench.EncogWorkBench; import org.encog.workbench.dialogs.wizard.analyst.AnalystWizardDialog; import org.encog.workbench.dialogs.wizard.analyst.RealTimeAnalystWizardDialog; import org.encog.workbench.dialogs.wizard.specific.BayesianWizardDialog; import org.encog.workbench.util.FileUtil; public class EncogAnalystWizard { public static void createEncogAnalyst(File csvFile) { boolean refresh = true; if (csvFile!=null && !EncogWorkBench.getInstance().getMainWindow().getTabManager() .queryViews(csvFile)) return; AnalystWizardDialog dialog = new AnalystWizardDialog(EncogWorkBench .getInstance().getMainWindow()); if (csvFile != null) { dialog.getRawFile().setValue(csvFile.toString()); } if (dialog.process()) { EncogAnalyst analyst = null; File projectFolder = EncogWorkBench.getInstance() .getProjectDirectory(); File egaFile = null; if( dialog.getMethodType()==WizardMethodType.SOM && dialog.getGoal()==AnalystGoal.Regression ) { EncogWorkBench.displayError("Error", "Can't use a SOM with regression."); return; } try { EncogWorkBench.getInstance().getMainWindow().beginWait(); File sourceCSVFile = new File(dialog.getRawFile().getValue()); File targetCSVFile = new File(projectFolder, sourceCSVFile.getName()); if (!sourceCSVFile.toString().equals(targetCSVFile.toString())) { org.encog.util.file.FileUtil.copy(sourceCSVFile, targetCSVFile); } egaFile = new File(FileUtil.forceExtension( targetCSVFile.toString(), "ega")); if (!EncogWorkBench.getInstance().getMainWindow() .getTabManager().queryViews(egaFile)) return; File egFile = new File(FileUtil.forceExtension( targetCSVFile.toString(), "eg")); analyst = new EncogAnalyst(); AnalystWizard wizard = new AnalystWizard(analyst); boolean headers = dialog.getHeaders().getValue(); AnalystFileFormat format = dialog.getFormat(); wizard.setMethodType(dialog.getMethodType()); wizard.setTargetField(dialog.getTargetField()); String m = (String)dialog.getMissing().getSelectedValue(); if( m.equals("DiscardMissing") ) { wizard.setMissing(new DiscardMissing()); } else if( m.equals("MeanAndModeMissing") ) { wizard.setMissing(new MeanAndModeMissing()); } else if( m.equals("NegateMissing") ) { wizard.setMissing(new NegateMissing()); } else { wizard.setMissing(new DiscardMissing()); } wizard.setGoal(dialog.getGoal()); wizard.setLagWindowSize(dialog.getLagCount().getValue()); wizard.setLeadWindowSize(dialog.getLeadCount().getValue()); wizard.setIncludeTargetField(dialog.getIncludeTarget() .getValue()); wizard.setRange(dialog.getRange()); wizard.setTaskNormalize(dialog.getNormalize().getValue()); wizard.setTaskRandomize(dialog.getRandomize().getValue()); wizard.setTaskSegregate(dialog.getSegregate().getValue()); wizard.setTaskBalance(dialog.getBalance().getValue()); wizard.setTaskCluster(dialog.getCluster().getValue()); wizard.setMaxError(dialog.getMaxError().getValue()/100.0); if( !setSpecific(wizard) ) return; wizard.wizard(targetCSVFile, headers, format); if (analyst != null) { analyst.save(egaFile); analyst = null; } refresh = false; EncogWorkBench.getInstance().getMainWindow().openFile(egaFile); } catch (EncogError e) { EncogWorkBench.displayError("Error Generating Analyst Script", e); } finally { EncogWorkBench.getInstance().getMainWindow().endWait(); - if (analyst != null) - analyst.save(egaFile); } } } public static void createRealtimeEncogAnalyst() { boolean refresh = true; RealTimeAnalystWizardDialog dialog = new RealTimeAnalystWizardDialog(); if (dialog.process()) { EncogAnalyst analyst = null; File projectFolder = EncogWorkBench.getInstance() .getProjectDirectory(); File targetCSVFile = null; File egaFile = null; if( dialog.getMethodType()==WizardMethodType.SOM && dialog.getGoal()==AnalystGoal.Regression ) { EncogWorkBench.displayError("Error", "Can't use a SOM with regression."); return; } try { EncogWorkBench.getInstance().getMainWindow().beginWait(); egaFile = new File(FileUtil.forceExtension( dialog.getEgaFile().getValue(), "ega") ); if (!EncogWorkBench.getInstance().getMainWindow() .getTabManager().queryViews(egaFile)) return; File egFile = new File(FileUtil.forceExtension( dialog.getEgaFile().getValue(), "eg")); analyst = new EncogAnalyst(); AnalystWizard wizard = new AnalystWizard(analyst); boolean headers = true; AnalystFileFormat format = AnalystFileFormat.DECPNT_COMMA; wizard.setMethodType(dialog.getMethodType()); wizard.setTargetField(""); String m = (String)dialog.getMissing().getSelectedValue(); if( m.equals("DiscardMissing") ) { wizard.setMissing(new DiscardMissing()); } else if( m.equals("MeanAndModeMissing") ) { wizard.setMissing(new MeanAndModeMissing()); } else if( m.equals("NegateMissing") ) { wizard.setMissing(new NegateMissing()); } else { wizard.setMissing(new DiscardMissing()); } wizard.setGoal(dialog.getGoal()); wizard.setLagWindowSize(dialog.getLagCount().getValue()); wizard.setLeadWindowSize(dialog.getLeadCount().getValue()); wizard.setIncludeTargetField(false); wizard.setRange(dialog.getRange()); wizard.setTaskNormalize(dialog.getNormalize().getValue()); wizard.setTaskRandomize(false); wizard.setTaskSegregate(dialog.getSegregate().getValue()); wizard.setTaskBalance(false); wizard.setTaskCluster(false); wizard.setMaxError(dialog.getMaxError().getValue()/100.0); if( !setSpecific(wizard) ) return; wizard.wizard(targetCSVFile, headers, format); if (analyst != null) { analyst.save(egaFile); analyst = null; } refresh = false; EncogWorkBench.getInstance().getMainWindow().openFile(egaFile); } catch (EncogError e) { EncogWorkBench.displayError("Error Generating Analyst Script", e); } finally { EncogWorkBench.getInstance().getMainWindow().endWait(); if (analyst != null) analyst.save(egaFile); } } } private static boolean setSpecific(AnalystWizard wizard) { if( wizard.getMethodType() == WizardMethodType.BayesianNetwork ) { BayesianWizardDialog dialog = new BayesianWizardDialog(); if( dialog.process() ) { wizard.setNaiveBayes(dialog.getNaiveBayesian().getValue()); wizard.setEvidenceSegements(dialog.getEvidenceSegments().getValue()); return true; } else { return false; } } return true; } }
true
true
public static void createEncogAnalyst(File csvFile) { boolean refresh = true; if (csvFile!=null && !EncogWorkBench.getInstance().getMainWindow().getTabManager() .queryViews(csvFile)) return; AnalystWizardDialog dialog = new AnalystWizardDialog(EncogWorkBench .getInstance().getMainWindow()); if (csvFile != null) { dialog.getRawFile().setValue(csvFile.toString()); } if (dialog.process()) { EncogAnalyst analyst = null; File projectFolder = EncogWorkBench.getInstance() .getProjectDirectory(); File egaFile = null; if( dialog.getMethodType()==WizardMethodType.SOM && dialog.getGoal()==AnalystGoal.Regression ) { EncogWorkBench.displayError("Error", "Can't use a SOM with regression."); return; } try { EncogWorkBench.getInstance().getMainWindow().beginWait(); File sourceCSVFile = new File(dialog.getRawFile().getValue()); File targetCSVFile = new File(projectFolder, sourceCSVFile.getName()); if (!sourceCSVFile.toString().equals(targetCSVFile.toString())) { org.encog.util.file.FileUtil.copy(sourceCSVFile, targetCSVFile); } egaFile = new File(FileUtil.forceExtension( targetCSVFile.toString(), "ega")); if (!EncogWorkBench.getInstance().getMainWindow() .getTabManager().queryViews(egaFile)) return; File egFile = new File(FileUtil.forceExtension( targetCSVFile.toString(), "eg")); analyst = new EncogAnalyst(); AnalystWizard wizard = new AnalystWizard(analyst); boolean headers = dialog.getHeaders().getValue(); AnalystFileFormat format = dialog.getFormat(); wizard.setMethodType(dialog.getMethodType()); wizard.setTargetField(dialog.getTargetField()); String m = (String)dialog.getMissing().getSelectedValue(); if( m.equals("DiscardMissing") ) { wizard.setMissing(new DiscardMissing()); } else if( m.equals("MeanAndModeMissing") ) { wizard.setMissing(new MeanAndModeMissing()); } else if( m.equals("NegateMissing") ) { wizard.setMissing(new NegateMissing()); } else { wizard.setMissing(new DiscardMissing()); } wizard.setGoal(dialog.getGoal()); wizard.setLagWindowSize(dialog.getLagCount().getValue()); wizard.setLeadWindowSize(dialog.getLeadCount().getValue()); wizard.setIncludeTargetField(dialog.getIncludeTarget() .getValue()); wizard.setRange(dialog.getRange()); wizard.setTaskNormalize(dialog.getNormalize().getValue()); wizard.setTaskRandomize(dialog.getRandomize().getValue()); wizard.setTaskSegregate(dialog.getSegregate().getValue()); wizard.setTaskBalance(dialog.getBalance().getValue()); wizard.setTaskCluster(dialog.getCluster().getValue()); wizard.setMaxError(dialog.getMaxError().getValue()/100.0); if( !setSpecific(wizard) ) return; wizard.wizard(targetCSVFile, headers, format); if (analyst != null) { analyst.save(egaFile); analyst = null; } refresh = false; EncogWorkBench.getInstance().getMainWindow().openFile(egaFile); } catch (EncogError e) { EncogWorkBench.displayError("Error Generating Analyst Script", e); } finally { EncogWorkBench.getInstance().getMainWindow().endWait(); if (analyst != null) analyst.save(egaFile); } } }
public static void createEncogAnalyst(File csvFile) { boolean refresh = true; if (csvFile!=null && !EncogWorkBench.getInstance().getMainWindow().getTabManager() .queryViews(csvFile)) return; AnalystWizardDialog dialog = new AnalystWizardDialog(EncogWorkBench .getInstance().getMainWindow()); if (csvFile != null) { dialog.getRawFile().setValue(csvFile.toString()); } if (dialog.process()) { EncogAnalyst analyst = null; File projectFolder = EncogWorkBench.getInstance() .getProjectDirectory(); File egaFile = null; if( dialog.getMethodType()==WizardMethodType.SOM && dialog.getGoal()==AnalystGoal.Regression ) { EncogWorkBench.displayError("Error", "Can't use a SOM with regression."); return; } try { EncogWorkBench.getInstance().getMainWindow().beginWait(); File sourceCSVFile = new File(dialog.getRawFile().getValue()); File targetCSVFile = new File(projectFolder, sourceCSVFile.getName()); if (!sourceCSVFile.toString().equals(targetCSVFile.toString())) { org.encog.util.file.FileUtil.copy(sourceCSVFile, targetCSVFile); } egaFile = new File(FileUtil.forceExtension( targetCSVFile.toString(), "ega")); if (!EncogWorkBench.getInstance().getMainWindow() .getTabManager().queryViews(egaFile)) return; File egFile = new File(FileUtil.forceExtension( targetCSVFile.toString(), "eg")); analyst = new EncogAnalyst(); AnalystWizard wizard = new AnalystWizard(analyst); boolean headers = dialog.getHeaders().getValue(); AnalystFileFormat format = dialog.getFormat(); wizard.setMethodType(dialog.getMethodType()); wizard.setTargetField(dialog.getTargetField()); String m = (String)dialog.getMissing().getSelectedValue(); if( m.equals("DiscardMissing") ) { wizard.setMissing(new DiscardMissing()); } else if( m.equals("MeanAndModeMissing") ) { wizard.setMissing(new MeanAndModeMissing()); } else if( m.equals("NegateMissing") ) { wizard.setMissing(new NegateMissing()); } else { wizard.setMissing(new DiscardMissing()); } wizard.setGoal(dialog.getGoal()); wizard.setLagWindowSize(dialog.getLagCount().getValue()); wizard.setLeadWindowSize(dialog.getLeadCount().getValue()); wizard.setIncludeTargetField(dialog.getIncludeTarget() .getValue()); wizard.setRange(dialog.getRange()); wizard.setTaskNormalize(dialog.getNormalize().getValue()); wizard.setTaskRandomize(dialog.getRandomize().getValue()); wizard.setTaskSegregate(dialog.getSegregate().getValue()); wizard.setTaskBalance(dialog.getBalance().getValue()); wizard.setTaskCluster(dialog.getCluster().getValue()); wizard.setMaxError(dialog.getMaxError().getValue()/100.0); if( !setSpecific(wizard) ) return; wizard.wizard(targetCSVFile, headers, format); if (analyst != null) { analyst.save(egaFile); analyst = null; } refresh = false; EncogWorkBench.getInstance().getMainWindow().openFile(egaFile); } catch (EncogError e) { EncogWorkBench.displayError("Error Generating Analyst Script", e); } finally { EncogWorkBench.getInstance().getMainWindow().endWait(); } } }
diff --git a/JsTestDriver/src/com/google/jstestdriver/browser/BrowserManagedRunner.java b/JsTestDriver/src/com/google/jstestdriver/browser/BrowserManagedRunner.java index c4fa146..5135d5b 100644 --- a/JsTestDriver/src/com/google/jstestdriver/browser/BrowserManagedRunner.java +++ b/JsTestDriver/src/com/google/jstestdriver/browser/BrowserManagedRunner.java @@ -1,81 +1,81 @@ package com.google.jstestdriver.browser; import com.google.jstestdriver.BrowserActionRunner; import com.google.jstestdriver.BrowserInfo; import com.google.jstestdriver.JsTestDriverClient; import com.google.jstestdriver.model.RunData; import com.google.jstestdriver.util.StopWatch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; /** * Manages a BrowserRunner lifecycle around a BrowserActionRunner. * * @author [email protected] (Corbin Smith) * */ public class BrowserManagedRunner implements Callable<RunData> { private static final Logger logger = LoggerFactory.getLogger(BrowserManagedRunner.class); private final BrowserRunner runner; private final String browserId; private final BrowserActionRunner browserActionRunner; private final String serverAddress; private final JsTestDriverClient client; private final StopWatch stopWatch; public BrowserManagedRunner(BrowserRunner runner, String browserId, String serverAddress, JsTestDriverClient client, BrowserActionRunner browserActionRunner, StopWatch stopWatch) { this.runner = runner; this.browserId = browserId; this.serverAddress = serverAddress; this.client = client; this.browserActionRunner = browserActionRunner; this.stopWatch = stopWatch; } public RunData call() throws Exception { - final String url = String.format("%s/capture?id=%s", serverAddress, browserId); + final String url = String.format("%s/capture/id/%s", serverAddress, browserId); stopWatch.start("browser start %s", runner); runner.startBrowser(url); String sessionId = null; try { long timeOut = TimeUnit.MILLISECONDS.convert(runner.getTimeout(), TimeUnit.SECONDS); long start = System.currentTimeMillis(); // TODO(corysmith): replace this with a stream from the client on browser // updates. while (!isBrowserCaptured(browserId, client)) { Thread.sleep(50); if (System.currentTimeMillis() - start > timeOut) { throw new RuntimeException("Could not start browser " + runner + " in " + runner.getTimeout()); } } stopWatch.stop("browser start %s", runner); return browserActionRunner.call(); } finally { stopWatch.start("browser stop %s", runner); runner.stopBrowser(); stopWatch.stop("browser stop %s", runner); } } private boolean isBrowserCaptured(String browserId, JsTestDriverClient client) { for (BrowserInfo browserInfo : client.listBrowsers()) { if (browserId.equals(String.valueOf(browserInfo.getId()))) { logger.debug("Started {}", browserInfo); return true; } } return false; } }
true
true
public RunData call() throws Exception { final String url = String.format("%s/capture?id=%s", serverAddress, browserId); stopWatch.start("browser start %s", runner); runner.startBrowser(url); String sessionId = null; try { long timeOut = TimeUnit.MILLISECONDS.convert(runner.getTimeout(), TimeUnit.SECONDS); long start = System.currentTimeMillis(); // TODO(corysmith): replace this with a stream from the client on browser // updates. while (!isBrowserCaptured(browserId, client)) { Thread.sleep(50); if (System.currentTimeMillis() - start > timeOut) { throw new RuntimeException("Could not start browser " + runner + " in " + runner.getTimeout()); } } stopWatch.stop("browser start %s", runner); return browserActionRunner.call(); } finally { stopWatch.start("browser stop %s", runner); runner.stopBrowser(); stopWatch.stop("browser stop %s", runner); } }
public RunData call() throws Exception { final String url = String.format("%s/capture/id/%s", serverAddress, browserId); stopWatch.start("browser start %s", runner); runner.startBrowser(url); String sessionId = null; try { long timeOut = TimeUnit.MILLISECONDS.convert(runner.getTimeout(), TimeUnit.SECONDS); long start = System.currentTimeMillis(); // TODO(corysmith): replace this with a stream from the client on browser // updates. while (!isBrowserCaptured(browserId, client)) { Thread.sleep(50); if (System.currentTimeMillis() - start > timeOut) { throw new RuntimeException("Could not start browser " + runner + " in " + runner.getTimeout()); } } stopWatch.stop("browser start %s", runner); return browserActionRunner.call(); } finally { stopWatch.start("browser stop %s", runner); runner.stopBrowser(); stopWatch.stop("browser stop %s", runner); } }
diff --git a/shrinksafe/src/org/dojotoolkit/shrinksafe/Compressor.java b/shrinksafe/src/org/dojotoolkit/shrinksafe/Compressor.java index 58a7090..eb565e0 100644 --- a/shrinksafe/src/org/dojotoolkit/shrinksafe/Compressor.java +++ b/shrinksafe/src/org/dojotoolkit/shrinksafe/Compressor.java @@ -1,1009 +1,1013 @@ /* * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Alex Russell * Richard Backhouse */ package org.dojotoolkit.shrinksafe; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Stack; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.mozilla.javascript.CompilerEnvirons; import org.mozilla.javascript.Decompiler; import org.mozilla.javascript.FunctionNode; import org.mozilla.javascript.Interpreter; import org.mozilla.javascript.Kit; import org.mozilla.javascript.Parser; import org.mozilla.javascript.ScriptOrFnNode; import org.mozilla.javascript.ScriptRuntime; import org.mozilla.javascript.Token; import org.mozilla.javascript.UintMap; /** * @author rbackhouse * */ public class Compressor { private static final int FUNCTION_END = Token.LAST_TOKEN + 1; /** * Compress the script * <p> * * @param encodedSource encoded source string * @param flags Flags specifying format of decompilation output * @param properties Decompilation properties * @param parseTree Mapping for each function node and corresponding parameters & variables names * @return compressed script */ private static String compress(String encodedSource, int flags, UintMap properties, ScriptOrFnNode parseTree, boolean escapeUnicode, String stripConsole, TokenMapper tm, Map replacedTokensLookup){ int indent = properties.getInt(Decompiler.INITIAL_INDENT_PROP, 0); if (indent < 0) throw new IllegalArgumentException(); int indentGap = properties.getInt(Decompiler.INDENT_GAP_PROP, 4); if (indentGap < 0) throw new IllegalArgumentException(); int caseGap = properties.getInt(Decompiler.CASE_GAP_PROP, 2); if (caseGap < 0) throw new IllegalArgumentException(); String stripConsoleRegex = "assert|count|debug|dir|dirxml|group|groupEnd|info|profile|profileEnd|time|timeEnd|trace|log"; if (stripConsole == null) { // may be null if unspecified on Main cmd line stripConsoleRegex = null; } else if (stripConsole.equals("normal")) { // leave default } else if (stripConsole.equals("warn")) { stripConsoleRegex += "|warn"; } else if (stripConsole.equals("all")) { stripConsoleRegex += "|warn|error"; } else { throw new IllegalArgumentException("unrecognised value for stripConsole: " + stripConsole + "!"); } Pattern stripConsolePattern = null; if (stripConsoleRegex != null) { stripConsolePattern = Pattern.compile(stripConsoleRegex); } StringBuffer result = new StringBuffer(); boolean justFunctionBody = (0 != (flags & Decompiler.ONLY_BODY_FLAG)); boolean toSource = (0 != (flags & Decompiler.TO_SOURCE_FLAG)); int braceNesting = 0; boolean afterFirstEOL = false; int i = 0; int prevToken = 0; boolean primeFunctionNesting = false; boolean inArgsList = false; boolean primeInArgsList = false; boolean discardingConsole = false; // control skipping "console.stuff()" int consoleParenCount = 0; // counter for parenthesis counting StringBuffer discardMe = new StringBuffer(); // throwaway buffer ReplacedTokens dummyTokens = new ReplacedTokens(new HashMap(), new int[]{}, replacedTokensLookup, null); int lastMeaningfulToken = Token.SEMI; int lastMeaningfulTokenBeforeConsole = Token.SEMI; int topFunctionType; if (encodedSource.charAt(i) == Token.SCRIPT) { ++i; topFunctionType = -1; } else { topFunctionType = encodedSource.charAt(i + 1); } if (!toSource) { // add an initial newline to exactly match js. // result.append('\n'); for (int j = 0; j < indent; j++){ // result.append(' '); result.append(""); } } else { if (topFunctionType == FunctionNode.FUNCTION_EXPRESSION) { result.append('('); } } Stack positionStack = new Stack(); Stack functionPositionStack = new Stack(); int length = encodedSource.length(); int lineCount = 1; while (i < length) { if(i>0){ prevToken = encodedSource.charAt(i-1); } if (discardingConsole) { // while we are skipping a console command, discard tokens int thisToken = encodedSource.charAt(i); /* Logic for controlling state of discardingConsole */ switch (thisToken) { case Token.LP: consoleParenCount++; break; case Token.RP: consoleParenCount--; if (consoleParenCount == 0) { // paren count fell to zero, must be end of console call discardingConsole = false; if (i < (length - 1)) { int nextToken = getNext(encodedSource, length, i); if ((lastMeaningfulTokenBeforeConsole != Token.SEMI && lastMeaningfulTokenBeforeConsole != Token.LC && lastMeaningfulTokenBeforeConsole != Token.RC) || nextToken != Token.SEMI) { // Either the previous or the following token // may use our return value, insert undefined // e.g. true ? console.log("bizarre") : (bar = true); result.append("undefined"); } else { if (Token.SEMI == nextToken) { // munch following semicolon i++; } } } if ((i < (length - 1)) && (Token.EOL == getNext(encodedSource, length, i))) { // as a nicety, munch following linefeed i++; } } break; } /* * advance i - borrow code from later switch statements (could * mingle this whole discardingConsole block in with rest of * function but it would be _ugly_) Use discardMe in place of * result, so we don't use the processed source Specific case * blocks for all source elements > 1 char long */ switch (thisToken) { case Token.NAME: case Token.REGEXP: int jumpPos = getSourceStringEnd(encodedSource, i + 1, escapeUnicode); if (Token.OBJECTLIT == encodedSource.charAt(jumpPos)) { i = printSourceString(encodedSource, i + 1, false, discardMe, escapeUnicode); } else { i = tm.sourceCompress(encodedSource, i + 1, false, discardMe, prevToken, inArgsList, braceNesting, dummyTokens); } break; case Token.STRING: i = printSourceString(encodedSource, i + 1, true, discardMe, escapeUnicode); break; case Token.NUMBER: i = printSourceNumber(encodedSource, i + 1, discardMe); break; default: // all plain tokens (no data to skip) i++; } // while discarding console, avoid the normal processing continue; } // System.out.println(Token.name(getNext(source, length, i))); int thisToken = encodedSource.charAt(i); switch(thisToken) { case Token.NAME: case Token.REGEXP: // re-wrapped in '/'s in parser... int jumpPos = getSourceStringEnd(encodedSource, i+1, escapeUnicode); if (stripConsolePattern != null && thisToken == Token.NAME) { // Check to see if this is a console.something() call that we // care about, if so switch on discardingConsole int nextTokenAt = tm.sourceCompress(encodedSource, i + 1, false, discardMe, prevToken, inArgsList, braceNesting, dummyTokens); if (encodedSource.substring(i+2, i+2+encodedSource.charAt(i+1)).equals("console") && (encodedSource.charAt(nextTokenAt) == Token.DOT)) { // Find the name of the console method and check it int afterFnName = printSourceString(encodedSource, nextTokenAt+2, false, discardMe, escapeUnicode); Matcher m = stripConsolePattern.matcher(encodedSource.substring(nextTokenAt + 3, afterFnName)); if (m.matches()) { // Must be an open parenthesis e.g. "console.log(" if (encodedSource.charAt(afterFnName) == Token.LP) { discardingConsole = true; consoleParenCount = 0; lastMeaningfulTokenBeforeConsole = lastMeaningfulToken; continue; } } } } if(Token.OBJECTLIT == encodedSource.charAt(jumpPos)){ i = printSourceString(encodedSource, i + 1, false, result, escapeUnicode); }else{ ReplacedTokens replacedTokens = null; if (positionStack.size() > 0) { Integer pos = (Integer)positionStack.peek(); replacedTokens = (ReplacedTokens)replacedTokensLookup.get(pos); } else { replacedTokens = new ReplacedTokens(new HashMap(), new int[]{}, replacedTokensLookup, null); } i = tm.sourceCompress( encodedSource, i + 1, false, result, prevToken, inArgsList, braceNesting, replacedTokens); } continue; case Token.STRING: // NOTE: this is the disabled "string munging" code provided in bugs.dojotoolkit.org/ticket/8828 // simply uncomment this block, and run the build.sh script located in the root shrinksafe folder. // there is a far-egde-case this is deemed unsafe in, so is entirely disabled for sanity of devs. // // StringBuffer buf = new StringBuffer(); // i--; // do { // i++; // i = printSourceString(encodedSource, i + 1, false, buf, escapeUnicode); // } while(Token.ADD == encodedSource.charAt(i) && // Token.STRING == getNext(encodedSource, length, i)); // result.append('"'); // result.append(escapeString(buf.toString(), escapeUnicode)); // result.append('"'); // // now comment out this line to complete the patch: i = printSourceString(encodedSource, i + 1, true, result, escapeUnicode); continue; case Token.NUMBER: i = printSourceNumber(encodedSource, i + 1, result); continue; case Token.TRUE: result.append("true"); break; case Token.FALSE: result.append("false"); break; case Token.NULL: result.append("null"); break; case Token.THIS: result.append("this"); break; case Token.FUNCTION: { ++i; // skip function type tm.incrementFunctionNumber(); primeInArgsList = true; primeFunctionNesting = true; result.append("function"); if (Token.LP != getNext(encodedSource, length, i)) { result.append(' '); } Integer functionPos = new Integer(i-1); functionPositionStack.push(functionPos); DebugData debugData = tm.getDebugData(functionPos); debugData.compressedStart = lineCount; break; } case FUNCTION_END: { Integer functionPos = (Integer)functionPositionStack.pop(); DebugData debugData = tm.getDebugData(functionPos); debugData.compressedEnd = lineCount; break; } case Token.COMMA: result.append(","); break; case Token.LC: ++braceNesting; if (Token.EOL == getNext(encodedSource, length, i)){ indent += indentGap; } result.append('{'); // // result.append('\n'); break; case Token.RC: { if (tm.leaveNestingLevel(braceNesting)) { positionStack.pop(); } --braceNesting; /* don't print the closing RC if it closes the * toplevel function and we're called from * decompileFunctionBody. */ if(justFunctionBody && braceNesting == 0){ break; } // // result.append('\n'); result.append('}'); // // result.append(' '); switch (getNext(encodedSource, length, i)) { case Token.EOL: case FUNCTION_END: if ( (getNext(encodedSource, length, i+1) != Token.SEMI) && (getNext(encodedSource, length, i+1) != Token.LP) && (getNext(encodedSource, length, i+1) != Token.RP) && (getNext(encodedSource, length, i+1) != Token.RB) && (getNext(encodedSource, length, i+1) != Token.RC) && (getNext(encodedSource, length, i+1) != Token.COMMA) && (getNext(encodedSource, length, i+1) != Token.COLON) && (getNext(encodedSource, length, i+1) != Token.DOT) && (getNext(encodedSource, length, i) == FUNCTION_END ) ){ result.append(';'); } indent -= indentGap; break; case Token.WHILE: case Token.ELSE: indent -= indentGap; // result.append(' '); result.append(""); break; } break; } case Token.LP: if(primeInArgsList){ inArgsList = true; primeInArgsList = false; } if(primeFunctionNesting){ positionStack.push(new Integer(i)); tm.enterNestingLevel(braceNesting); primeFunctionNesting = false; } result.append('('); break; case Token.RP: if(inArgsList){ inArgsList = false; } result.append(')'); /* if (Token.LC == getNext(source, length, i)){ result.append(' '); } */ break; case Token.LB: result.append('['); break; case Token.RB: result.append(']'); break; case Token.EOL: { if (toSource) break; boolean newLine = true; if (!afterFirstEOL) { afterFirstEOL = true; if (justFunctionBody) { /* throw away just added 'function name(...) {' * and restore the original indent */ result.setLength(0); indent -= indentGap; newLine = false; } } if (newLine) { result.append('\n'); lineCount++; } /* add indent if any tokens remain, * less setback if next token is * a label, case or default. */ if (i + 1 < length) { int less = 0; int nextToken = encodedSource.charAt(i + 1); if (nextToken == Token.CASE || nextToken == Token.DEFAULT) { less = indentGap - caseGap; } else if (nextToken == Token.RC) { less = indentGap; } /* elaborate check against label... skip past a * following inlined NAME and look for a COLON. */ else if (nextToken == Token.NAME) { int afterName = getSourceStringEnd(encodedSource, i + 2, escapeUnicode); if (encodedSource.charAt(afterName) == Token.COLON) less = indentGap; } for (; less < indent; less++){ // result.append(' '); result.append(""); } } break; } case Token.DOT: result.append('.'); break; case Token.NEW: result.append("new "); break; case Token.DELPROP: result.append("delete "); break; case Token.IF: result.append("if"); break; case Token.ELSE: result.append("else"); break; case Token.FOR: result.append("for"); break; case Token.IN: result.append(" in "); break; case Token.WITH: result.append("with"); break; case Token.WHILE: result.append("while"); break; case Token.DO: result.append("do"); break; case Token.TRY: result.append("try"); break; case Token.CATCH: result.append("catch"); break; case Token.FINALLY: result.append("finally"); break; case Token.THROW: result.append("throw "); break; case Token.SWITCH: result.append("switch"); break; case Token.BREAK: result.append("break"); if(Token.NAME == getNext(encodedSource, length, i)){ result.append(' '); } break; case Token.CONTINUE: result.append("continue"); if(Token.NAME == getNext(encodedSource, length, i)){ result.append(' '); } break; case Token.CASE: result.append("case "); break; case Token.DEFAULT: result.append("default"); break; case Token.RETURN: result.append("return"); if(Token.SEMI != getNext(encodedSource, length, i)){ result.append(' '); } break; case Token.VAR: result.append("var "); break; case Token.SEMI: result.append(';'); // result.append('\n'); /* if (Token.EOL != getNext(source, length, i)) { // separators in FOR result.append(' '); } */ break; case Token.ASSIGN: result.append("="); break; case Token.ASSIGN_ADD: result.append("+="); break; case Token.ASSIGN_SUB: result.append("-="); break; case Token.ASSIGN_MUL: result.append("*="); break; case Token.ASSIGN_DIV: result.append("/="); break; case Token.ASSIGN_MOD: result.append("%="); break; case Token.ASSIGN_BITOR: result.append("|="); break; case Token.ASSIGN_BITXOR: result.append("^="); break; case Token.ASSIGN_BITAND: result.append("&="); break; case Token.ASSIGN_LSH: result.append("<<="); break; case Token.ASSIGN_RSH: result.append(">>="); break; case Token.ASSIGN_URSH: result.append(">>>="); break; case Token.HOOK: result.append("?"); break; case Token.OBJECTLIT: // pun OBJECTLIT to mean colon in objlit property // initialization. // This needs to be distinct from COLON in the general case // to distinguish from the colon in a ternary... which needs // different spacing. result.append(':'); break; case Token.COLON: if (Token.EOL == getNext(encodedSource, length, i)) // it's the end of a label result.append(':'); else // it's the middle part of a ternary result.append(":"); break; case Token.OR: result.append("||"); break; case Token.AND: result.append("&&"); break; case Token.BITOR: result.append("|"); break; case Token.BITXOR: result.append("^"); break; case Token.BITAND: result.append("&"); break; case Token.SHEQ: result.append("==="); break; case Token.SHNE: result.append("!=="); break; case Token.EQ: result.append("=="); break; case Token.NE: result.append("!="); break; case Token.LE: result.append("<="); break; case Token.LT: result.append("<"); break; case Token.GE: result.append(">="); break; case Token.GT: result.append(">"); break; case Token.INSTANCEOF: // FIXME: does this really need leading space? result.append(" instanceof "); break; case Token.LSH: result.append("<<"); break; case Token.RSH: result.append(">>"); break; case Token.URSH: result.append(">>>"); break; case Token.TYPEOF: result.append("typeof "); break; case Token.VOID: result.append("void "); break; case Token.NOT: result.append('!'); break; case Token.BITNOT: result.append('~'); break; case Token.POS: result.append('+'); break; case Token.NEG: result.append('-'); break; case Token.INC: if(Token.ADD == prevToken){ result.append(' '); } result.append("++"); if(Token.ADD == getNext(encodedSource, length, i)){ result.append(' '); } break; case Token.DEC: if(Token.SUB == prevToken){ result.append(' '); } result.append("--"); if(Token.SUB == getNext(encodedSource, length, i)){ result.append(' '); } break; case Token.ADD: result.append("+"); + int nextToken = encodedSource.charAt(i + 1); + if (nextToken == Token.POS) { + result.append(' '); + } break; case Token.SUB: result.append("-"); break; case Token.MUL: result.append("*"); break; case Token.DIV: result.append("/"); break; case Token.MOD: result.append("%"); break; case Token.COLONCOLON: result.append("::"); break; case Token.DOTDOT: result.append(".."); break; case Token.XMLATTR: result.append('@'); break; case Token.DEBUGGER: System.out.println("WARNING: Found a `debugger;` statement in code being compressed"); result.append("debugger"); break; default: // If we don't know how to decompile it, raise an exception. throw new RuntimeException(); } if (thisToken != Token.EOL) { lastMeaningfulToken = thisToken; } ++i; } if (!toSource) { // add that trailing newline if it's an outermost function. // if (!justFunctionBody){ // result.append('\n'); // } } else { if (topFunctionType == FunctionNode.FUNCTION_EXPRESSION) { result.append(')'); } } return result.toString(); } /** * Collect the replaced tokens and store them in a lookup table for the next * source pass. * * @param encodedSource encoded source string * @param escapeUnicode escape chars with unicode. * @param tm token mapper object. * @return Map containing replaced tokens lookup information */ private static Map collectReplacedTokens(String encodedSource, boolean escapeUnicode, TokenMapper tm) { int length = encodedSource.length(); int i = 0; int prevToken = 0; int braceNesting = 0; boolean inArgsList = false; boolean primeFunctionNesting = false; boolean primeInArgsList = false; if (encodedSource.charAt(i) == Token.SCRIPT) { ++i; } Stack positionStack = new Stack(); Stack functionPositionStack = new Stack(); Map tokenLookup = new HashMap(); while (i < length) { if (i > 0) { prevToken = encodedSource.charAt(i - 1); } switch (encodedSource.charAt(i)) { case Token.NAME: case Token.REGEXP: { int jumpPos = getSourceStringEnd(encodedSource, i + 1, escapeUnicode); if (Token.OBJECTLIT == encodedSource.charAt(jumpPos)) { i = printSourceString(encodedSource, i + 1, false, null, escapeUnicode); } else { i = tm.sourceCompress(encodedSource, i + 1, false, null, prevToken, inArgsList, braceNesting, null); } continue; } case Token.STRING: { i = printSourceString(encodedSource, i + 1, true, null, escapeUnicode); continue; } case Token.NUMBER: { i = printSourceNumber(encodedSource, i + 1, null); continue; } case Token.FUNCTION: { ++i; // skip function type tm.incrementFunctionNumber(); primeInArgsList = true; primeFunctionNesting = true; functionPositionStack.push(new Integer(i-1)); break; } case Token.LC: { ++braceNesting; break; } case Token.RC: { Map m = tm.getCurrentTokens(); if (tm.leaveNestingLevel(braceNesting)) { Integer pos = (Integer)positionStack.pop(); Integer functionPos = (Integer)functionPositionStack.pop(); int[] parents = new int[positionStack.size()]; int idx = 0; for (Iterator itr = positionStack.iterator(); itr.hasNext();) { parents[idx++] = ((Integer)itr.next()).intValue(); } DebugData debugData = tm.getDebugData(functionPos); ReplacedTokens replacedTokens = new ReplacedTokens(m, parents, tokenLookup, debugData); tokenLookup.put(pos, replacedTokens); } --braceNesting; break; } case Token.LP: { if (primeInArgsList) { inArgsList = true; primeInArgsList = false; } if (primeFunctionNesting) { positionStack.push(new Integer(i)); tm.enterNestingLevel(braceNesting); primeFunctionNesting = false; } break; } case Token.RP: { if (inArgsList) { inArgsList = false; } break; } } ++i; } return tokenLookup; } private static int getNext(String source, int length, int i) { return (i + 1 < length) ? source.charAt(i + 1) : Token.EOF; } private static int getSourceStringEnd(String source, int offset, boolean escapeUnicode) { return printSourceString(source, offset, false, null, escapeUnicode); } private static int printSourceString(String source, int offset, boolean asQuotedString, StringBuffer sb, boolean escapeUnicode) { int length = source.charAt(offset); ++offset; if ((0x8000 & length) != 0) { length = ((0x7FFF & length) << 16) | source.charAt(offset); ++offset; } if (sb != null) { String str = source.substring(offset, offset + length); if (!asQuotedString) { sb.append(str); } else { sb.append('"'); sb.append(escapeString(str, escapeUnicode)); sb.append('"'); } } return offset + length; } private static int printSourceNumber(String source, int offset, StringBuffer sb) { double number = 0.0; char type = source.charAt(offset); ++offset; if (type == 'S') { if (sb != null) { int ival = source.charAt(offset); number = ival; } ++offset; } else if (type == 'J' || type == 'D') { if (sb != null) { long lbits; lbits = (long) source.charAt(offset) << 48; lbits |= (long) source.charAt(offset + 1) << 32; lbits |= (long) source.charAt(offset + 2) << 16; lbits |= source.charAt(offset + 3); if (type == 'J') { number = lbits; } else { number = Double.longBitsToDouble(lbits); } } offset += 4; } else { // Bad source throw new RuntimeException(); } if (sb != null) { sb.append(ScriptRuntime.numberToString(number, 10)); } return offset; } private static String escapeString(String s, boolean escapeUnicode) { return escapeString(s, '"', escapeUnicode); } private static String escapeString(String s, char escapeQuote, boolean escapeUnicode) { if (!(escapeQuote == '"' || escapeQuote == '\'')) Kit.codeBug(); StringBuffer sb = null; for(int i = 0, L = s.length(); i != L; ++i) { int c = s.charAt(i); if (' ' <= c && c <= '~' && c != escapeQuote && c != '\\') { // an ordinary print character (like C isprint()) and not " // or \ . if (sb != null) { sb.append((char)c); } continue; } if (sb == null) { sb = new StringBuffer(L + 3); sb.append(s); sb.setLength(i); } int escape = -1; switch (c) { case '\b': escape = 'b'; break; case '\f': escape = 'f'; break; case '\n': escape = 'n'; break; case '\r': escape = 'r'; break; case '\t': escape = 't'; break; case 0xb: escape = 'v'; break; // Java lacks \v. case ' ': escape = ' '; break; case '\\': escape = '\\'; break; } if (escape >= 0) { // an \escaped sort of character sb.append('\\'); sb.append((char)escape); } else if (c == escapeQuote) { sb.append('\\'); sb.append(escapeQuote); } else { if (escapeUnicode || c == 0) { // always escape the null character (#5027) int hexSize; if (c < 256) { // 2-digit hex sb.append("\\x"); hexSize = 2; } else { // Unicode. sb.append("\\u"); hexSize = 4; } // append hexadecimal form of c left-padded with 0 for (int shift = (hexSize - 1) * 4; shift >= 0; shift -= 4) { int digit = 0xf & (c >> shift); int hc = (digit < 10) ? '0' + digit : 'a' - 10 + digit; sb.append((char)hc); } } else { sb.append((char)c); } } } return (sb == null) ? s : sb.toString(); } public static final String compressScript(String source, int indent, int lineno, String stripConsole) { return compressScript(source, indent, lineno, false, stripConsole); } public static final String compressScript(String source, int indent, int lineno, boolean escapeUnicode, String stripConsole) { return compressScript(source, indent, lineno, false, stripConsole, null); } public static final String compressScript(String source, int indent, int lineno, boolean escapeUnicode, String stripConsole, StringBuffer debugData) { CompilerEnvirons compilerEnv = new CompilerEnvirons(); Parser parser = new Parser(compilerEnv, compilerEnv.getErrorReporter()); ScriptOrFnNode tree = parser.parse(source, null, lineno); String encodedSource = parser.getEncodedSource(); if (encodedSource.length() == 0) { return ""; } Interpreter compiler = new Interpreter(); compiler.compile(compilerEnv, tree, encodedSource, false); UintMap properties = new UintMap(1); properties.put(Decompiler.INITIAL_INDENT_PROP, indent); TokenMapper tm = new TokenMapper(tree); Map replacedTokensLookup = collectReplacedTokens(encodedSource, escapeUnicode, tm); tm.reset(); String compressedSource = compress(encodedSource, 0, properties, tree, escapeUnicode, stripConsole, tm, replacedTokensLookup); if (debugData != null) { debugData.append("[\n"); int count = 1; for (Iterator itr = replacedTokensLookup.keySet().iterator(); itr.hasNext();) { Integer pos = (Integer)itr.next(); ReplacedTokens replacedTokens = (ReplacedTokens)replacedTokensLookup.get(pos); debugData.append(replacedTokens.toJson()); if (count++ < replacedTokensLookup.size()) { debugData.append(','); } debugData.append("\n"); } debugData.append("]"); } return compressedSource; } }
true
true
private static String compress(String encodedSource, int flags, UintMap properties, ScriptOrFnNode parseTree, boolean escapeUnicode, String stripConsole, TokenMapper tm, Map replacedTokensLookup){ int indent = properties.getInt(Decompiler.INITIAL_INDENT_PROP, 0); if (indent < 0) throw new IllegalArgumentException(); int indentGap = properties.getInt(Decompiler.INDENT_GAP_PROP, 4); if (indentGap < 0) throw new IllegalArgumentException(); int caseGap = properties.getInt(Decompiler.CASE_GAP_PROP, 2); if (caseGap < 0) throw new IllegalArgumentException(); String stripConsoleRegex = "assert|count|debug|dir|dirxml|group|groupEnd|info|profile|profileEnd|time|timeEnd|trace|log"; if (stripConsole == null) { // may be null if unspecified on Main cmd line stripConsoleRegex = null; } else if (stripConsole.equals("normal")) { // leave default } else if (stripConsole.equals("warn")) { stripConsoleRegex += "|warn"; } else if (stripConsole.equals("all")) { stripConsoleRegex += "|warn|error"; } else { throw new IllegalArgumentException("unrecognised value for stripConsole: " + stripConsole + "!"); } Pattern stripConsolePattern = null; if (stripConsoleRegex != null) { stripConsolePattern = Pattern.compile(stripConsoleRegex); } StringBuffer result = new StringBuffer(); boolean justFunctionBody = (0 != (flags & Decompiler.ONLY_BODY_FLAG)); boolean toSource = (0 != (flags & Decompiler.TO_SOURCE_FLAG)); int braceNesting = 0; boolean afterFirstEOL = false; int i = 0; int prevToken = 0; boolean primeFunctionNesting = false; boolean inArgsList = false; boolean primeInArgsList = false; boolean discardingConsole = false; // control skipping "console.stuff()" int consoleParenCount = 0; // counter for parenthesis counting StringBuffer discardMe = new StringBuffer(); // throwaway buffer ReplacedTokens dummyTokens = new ReplacedTokens(new HashMap(), new int[]{}, replacedTokensLookup, null); int lastMeaningfulToken = Token.SEMI; int lastMeaningfulTokenBeforeConsole = Token.SEMI; int topFunctionType; if (encodedSource.charAt(i) == Token.SCRIPT) { ++i; topFunctionType = -1; } else { topFunctionType = encodedSource.charAt(i + 1); } if (!toSource) { // add an initial newline to exactly match js. // result.append('\n'); for (int j = 0; j < indent; j++){ // result.append(' '); result.append(""); } } else { if (topFunctionType == FunctionNode.FUNCTION_EXPRESSION) { result.append('('); } } Stack positionStack = new Stack(); Stack functionPositionStack = new Stack(); int length = encodedSource.length(); int lineCount = 1; while (i < length) { if(i>0){ prevToken = encodedSource.charAt(i-1); } if (discardingConsole) { // while we are skipping a console command, discard tokens int thisToken = encodedSource.charAt(i); /* Logic for controlling state of discardingConsole */ switch (thisToken) { case Token.LP: consoleParenCount++; break; case Token.RP: consoleParenCount--; if (consoleParenCount == 0) { // paren count fell to zero, must be end of console call discardingConsole = false; if (i < (length - 1)) { int nextToken = getNext(encodedSource, length, i); if ((lastMeaningfulTokenBeforeConsole != Token.SEMI && lastMeaningfulTokenBeforeConsole != Token.LC && lastMeaningfulTokenBeforeConsole != Token.RC) || nextToken != Token.SEMI) { // Either the previous or the following token // may use our return value, insert undefined // e.g. true ? console.log("bizarre") : (bar = true); result.append("undefined"); } else { if (Token.SEMI == nextToken) { // munch following semicolon i++; } } } if ((i < (length - 1)) && (Token.EOL == getNext(encodedSource, length, i))) { // as a nicety, munch following linefeed i++; } } break; } /* * advance i - borrow code from later switch statements (could * mingle this whole discardingConsole block in with rest of * function but it would be _ugly_) Use discardMe in place of * result, so we don't use the processed source Specific case * blocks for all source elements > 1 char long */ switch (thisToken) { case Token.NAME: case Token.REGEXP: int jumpPos = getSourceStringEnd(encodedSource, i + 1, escapeUnicode); if (Token.OBJECTLIT == encodedSource.charAt(jumpPos)) { i = printSourceString(encodedSource, i + 1, false, discardMe, escapeUnicode); } else { i = tm.sourceCompress(encodedSource, i + 1, false, discardMe, prevToken, inArgsList, braceNesting, dummyTokens); } break; case Token.STRING: i = printSourceString(encodedSource, i + 1, true, discardMe, escapeUnicode); break; case Token.NUMBER: i = printSourceNumber(encodedSource, i + 1, discardMe); break; default: // all plain tokens (no data to skip) i++; } // while discarding console, avoid the normal processing continue; } // System.out.println(Token.name(getNext(source, length, i))); int thisToken = encodedSource.charAt(i); switch(thisToken) { case Token.NAME: case Token.REGEXP: // re-wrapped in '/'s in parser... int jumpPos = getSourceStringEnd(encodedSource, i+1, escapeUnicode); if (stripConsolePattern != null && thisToken == Token.NAME) { // Check to see if this is a console.something() call that we // care about, if so switch on discardingConsole int nextTokenAt = tm.sourceCompress(encodedSource, i + 1, false, discardMe, prevToken, inArgsList, braceNesting, dummyTokens); if (encodedSource.substring(i+2, i+2+encodedSource.charAt(i+1)).equals("console") && (encodedSource.charAt(nextTokenAt) == Token.DOT)) { // Find the name of the console method and check it int afterFnName = printSourceString(encodedSource, nextTokenAt+2, false, discardMe, escapeUnicode); Matcher m = stripConsolePattern.matcher(encodedSource.substring(nextTokenAt + 3, afterFnName)); if (m.matches()) { // Must be an open parenthesis e.g. "console.log(" if (encodedSource.charAt(afterFnName) == Token.LP) { discardingConsole = true; consoleParenCount = 0; lastMeaningfulTokenBeforeConsole = lastMeaningfulToken; continue; } } } } if(Token.OBJECTLIT == encodedSource.charAt(jumpPos)){ i = printSourceString(encodedSource, i + 1, false, result, escapeUnicode); }else{ ReplacedTokens replacedTokens = null; if (positionStack.size() > 0) { Integer pos = (Integer)positionStack.peek(); replacedTokens = (ReplacedTokens)replacedTokensLookup.get(pos); } else { replacedTokens = new ReplacedTokens(new HashMap(), new int[]{}, replacedTokensLookup, null); } i = tm.sourceCompress( encodedSource, i + 1, false, result, prevToken, inArgsList, braceNesting, replacedTokens); } continue; case Token.STRING: // NOTE: this is the disabled "string munging" code provided in bugs.dojotoolkit.org/ticket/8828 // simply uncomment this block, and run the build.sh script located in the root shrinksafe folder. // there is a far-egde-case this is deemed unsafe in, so is entirely disabled for sanity of devs. // // StringBuffer buf = new StringBuffer(); // i--; // do { // i++; // i = printSourceString(encodedSource, i + 1, false, buf, escapeUnicode); // } while(Token.ADD == encodedSource.charAt(i) && // Token.STRING == getNext(encodedSource, length, i)); // result.append('"'); // result.append(escapeString(buf.toString(), escapeUnicode)); // result.append('"'); // // now comment out this line to complete the patch: i = printSourceString(encodedSource, i + 1, true, result, escapeUnicode); continue; case Token.NUMBER: i = printSourceNumber(encodedSource, i + 1, result); continue; case Token.TRUE: result.append("true"); break; case Token.FALSE: result.append("false"); break; case Token.NULL: result.append("null"); break; case Token.THIS: result.append("this"); break; case Token.FUNCTION: { ++i; // skip function type tm.incrementFunctionNumber(); primeInArgsList = true; primeFunctionNesting = true; result.append("function"); if (Token.LP != getNext(encodedSource, length, i)) { result.append(' '); } Integer functionPos = new Integer(i-1); functionPositionStack.push(functionPos); DebugData debugData = tm.getDebugData(functionPos); debugData.compressedStart = lineCount; break; } case FUNCTION_END: { Integer functionPos = (Integer)functionPositionStack.pop(); DebugData debugData = tm.getDebugData(functionPos); debugData.compressedEnd = lineCount; break; } case Token.COMMA: result.append(","); break; case Token.LC: ++braceNesting; if (Token.EOL == getNext(encodedSource, length, i)){ indent += indentGap; } result.append('{'); // // result.append('\n'); break; case Token.RC: { if (tm.leaveNestingLevel(braceNesting)) { positionStack.pop(); } --braceNesting; /* don't print the closing RC if it closes the * toplevel function and we're called from * decompileFunctionBody. */ if(justFunctionBody && braceNesting == 0){ break; } // // result.append('\n'); result.append('}'); // // result.append(' '); switch (getNext(encodedSource, length, i)) { case Token.EOL: case FUNCTION_END: if ( (getNext(encodedSource, length, i+1) != Token.SEMI) && (getNext(encodedSource, length, i+1) != Token.LP) && (getNext(encodedSource, length, i+1) != Token.RP) && (getNext(encodedSource, length, i+1) != Token.RB) && (getNext(encodedSource, length, i+1) != Token.RC) && (getNext(encodedSource, length, i+1) != Token.COMMA) && (getNext(encodedSource, length, i+1) != Token.COLON) && (getNext(encodedSource, length, i+1) != Token.DOT) && (getNext(encodedSource, length, i) == FUNCTION_END ) ){ result.append(';'); } indent -= indentGap; break; case Token.WHILE: case Token.ELSE: indent -= indentGap; // result.append(' '); result.append(""); break; } break; } case Token.LP: if(primeInArgsList){ inArgsList = true; primeInArgsList = false; } if(primeFunctionNesting){ positionStack.push(new Integer(i)); tm.enterNestingLevel(braceNesting); primeFunctionNesting = false; } result.append('('); break; case Token.RP: if(inArgsList){ inArgsList = false; } result.append(')'); /* if (Token.LC == getNext(source, length, i)){ result.append(' '); } */ break; case Token.LB: result.append('['); break; case Token.RB: result.append(']'); break; case Token.EOL: { if (toSource) break; boolean newLine = true; if (!afterFirstEOL) { afterFirstEOL = true; if (justFunctionBody) { /* throw away just added 'function name(...) {' * and restore the original indent */ result.setLength(0); indent -= indentGap; newLine = false; } } if (newLine) { result.append('\n'); lineCount++; } /* add indent if any tokens remain, * less setback if next token is * a label, case or default. */ if (i + 1 < length) { int less = 0; int nextToken = encodedSource.charAt(i + 1); if (nextToken == Token.CASE || nextToken == Token.DEFAULT) { less = indentGap - caseGap; } else if (nextToken == Token.RC) { less = indentGap; } /* elaborate check against label... skip past a * following inlined NAME and look for a COLON. */ else if (nextToken == Token.NAME) { int afterName = getSourceStringEnd(encodedSource, i + 2, escapeUnicode); if (encodedSource.charAt(afterName) == Token.COLON) less = indentGap; } for (; less < indent; less++){ // result.append(' '); result.append(""); } } break; } case Token.DOT: result.append('.'); break; case Token.NEW: result.append("new "); break; case Token.DELPROP: result.append("delete "); break; case Token.IF: result.append("if"); break; case Token.ELSE: result.append("else"); break; case Token.FOR: result.append("for"); break; case Token.IN: result.append(" in "); break; case Token.WITH: result.append("with"); break; case Token.WHILE: result.append("while"); break; case Token.DO: result.append("do"); break; case Token.TRY: result.append("try"); break; case Token.CATCH: result.append("catch"); break; case Token.FINALLY: result.append("finally"); break; case Token.THROW: result.append("throw "); break; case Token.SWITCH: result.append("switch"); break; case Token.BREAK: result.append("break"); if(Token.NAME == getNext(encodedSource, length, i)){ result.append(' '); } break; case Token.CONTINUE: result.append("continue"); if(Token.NAME == getNext(encodedSource, length, i)){ result.append(' '); } break; case Token.CASE: result.append("case "); break; case Token.DEFAULT: result.append("default"); break; case Token.RETURN: result.append("return"); if(Token.SEMI != getNext(encodedSource, length, i)){ result.append(' '); } break; case Token.VAR: result.append("var "); break; case Token.SEMI: result.append(';'); // result.append('\n'); /* if (Token.EOL != getNext(source, length, i)) { // separators in FOR result.append(' '); } */ break; case Token.ASSIGN: result.append("="); break; case Token.ASSIGN_ADD: result.append("+="); break; case Token.ASSIGN_SUB: result.append("-="); break; case Token.ASSIGN_MUL: result.append("*="); break; case Token.ASSIGN_DIV: result.append("/="); break; case Token.ASSIGN_MOD: result.append("%="); break; case Token.ASSIGN_BITOR: result.append("|="); break; case Token.ASSIGN_BITXOR: result.append("^="); break; case Token.ASSIGN_BITAND: result.append("&="); break; case Token.ASSIGN_LSH: result.append("<<="); break; case Token.ASSIGN_RSH: result.append(">>="); break; case Token.ASSIGN_URSH: result.append(">>>="); break; case Token.HOOK: result.append("?"); break; case Token.OBJECTLIT: // pun OBJECTLIT to mean colon in objlit property // initialization. // This needs to be distinct from COLON in the general case // to distinguish from the colon in a ternary... which needs // different spacing. result.append(':'); break; case Token.COLON: if (Token.EOL == getNext(encodedSource, length, i)) // it's the end of a label result.append(':'); else // it's the middle part of a ternary result.append(":"); break; case Token.OR: result.append("||"); break; case Token.AND: result.append("&&"); break; case Token.BITOR: result.append("|"); break; case Token.BITXOR: result.append("^"); break; case Token.BITAND: result.append("&"); break; case Token.SHEQ: result.append("==="); break; case Token.SHNE: result.append("!=="); break; case Token.EQ: result.append("=="); break; case Token.NE: result.append("!="); break; case Token.LE: result.append("<="); break; case Token.LT: result.append("<"); break; case Token.GE: result.append(">="); break; case Token.GT: result.append(">"); break; case Token.INSTANCEOF: // FIXME: does this really need leading space? result.append(" instanceof "); break; case Token.LSH: result.append("<<"); break; case Token.RSH: result.append(">>"); break; case Token.URSH: result.append(">>>"); break; case Token.TYPEOF: result.append("typeof "); break; case Token.VOID: result.append("void "); break; case Token.NOT: result.append('!'); break; case Token.BITNOT: result.append('~'); break; case Token.POS: result.append('+'); break; case Token.NEG: result.append('-'); break; case Token.INC: if(Token.ADD == prevToken){ result.append(' '); } result.append("++"); if(Token.ADD == getNext(encodedSource, length, i)){ result.append(' '); } break; case Token.DEC: if(Token.SUB == prevToken){ result.append(' '); } result.append("--"); if(Token.SUB == getNext(encodedSource, length, i)){ result.append(' '); } break; case Token.ADD: result.append("+"); break; case Token.SUB: result.append("-"); break; case Token.MUL: result.append("*"); break; case Token.DIV: result.append("/"); break; case Token.MOD: result.append("%"); break; case Token.COLONCOLON: result.append("::"); break; case Token.DOTDOT: result.append(".."); break; case Token.XMLATTR: result.append('@'); break; case Token.DEBUGGER: System.out.println("WARNING: Found a `debugger;` statement in code being compressed"); result.append("debugger"); break; default: // If we don't know how to decompile it, raise an exception. throw new RuntimeException(); } if (thisToken != Token.EOL) { lastMeaningfulToken = thisToken; } ++i; } if (!toSource) { // add that trailing newline if it's an outermost function. // if (!justFunctionBody){ // result.append('\n'); // } } else { if (topFunctionType == FunctionNode.FUNCTION_EXPRESSION) { result.append(')'); } } return result.toString(); }
private static String compress(String encodedSource, int flags, UintMap properties, ScriptOrFnNode parseTree, boolean escapeUnicode, String stripConsole, TokenMapper tm, Map replacedTokensLookup){ int indent = properties.getInt(Decompiler.INITIAL_INDENT_PROP, 0); if (indent < 0) throw new IllegalArgumentException(); int indentGap = properties.getInt(Decompiler.INDENT_GAP_PROP, 4); if (indentGap < 0) throw new IllegalArgumentException(); int caseGap = properties.getInt(Decompiler.CASE_GAP_PROP, 2); if (caseGap < 0) throw new IllegalArgumentException(); String stripConsoleRegex = "assert|count|debug|dir|dirxml|group|groupEnd|info|profile|profileEnd|time|timeEnd|trace|log"; if (stripConsole == null) { // may be null if unspecified on Main cmd line stripConsoleRegex = null; } else if (stripConsole.equals("normal")) { // leave default } else if (stripConsole.equals("warn")) { stripConsoleRegex += "|warn"; } else if (stripConsole.equals("all")) { stripConsoleRegex += "|warn|error"; } else { throw new IllegalArgumentException("unrecognised value for stripConsole: " + stripConsole + "!"); } Pattern stripConsolePattern = null; if (stripConsoleRegex != null) { stripConsolePattern = Pattern.compile(stripConsoleRegex); } StringBuffer result = new StringBuffer(); boolean justFunctionBody = (0 != (flags & Decompiler.ONLY_BODY_FLAG)); boolean toSource = (0 != (flags & Decompiler.TO_SOURCE_FLAG)); int braceNesting = 0; boolean afterFirstEOL = false; int i = 0; int prevToken = 0; boolean primeFunctionNesting = false; boolean inArgsList = false; boolean primeInArgsList = false; boolean discardingConsole = false; // control skipping "console.stuff()" int consoleParenCount = 0; // counter for parenthesis counting StringBuffer discardMe = new StringBuffer(); // throwaway buffer ReplacedTokens dummyTokens = new ReplacedTokens(new HashMap(), new int[]{}, replacedTokensLookup, null); int lastMeaningfulToken = Token.SEMI; int lastMeaningfulTokenBeforeConsole = Token.SEMI; int topFunctionType; if (encodedSource.charAt(i) == Token.SCRIPT) { ++i; topFunctionType = -1; } else { topFunctionType = encodedSource.charAt(i + 1); } if (!toSource) { // add an initial newline to exactly match js. // result.append('\n'); for (int j = 0; j < indent; j++){ // result.append(' '); result.append(""); } } else { if (topFunctionType == FunctionNode.FUNCTION_EXPRESSION) { result.append('('); } } Stack positionStack = new Stack(); Stack functionPositionStack = new Stack(); int length = encodedSource.length(); int lineCount = 1; while (i < length) { if(i>0){ prevToken = encodedSource.charAt(i-1); } if (discardingConsole) { // while we are skipping a console command, discard tokens int thisToken = encodedSource.charAt(i); /* Logic for controlling state of discardingConsole */ switch (thisToken) { case Token.LP: consoleParenCount++; break; case Token.RP: consoleParenCount--; if (consoleParenCount == 0) { // paren count fell to zero, must be end of console call discardingConsole = false; if (i < (length - 1)) { int nextToken = getNext(encodedSource, length, i); if ((lastMeaningfulTokenBeforeConsole != Token.SEMI && lastMeaningfulTokenBeforeConsole != Token.LC && lastMeaningfulTokenBeforeConsole != Token.RC) || nextToken != Token.SEMI) { // Either the previous or the following token // may use our return value, insert undefined // e.g. true ? console.log("bizarre") : (bar = true); result.append("undefined"); } else { if (Token.SEMI == nextToken) { // munch following semicolon i++; } } } if ((i < (length - 1)) && (Token.EOL == getNext(encodedSource, length, i))) { // as a nicety, munch following linefeed i++; } } break; } /* * advance i - borrow code from later switch statements (could * mingle this whole discardingConsole block in with rest of * function but it would be _ugly_) Use discardMe in place of * result, so we don't use the processed source Specific case * blocks for all source elements > 1 char long */ switch (thisToken) { case Token.NAME: case Token.REGEXP: int jumpPos = getSourceStringEnd(encodedSource, i + 1, escapeUnicode); if (Token.OBJECTLIT == encodedSource.charAt(jumpPos)) { i = printSourceString(encodedSource, i + 1, false, discardMe, escapeUnicode); } else { i = tm.sourceCompress(encodedSource, i + 1, false, discardMe, prevToken, inArgsList, braceNesting, dummyTokens); } break; case Token.STRING: i = printSourceString(encodedSource, i + 1, true, discardMe, escapeUnicode); break; case Token.NUMBER: i = printSourceNumber(encodedSource, i + 1, discardMe); break; default: // all plain tokens (no data to skip) i++; } // while discarding console, avoid the normal processing continue; } // System.out.println(Token.name(getNext(source, length, i))); int thisToken = encodedSource.charAt(i); switch(thisToken) { case Token.NAME: case Token.REGEXP: // re-wrapped in '/'s in parser... int jumpPos = getSourceStringEnd(encodedSource, i+1, escapeUnicode); if (stripConsolePattern != null && thisToken == Token.NAME) { // Check to see if this is a console.something() call that we // care about, if so switch on discardingConsole int nextTokenAt = tm.sourceCompress(encodedSource, i + 1, false, discardMe, prevToken, inArgsList, braceNesting, dummyTokens); if (encodedSource.substring(i+2, i+2+encodedSource.charAt(i+1)).equals("console") && (encodedSource.charAt(nextTokenAt) == Token.DOT)) { // Find the name of the console method and check it int afterFnName = printSourceString(encodedSource, nextTokenAt+2, false, discardMe, escapeUnicode); Matcher m = stripConsolePattern.matcher(encodedSource.substring(nextTokenAt + 3, afterFnName)); if (m.matches()) { // Must be an open parenthesis e.g. "console.log(" if (encodedSource.charAt(afterFnName) == Token.LP) { discardingConsole = true; consoleParenCount = 0; lastMeaningfulTokenBeforeConsole = lastMeaningfulToken; continue; } } } } if(Token.OBJECTLIT == encodedSource.charAt(jumpPos)){ i = printSourceString(encodedSource, i + 1, false, result, escapeUnicode); }else{ ReplacedTokens replacedTokens = null; if (positionStack.size() > 0) { Integer pos = (Integer)positionStack.peek(); replacedTokens = (ReplacedTokens)replacedTokensLookup.get(pos); } else { replacedTokens = new ReplacedTokens(new HashMap(), new int[]{}, replacedTokensLookup, null); } i = tm.sourceCompress( encodedSource, i + 1, false, result, prevToken, inArgsList, braceNesting, replacedTokens); } continue; case Token.STRING: // NOTE: this is the disabled "string munging" code provided in bugs.dojotoolkit.org/ticket/8828 // simply uncomment this block, and run the build.sh script located in the root shrinksafe folder. // there is a far-egde-case this is deemed unsafe in, so is entirely disabled for sanity of devs. // // StringBuffer buf = new StringBuffer(); // i--; // do { // i++; // i = printSourceString(encodedSource, i + 1, false, buf, escapeUnicode); // } while(Token.ADD == encodedSource.charAt(i) && // Token.STRING == getNext(encodedSource, length, i)); // result.append('"'); // result.append(escapeString(buf.toString(), escapeUnicode)); // result.append('"'); // // now comment out this line to complete the patch: i = printSourceString(encodedSource, i + 1, true, result, escapeUnicode); continue; case Token.NUMBER: i = printSourceNumber(encodedSource, i + 1, result); continue; case Token.TRUE: result.append("true"); break; case Token.FALSE: result.append("false"); break; case Token.NULL: result.append("null"); break; case Token.THIS: result.append("this"); break; case Token.FUNCTION: { ++i; // skip function type tm.incrementFunctionNumber(); primeInArgsList = true; primeFunctionNesting = true; result.append("function"); if (Token.LP != getNext(encodedSource, length, i)) { result.append(' '); } Integer functionPos = new Integer(i-1); functionPositionStack.push(functionPos); DebugData debugData = tm.getDebugData(functionPos); debugData.compressedStart = lineCount; break; } case FUNCTION_END: { Integer functionPos = (Integer)functionPositionStack.pop(); DebugData debugData = tm.getDebugData(functionPos); debugData.compressedEnd = lineCount; break; } case Token.COMMA: result.append(","); break; case Token.LC: ++braceNesting; if (Token.EOL == getNext(encodedSource, length, i)){ indent += indentGap; } result.append('{'); // // result.append('\n'); break; case Token.RC: { if (tm.leaveNestingLevel(braceNesting)) { positionStack.pop(); } --braceNesting; /* don't print the closing RC if it closes the * toplevel function and we're called from * decompileFunctionBody. */ if(justFunctionBody && braceNesting == 0){ break; } // // result.append('\n'); result.append('}'); // // result.append(' '); switch (getNext(encodedSource, length, i)) { case Token.EOL: case FUNCTION_END: if ( (getNext(encodedSource, length, i+1) != Token.SEMI) && (getNext(encodedSource, length, i+1) != Token.LP) && (getNext(encodedSource, length, i+1) != Token.RP) && (getNext(encodedSource, length, i+1) != Token.RB) && (getNext(encodedSource, length, i+1) != Token.RC) && (getNext(encodedSource, length, i+1) != Token.COMMA) && (getNext(encodedSource, length, i+1) != Token.COLON) && (getNext(encodedSource, length, i+1) != Token.DOT) && (getNext(encodedSource, length, i) == FUNCTION_END ) ){ result.append(';'); } indent -= indentGap; break; case Token.WHILE: case Token.ELSE: indent -= indentGap; // result.append(' '); result.append(""); break; } break; } case Token.LP: if(primeInArgsList){ inArgsList = true; primeInArgsList = false; } if(primeFunctionNesting){ positionStack.push(new Integer(i)); tm.enterNestingLevel(braceNesting); primeFunctionNesting = false; } result.append('('); break; case Token.RP: if(inArgsList){ inArgsList = false; } result.append(')'); /* if (Token.LC == getNext(source, length, i)){ result.append(' '); } */ break; case Token.LB: result.append('['); break; case Token.RB: result.append(']'); break; case Token.EOL: { if (toSource) break; boolean newLine = true; if (!afterFirstEOL) { afterFirstEOL = true; if (justFunctionBody) { /* throw away just added 'function name(...) {' * and restore the original indent */ result.setLength(0); indent -= indentGap; newLine = false; } } if (newLine) { result.append('\n'); lineCount++; } /* add indent if any tokens remain, * less setback if next token is * a label, case or default. */ if (i + 1 < length) { int less = 0; int nextToken = encodedSource.charAt(i + 1); if (nextToken == Token.CASE || nextToken == Token.DEFAULT) { less = indentGap - caseGap; } else if (nextToken == Token.RC) { less = indentGap; } /* elaborate check against label... skip past a * following inlined NAME and look for a COLON. */ else if (nextToken == Token.NAME) { int afterName = getSourceStringEnd(encodedSource, i + 2, escapeUnicode); if (encodedSource.charAt(afterName) == Token.COLON) less = indentGap; } for (; less < indent; less++){ // result.append(' '); result.append(""); } } break; } case Token.DOT: result.append('.'); break; case Token.NEW: result.append("new "); break; case Token.DELPROP: result.append("delete "); break; case Token.IF: result.append("if"); break; case Token.ELSE: result.append("else"); break; case Token.FOR: result.append("for"); break; case Token.IN: result.append(" in "); break; case Token.WITH: result.append("with"); break; case Token.WHILE: result.append("while"); break; case Token.DO: result.append("do"); break; case Token.TRY: result.append("try"); break; case Token.CATCH: result.append("catch"); break; case Token.FINALLY: result.append("finally"); break; case Token.THROW: result.append("throw "); break; case Token.SWITCH: result.append("switch"); break; case Token.BREAK: result.append("break"); if(Token.NAME == getNext(encodedSource, length, i)){ result.append(' '); } break; case Token.CONTINUE: result.append("continue"); if(Token.NAME == getNext(encodedSource, length, i)){ result.append(' '); } break; case Token.CASE: result.append("case "); break; case Token.DEFAULT: result.append("default"); break; case Token.RETURN: result.append("return"); if(Token.SEMI != getNext(encodedSource, length, i)){ result.append(' '); } break; case Token.VAR: result.append("var "); break; case Token.SEMI: result.append(';'); // result.append('\n'); /* if (Token.EOL != getNext(source, length, i)) { // separators in FOR result.append(' '); } */ break; case Token.ASSIGN: result.append("="); break; case Token.ASSIGN_ADD: result.append("+="); break; case Token.ASSIGN_SUB: result.append("-="); break; case Token.ASSIGN_MUL: result.append("*="); break; case Token.ASSIGN_DIV: result.append("/="); break; case Token.ASSIGN_MOD: result.append("%="); break; case Token.ASSIGN_BITOR: result.append("|="); break; case Token.ASSIGN_BITXOR: result.append("^="); break; case Token.ASSIGN_BITAND: result.append("&="); break; case Token.ASSIGN_LSH: result.append("<<="); break; case Token.ASSIGN_RSH: result.append(">>="); break; case Token.ASSIGN_URSH: result.append(">>>="); break; case Token.HOOK: result.append("?"); break; case Token.OBJECTLIT: // pun OBJECTLIT to mean colon in objlit property // initialization. // This needs to be distinct from COLON in the general case // to distinguish from the colon in a ternary... which needs // different spacing. result.append(':'); break; case Token.COLON: if (Token.EOL == getNext(encodedSource, length, i)) // it's the end of a label result.append(':'); else // it's the middle part of a ternary result.append(":"); break; case Token.OR: result.append("||"); break; case Token.AND: result.append("&&"); break; case Token.BITOR: result.append("|"); break; case Token.BITXOR: result.append("^"); break; case Token.BITAND: result.append("&"); break; case Token.SHEQ: result.append("==="); break; case Token.SHNE: result.append("!=="); break; case Token.EQ: result.append("=="); break; case Token.NE: result.append("!="); break; case Token.LE: result.append("<="); break; case Token.LT: result.append("<"); break; case Token.GE: result.append(">="); break; case Token.GT: result.append(">"); break; case Token.INSTANCEOF: // FIXME: does this really need leading space? result.append(" instanceof "); break; case Token.LSH: result.append("<<"); break; case Token.RSH: result.append(">>"); break; case Token.URSH: result.append(">>>"); break; case Token.TYPEOF: result.append("typeof "); break; case Token.VOID: result.append("void "); break; case Token.NOT: result.append('!'); break; case Token.BITNOT: result.append('~'); break; case Token.POS: result.append('+'); break; case Token.NEG: result.append('-'); break; case Token.INC: if(Token.ADD == prevToken){ result.append(' '); } result.append("++"); if(Token.ADD == getNext(encodedSource, length, i)){ result.append(' '); } break; case Token.DEC: if(Token.SUB == prevToken){ result.append(' '); } result.append("--"); if(Token.SUB == getNext(encodedSource, length, i)){ result.append(' '); } break; case Token.ADD: result.append("+"); int nextToken = encodedSource.charAt(i + 1); if (nextToken == Token.POS) { result.append(' '); } break; case Token.SUB: result.append("-"); break; case Token.MUL: result.append("*"); break; case Token.DIV: result.append("/"); break; case Token.MOD: result.append("%"); break; case Token.COLONCOLON: result.append("::"); break; case Token.DOTDOT: result.append(".."); break; case Token.XMLATTR: result.append('@'); break; case Token.DEBUGGER: System.out.println("WARNING: Found a `debugger;` statement in code being compressed"); result.append("debugger"); break; default: // If we don't know how to decompile it, raise an exception. throw new RuntimeException(); } if (thisToken != Token.EOL) { lastMeaningfulToken = thisToken; } ++i; } if (!toSource) { // add that trailing newline if it's an outermost function. // if (!justFunctionBody){ // result.append('\n'); // } } else { if (topFunctionType == FunctionNode.FUNCTION_EXPRESSION) { result.append(')'); } } return result.toString(); }
diff --git a/samples/trivialdrive/src/org/onepf/trivialdrive/MainActivity.java b/samples/trivialdrive/src/org/onepf/trivialdrive/MainActivity.java index 533680c..68319f6 100644 --- a/samples/trivialdrive/src/org/onepf/trivialdrive/MainActivity.java +++ b/samples/trivialdrive/src/org/onepf/trivialdrive/MainActivity.java @@ -1,537 +1,539 @@ /* Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onepf.trivialdrive; import java.util.HashMap; import java.util.Map; import org.onepf.oms.OpenIabHelper; import org.onepf.oms.appstore.AmazonAppstore; import org.onepf.oms.appstore.googleUtils.IabHelper; import org.onepf.oms.appstore.googleUtils.IabResult; import org.onepf.oms.appstore.googleUtils.Inventory; import org.onepf.oms.appstore.googleUtils.Purchase; import android.app.Activity; import android.app.AlertDialog; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.Toast; /** * Example game using in-app billing version 3. * * Before attempting to run this sample, please read the README file. It * contains important information on how to set up this project. * * All the game-specific logic is implemented here in MainActivity, while the * general-purpose boilerplate that can be reused in any app is provided in the * classes in the util/ subdirectory. When implementing your own application, * you can copy over util/*.java to make use of those utility classes. * * This game is a simple "driving" game where the player can buy gas * and drive. The car has a tank which stores gas. When the player purchases * gas, the tank fills up (1/4 tank at a time). When the player drives, the gas * in the tank diminishes (also 1/4 tank at a time). * * The user can also purchase a "premium upgrade" that gives them a red car * instead of the standard blue one (exciting!). * * The user can also purchase a subscription ("infinite gas") that allows them * to drive without using up any gas while that subscription is active. * * It's important to note the consumption mechanics for each item. * * PREMIUM: the item is purchased and NEVER consumed. So, after the original * purchase, the player will always own that item. The application knows to * display the red car instead of the blue one because it queries whether * the premium "item" is owned or not. * * INFINITE GAS: this is a subscription, and subscriptions can't be consumed. * * GAS: when gas is purchased, the "gas" item is then owned. We consume it * when we apply that item's effects to our app's world, which to us means * filling up 1/4 of the tank. This happens immediately after purchase! * It's at this point (and not when the user drives) that the "gas" * item is CONSUMED. Consumption should always happen when your game * world was safely updated to apply the effect of the purchase. So, * in an example scenario: * * BEFORE: tank at 1/2 * ON PURCHASE: tank at 1/2, "gas" item is owned * IMMEDIATELY: "gas" is consumed, tank goes to 3/4 * AFTER: tank at 3/4, "gas" item NOT owned any more * * Another important point to notice is that it may so happen that * the application crashed (or anything else happened) after the user * purchased the "gas" item, but before it was consumed. That's why, * on startup, we check if we own the "gas" item, and, if so, * we have to apply its effects to our world and consume it. This * is also very important! * * @author Bruno Oliveira (Google) */ public class MainActivity extends Activity { // Debug tag, for logging static final String TAG = "TrivialDrive"; // Does the user have the premium upgrade? boolean mIsPremium = false; // Does the user have an active subscription to the infinite gas plan? boolean mSubscribedToInfiniteGas = false; // SKUs for our products: the premium upgrade (non-consumable) and gas (consumable) static final String SKU_PREMIUM = "sku_premium"; static final String SKU_GAS = "sku_gas"; // SKU for our subscription (infinite gas) static final String SKU_INFINITE_GAS = "sku_infinite_gas"; static { OpenIabHelper.mapSku(SKU_PREMIUM, OpenIabHelper.NAME_AMAZON, "org.onepf.trivialdrive.amazon.premium"); OpenIabHelper.mapSku(SKU_PREMIUM, OpenIabHelper.NAME_TSTORE, "tstore_sku_premium"); OpenIabHelper.mapSku(SKU_PREMIUM, OpenIabHelper.NAME_SAMSUNG, "100000100696/000001003746"); OpenIabHelper.mapSku(SKU_PREMIUM, "com.yandex.store", "org.onepf.trivialdrive.premium"); OpenIabHelper.mapSku(SKU_GAS, OpenIabHelper.NAME_AMAZON, "org.onepf.trivialdrive.amazon.gas"); OpenIabHelper.mapSku(SKU_GAS, OpenIabHelper.NAME_TSTORE, "tstore_sku_gas"); OpenIabHelper.mapSku(SKU_GAS, OpenIabHelper.NAME_SAMSUNG, "100000100696/000001003744"); OpenIabHelper.mapSku(SKU_GAS, "com.yandex.store", "org.onepf.trivialdrive.gas"); OpenIabHelper.mapSku(SKU_INFINITE_GAS, OpenIabHelper.NAME_AMAZON, "org.onepf.trivialdrive.amazon.infinite_gas"); OpenIabHelper.mapSku(SKU_INFINITE_GAS, OpenIabHelper.NAME_TSTORE, "tstore_sku_infinite_gas"); OpenIabHelper.mapSku(SKU_INFINITE_GAS, OpenIabHelper.NAME_SAMSUNG, "100000100696/000001003747"); OpenIabHelper.mapSku(SKU_INFINITE_GAS, "com.yandex.store", "org.onepf.trivialdrive.infinite_gas"); } // (arbitrary) request code for the purchase flow static final int RC_REQUEST = 10001; // Graphics for the gas gauge static int[] TANK_RES_IDS = { R.drawable.gas0, R.drawable.gas1, R.drawable.gas2, R.drawable.gas3, R.drawable.gas4 }; // How many units (1/4 tank is our unit) fill in the tank. static final int TANK_MAX = 4; // Current amount of gas in tank, in units int mTank; // The helper object OpenIabHelper mHelper; /** is bililng setup is completed */ private boolean setupDone = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // load game data loadData(); /* base64EncodedPublicKey should be YOUR APPLICATION'S PUBLIC KEY * (that you got from the Google Play developer console). This is not your * developer public key, it's the *app-specific* public key. * * Instead of just storing the entire literal string here embedded in the * program, construct the key at runtime from pieces or * use bit manipulation (for example, XOR with some other string) to hide * the actual key. The key itself is not secret information, but we don't * want to make it easy for an attacker to replace the public key with one * of their own and then fake messages from the server. */ String base64EncodedPublicKey = "CONSTRUCT_YOUR_KEY_AND_PLACE_IT_HERE"; String YANDEX_PUBLIC_KEY = "PLACE_HERE_YANDEX_KEY"; // Some sanity checks to see if the developer (that's you!) really followed the // instructions to run this sample (don't put these checks on your app!) if (base64EncodedPublicKey.contains("CONSTRUCT_YOUR")) { throw new RuntimeException("Please put your app's public key in MainActivity.java. See README."); } if (getPackageName().startsWith("com.example")) { throw new RuntimeException("Please change the sample's package name! See README."); } // Create the helper, passing it our context and the public key to verify signatures with Log.d(TAG, "Creating IAB helper."); Map<String, String> storeKeys = new HashMap<String, String>(); storeKeys.put(OpenIabHelper.NAME_GOOGLE, base64EncodedPublicKey); +// storeKeys.put(OpenIabHelper.NAME_AMAZON, "Unavailable. Amazon doesn't support RSA verification. So this mapping is not needed"); // +// storeKeys.put(OpenIabHelper.NAME_SAMSUNG,"Unavailable. SamsungApps doesn't support RSA verification. So this mapping is not needed"); // storeKeys.put("com.yandex.store", YANDEX_PUBLIC_KEY); mHelper = new OpenIabHelper(this, storeKeys); // enable debug logging (for a production application, you should set this to false). //mHelper.enableDebugLogging(true); // Start setup. This is asynchronous and the specified listener // will be called once setup completes. Log.d(TAG, "Starting setup."); mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() { public void onIabSetupFinished(IabResult result) { Log.d(TAG, "Setup finished."); if (!result.isSuccess()) { // Oh noes, there was a problem. complain("Problem setting up in-app billing: " + result); return; } // Hooray, IAB is fully set up. Now, let's get an inventory of stuff we own. Log.d(TAG, "Setup successful. Querying inventory."); setupDone = true; mHelper.queryInventoryAsync(mGotInventoryListener); } }); } // Listener that's called when we finish querying the items and subscriptions we own IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() { public void onQueryInventoryFinished(IabResult result, Inventory inventory) { Log.d(TAG, "Query inventory finished."); if (result.isFailure()) { complain("Failed to query inventory: " + result); return; } Log.d(TAG, "Query inventory was successful."); /* * Check for items we own. Notice that for each purchase, we check * the developer payload to see if it's correct! See * verifyDeveloperPayload(). */ // Do we have the premium upgrade? Purchase premiumPurchase = inventory.getPurchase(SKU_PREMIUM); mIsPremium = (premiumPurchase != null && verifyDeveloperPayload(premiumPurchase)); Log.d(TAG, "User is " + (mIsPremium ? "PREMIUM" : "NOT PREMIUM")); // Do we have the infinite gas plan? Purchase infiniteGasPurchase = inventory.getPurchase(SKU_INFINITE_GAS); mSubscribedToInfiniteGas = (infiniteGasPurchase != null && verifyDeveloperPayload(infiniteGasPurchase)); Log.d(TAG, "User " + (mSubscribedToInfiniteGas ? "HAS" : "DOES NOT HAVE") + " infinite gas subscription."); if (mSubscribedToInfiniteGas) mTank = TANK_MAX; // Check for gas delivery -- if we own gas, we should fill up the tank immediately Purchase gasPurchase = inventory.getPurchase(SKU_GAS); if (gasPurchase != null && verifyDeveloperPayload(gasPurchase)) { Log.d(TAG, "We have gas. Consuming it."); mHelper.consumeAsync(inventory.getPurchase(SKU_GAS), mConsumeFinishedListener); return; } updateUi(); setWaitScreen(false); Log.d(TAG, "Initial inventory query finished; enabling main UI."); } }; // User clicked the "Buy Gas" button public void onBuyGasButtonClicked(View arg0) { Log.d(TAG, "Buy gas button clicked."); if (mSubscribedToInfiniteGas) { complain("No need! You're subscribed to infinite gas. Isn't that awesome?"); return; } if (mTank >= TANK_MAX) { complain("Your tank is full. Drive around a bit!"); return; } if (!setupDone) { complain("Billing Setup is not completed yet"); return; } // launch the gas purchase UI flow. // We will be notified of completion via mPurchaseFinishedListener setWaitScreen(true); Log.d(TAG, "Launching purchase flow for gas."); /* TODO: for security, generate your payload here for verification. See the comments on * verifyDeveloperPayload() for more info. Since this is a SAMPLE, we just use * an empty string, but on a production app you should carefully generate this. */ String payload = ""; mHelper.launchPurchaseFlow(this, SKU_GAS, RC_REQUEST, mPurchaseFinishedListener, payload); } // User clicked the "Upgrade to Premium" button. public void onUpgradeAppButtonClicked(View arg0) { Log.d(TAG, "Upgrade button clicked; launching purchase flow for upgrade."); if (!setupDone) { complain("Billing Setup is not completed yet"); return; } setWaitScreen(true); /* TODO: for security, generate your payload here for verification. See the comments on * verifyDeveloperPayload() for more info. Since this is a SAMPLE, we just use * an empty string, but on a production app you should carefully generate this. */ String payload = ""; mHelper.launchPurchaseFlow(this, SKU_PREMIUM, RC_REQUEST, mPurchaseFinishedListener, payload); } // "Subscribe to infinite gas" button clicked. Explain to user, then start purchase // flow for subscription. public void onInfiniteGasButtonClicked(View arg0) { if (!setupDone) { complain("Billing Setup is not completed yet"); return; } if (!mHelper.subscriptionsSupported()) { complain("Subscriptions not supported on your device yet. Sorry!"); return; } /* TODO: for security, generate your payload here for verification. See the comments on * verifyDeveloperPayload() for more info. Since this is a SAMPLE, we just use * an empty string, but on a production app you should carefully generate this. */ String payload = ""; setWaitScreen(true); Log.d(TAG, "Launching purchase flow for infinite gas subscription."); mHelper.launchPurchaseFlow(this, SKU_INFINITE_GAS, IabHelper.ITEM_TYPE_SUBS, RC_REQUEST, mPurchaseFinishedListener, payload); } @Override public void startActivityForResult(Intent intent, int requestCode) { Log.d(TAG, "startActivityForResult() intent: " + intent + " requestCode: " + requestCode); super.startActivityForResult(intent, requestCode); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d(TAG, "onActivityResult() requestCode: " + requestCode+ " resultCode: " + resultCode+ " data: " + data); // Pass on the activity result to the helper for handling if (!mHelper.handleActivityResult(requestCode, resultCode, data)) { // not handled, so handle it ourselves (here's where you'd // perform any handling of activity results not related to in-app // billing... super.onActivityResult(requestCode, resultCode, data); } else { Log.d(TAG, "onActivityResult handled by IABUtil."); } } /** Verifies the developer payload of a purchase. */ boolean verifyDeveloperPayload(Purchase p) { String payload = p.getDeveloperPayload(); /* * TODO: verify that the developer payload of the purchase is correct. It will be * the same one that you sent when initiating the purchase. * * WARNING: Locally generating a random string when starting a purchase and * verifying it here might seem like a good approach, but this will fail in the * case where the user purchases an item on one device and then uses your app on * a different device, because on the other device you will not have access to the * random string you originally generated. * * So a good developer payload has these characteristics: * * 1. If two different users purchase an item, the payload is different between them, * so that one user's purchase can't be replayed to another user. * * 2. The payload must be such that you can verify it even when the app wasn't the * one who initiated the purchase flow (so that items purchased by the user on * one device work on other devices owned by the user). * * Using your own server to store and verify developer payloads across app * installations is recommended. */ return true; } // Callback for when a purchase is finished IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() { public void onIabPurchaseFinished(IabResult result, Purchase purchase) { Log.d(TAG, "Purchase finished: " + result + ", purchase: " + purchase); if (result.isFailure()) { complain("Error purchasing: " + result); setWaitScreen(false); return; } if (!verifyDeveloperPayload(purchase)) { complain("Error purchasing. Authenticity verification failed."); setWaitScreen(false); return; } Log.d(TAG, "Purchase successful."); if (purchase.getSku().equals(SKU_GAS)) { // bought 1/4 tank of gas. So consume it. Log.d(TAG, "Purchase is gas. Starting gas consumption."); mHelper.consumeAsync(purchase, mConsumeFinishedListener); } else if (purchase.getSku().equals(SKU_PREMIUM)) { // bought the premium upgrade! Log.d(TAG, "Purchase is premium upgrade. Congratulating user."); alert("Thank you for upgrading to premium!"); mIsPremium = true; updateUi(); setWaitScreen(false); } else if (purchase.getSku().equals(SKU_INFINITE_GAS)) { // bought the infinite gas subscription Log.d(TAG, "Infinite gas subscription purchased."); alert("Thank you for subscribing to infinite gas!"); mSubscribedToInfiniteGas = true; mTank = TANK_MAX; updateUi(); setWaitScreen(false); } } }; // Called when consumption is complete IabHelper.OnConsumeFinishedListener mConsumeFinishedListener = new IabHelper.OnConsumeFinishedListener() { public void onConsumeFinished(Purchase purchase, IabResult result) { Log.d(TAG, "Consumption finished. Purchase: " + purchase + ", result: " + result); // We know this is the "gas" sku because it's the only one we consume, // so we don't check which sku was consumed. If you have more than one // sku, you probably should check... if (result.isSuccess()) { // successfully consumed, so we apply the effects of the item in our // game world's logic, which in our case means filling the gas tank a bit Log.d(TAG, "Consumption successful. Provisioning."); mTank = mTank == TANK_MAX ? TANK_MAX : mTank + 1; saveData(); alert("You filled 1/4 tank. Your tank is now " + String.valueOf(mTank) + "/4 full!"); } else { complain("Error while consuming: " + result); } updateUi(); setWaitScreen(false); Log.d(TAG, "End consumption flow."); } }; // Drive button clicked. Burn gas! public void onDriveButtonClicked(View arg0) { Log.d(TAG, "Drive button clicked."); if (!mSubscribedToInfiniteGas && mTank <= 0) alert("Oh, no! You are out of gas! Try buying some!"); else { if (!mSubscribedToInfiniteGas) --mTank; saveData(); alert("Vroooom, you drove a few miles."); updateUi(); Log.d(TAG, "Vrooom. Tank is now " + mTank); } } // We're being destroyed. It's important to dispose of the helper here! @Override public void onDestroy() { super.onDestroy(); // very important: Log.d(TAG, "Destroying helper."); if (mHelper != null) mHelper.dispose(); mHelper = null; } // updates UI to reflect model public void updateUi() { // update the car color to reflect premium status or lack thereof ((ImageView)findViewById(R.id.free_or_premium)).setImageResource(mIsPremium ? R.drawable.premium : R.drawable.free); // "Upgrade" button is only visible if the user is not premium findViewById(R.id.upgrade_button).setVisibility(mIsPremium ? View.GONE : View.VISIBLE); // "Get infinite gas" button is only visible if the user is not subscribed yet findViewById(R.id.infinite_gas_button).setVisibility(mSubscribedToInfiniteGas ? View.GONE : View.VISIBLE); // update gas gauge to reflect tank status if (mSubscribedToInfiniteGas) { ((ImageView)findViewById(R.id.gas_gauge)).setImageResource(R.drawable.gas_inf); } else { int index = mTank >= TANK_RES_IDS.length ? TANK_RES_IDS.length - 1 : mTank; ((ImageView)findViewById(R.id.gas_gauge)).setImageResource(TANK_RES_IDS[index]); } } // Enables or disables the "please wait" screen. void setWaitScreen(boolean set) { findViewById(R.id.screen_main).setVisibility(set ? View.GONE : View.VISIBLE); findViewById(R.id.screen_wait).setVisibility(set ? View.VISIBLE : View.GONE); } void complain(String message) { Log.e(TAG, "**** TrivialDrive Error: " + message); if (AmazonAppstore.hasAmazonClasses()) { // Amazon moderators don't allow alert dialogs for in-apps Toast.makeText(this, "Welcome back, Driver!", Toast.LENGTH_SHORT).show(); } else { alert("Error: " + message); } } void alert(String message) { AlertDialog.Builder bld = new AlertDialog.Builder(this); bld.setMessage(message); bld.setNeutralButton("OK", null); Log.d(TAG, "Showing alert dialog: " + message); bld.create().show(); } void saveData() { /* * WARNING: on a real application, we recommend you save data in a secure way to * prevent tampering. For simplicity in this sample, we simply store the data using a * SharedPreferences. */ SharedPreferences.Editor spe = getPreferences(MODE_PRIVATE).edit(); spe.putInt("tank", mTank); spe.commit(); Log.d(TAG, "Saved data: tank = " + String.valueOf(mTank)); } void loadData() { SharedPreferences sp = getPreferences(MODE_PRIVATE); mTank = sp.getInt("tank", 2); Log.d(TAG, "Loaded data: tank = " + String.valueOf(mTank)); } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // load game data loadData(); /* base64EncodedPublicKey should be YOUR APPLICATION'S PUBLIC KEY * (that you got from the Google Play developer console). This is not your * developer public key, it's the *app-specific* public key. * * Instead of just storing the entire literal string here embedded in the * program, construct the key at runtime from pieces or * use bit manipulation (for example, XOR with some other string) to hide * the actual key. The key itself is not secret information, but we don't * want to make it easy for an attacker to replace the public key with one * of their own and then fake messages from the server. */ String base64EncodedPublicKey = "CONSTRUCT_YOUR_KEY_AND_PLACE_IT_HERE"; String YANDEX_PUBLIC_KEY = "PLACE_HERE_YANDEX_KEY"; // Some sanity checks to see if the developer (that's you!) really followed the // instructions to run this sample (don't put these checks on your app!) if (base64EncodedPublicKey.contains("CONSTRUCT_YOUR")) { throw new RuntimeException("Please put your app's public key in MainActivity.java. See README."); } if (getPackageName().startsWith("com.example")) { throw new RuntimeException("Please change the sample's package name! See README."); } // Create the helper, passing it our context and the public key to verify signatures with Log.d(TAG, "Creating IAB helper."); Map<String, String> storeKeys = new HashMap<String, String>(); storeKeys.put(OpenIabHelper.NAME_GOOGLE, base64EncodedPublicKey); storeKeys.put("com.yandex.store", YANDEX_PUBLIC_KEY); mHelper = new OpenIabHelper(this, storeKeys); // enable debug logging (for a production application, you should set this to false). //mHelper.enableDebugLogging(true); // Start setup. This is asynchronous and the specified listener // will be called once setup completes. Log.d(TAG, "Starting setup."); mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() { public void onIabSetupFinished(IabResult result) { Log.d(TAG, "Setup finished."); if (!result.isSuccess()) { // Oh noes, there was a problem. complain("Problem setting up in-app billing: " + result); return; } // Hooray, IAB is fully set up. Now, let's get an inventory of stuff we own. Log.d(TAG, "Setup successful. Querying inventory."); setupDone = true; mHelper.queryInventoryAsync(mGotInventoryListener); } }); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // load game data loadData(); /* base64EncodedPublicKey should be YOUR APPLICATION'S PUBLIC KEY * (that you got from the Google Play developer console). This is not your * developer public key, it's the *app-specific* public key. * * Instead of just storing the entire literal string here embedded in the * program, construct the key at runtime from pieces or * use bit manipulation (for example, XOR with some other string) to hide * the actual key. The key itself is not secret information, but we don't * want to make it easy for an attacker to replace the public key with one * of their own and then fake messages from the server. */ String base64EncodedPublicKey = "CONSTRUCT_YOUR_KEY_AND_PLACE_IT_HERE"; String YANDEX_PUBLIC_KEY = "PLACE_HERE_YANDEX_KEY"; // Some sanity checks to see if the developer (that's you!) really followed the // instructions to run this sample (don't put these checks on your app!) if (base64EncodedPublicKey.contains("CONSTRUCT_YOUR")) { throw new RuntimeException("Please put your app's public key in MainActivity.java. See README."); } if (getPackageName().startsWith("com.example")) { throw new RuntimeException("Please change the sample's package name! See README."); } // Create the helper, passing it our context and the public key to verify signatures with Log.d(TAG, "Creating IAB helper."); Map<String, String> storeKeys = new HashMap<String, String>(); storeKeys.put(OpenIabHelper.NAME_GOOGLE, base64EncodedPublicKey); // storeKeys.put(OpenIabHelper.NAME_AMAZON, "Unavailable. Amazon doesn't support RSA verification. So this mapping is not needed"); // // storeKeys.put(OpenIabHelper.NAME_SAMSUNG,"Unavailable. SamsungApps doesn't support RSA verification. So this mapping is not needed"); // storeKeys.put("com.yandex.store", YANDEX_PUBLIC_KEY); mHelper = new OpenIabHelper(this, storeKeys); // enable debug logging (for a production application, you should set this to false). //mHelper.enableDebugLogging(true); // Start setup. This is asynchronous and the specified listener // will be called once setup completes. Log.d(TAG, "Starting setup."); mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() { public void onIabSetupFinished(IabResult result) { Log.d(TAG, "Setup finished."); if (!result.isSuccess()) { // Oh noes, there was a problem. complain("Problem setting up in-app billing: " + result); return; } // Hooray, IAB is fully set up. Now, let's get an inventory of stuff we own. Log.d(TAG, "Setup successful. Querying inventory."); setupDone = true; mHelper.queryInventoryAsync(mGotInventoryListener); } }); }
diff --git a/src/no/digipost/android/api/ErrorHandling.java b/src/no/digipost/android/api/ErrorHandling.java index 36b7a027..b02547f6 100644 --- a/src/no/digipost/android/api/ErrorHandling.java +++ b/src/no/digipost/android/api/ErrorHandling.java @@ -1,41 +1,41 @@ /** * Copyright (C) Posten Norge AS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package no.digipost.android.api; public class ErrorHandling { public static final int ERROR_SERVER = 0; public static final int ERROR_CLIENT = 1; public static final int ERROR_DEVICE = 3; public static final int ERROR_GENERAL = 4; public static final int ERROR_OK = 5; public static String LogError(final int error_type, final String error_message) { switch (error_type) { case ERROR_SERVER: - return ""; + return "En feil oppstod under oppkoblingen mot Digipost."; case ERROR_CLIENT: return ""; case ERROR_DEVICE: return ""; case ERROR_GENERAL: return ""; default: return null; } } }
true
true
public static String LogError(final int error_type, final String error_message) { switch (error_type) { case ERROR_SERVER: return ""; case ERROR_CLIENT: return ""; case ERROR_DEVICE: return ""; case ERROR_GENERAL: return ""; default: return null; } }
public static String LogError(final int error_type, final String error_message) { switch (error_type) { case ERROR_SERVER: return "En feil oppstod under oppkoblingen mot Digipost."; case ERROR_CLIENT: return ""; case ERROR_DEVICE: return ""; case ERROR_GENERAL: return ""; default: return null; } }
diff --git a/src/be/ibridge/kettle/job/entry/ftp/JobEntryFTP.java b/src/be/ibridge/kettle/job/entry/ftp/JobEntryFTP.java index 173aa541..abbc293e 100644 --- a/src/be/ibridge/kettle/job/entry/ftp/JobEntryFTP.java +++ b/src/be/ibridge/kettle/job/entry/ftp/JobEntryFTP.java @@ -1,547 +1,548 @@ /********************************************************************** ** ** ** This code belongs to the KETTLE project. ** ** ** ** Kettle, from version 2.2 on, is released into the public domain ** ** under the Lesser GNU Public License (LGPL). ** ** ** ** For more details, please read the document LICENSE.txt, included ** ** in this project ** ** ** ** http://www.kettle.be ** ** [email protected] ** ** ** **********************************************************************/ package be.ibridge.kettle.job.entry.ftp; import java.io.File; import java.net.InetAddress; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.log4j.Logger; import org.eclipse.swt.widgets.Shell; import org.w3c.dom.Node; import be.ibridge.kettle.core.Const; import be.ibridge.kettle.core.LogWriter; import be.ibridge.kettle.core.Result; import be.ibridge.kettle.core.ResultFile; import be.ibridge.kettle.core.XMLHandler; import be.ibridge.kettle.core.exception.KettleDatabaseException; import be.ibridge.kettle.core.exception.KettleException; import be.ibridge.kettle.core.exception.KettleXMLException; import be.ibridge.kettle.core.util.StringUtil; import be.ibridge.kettle.job.Job; import be.ibridge.kettle.job.JobMeta; import be.ibridge.kettle.job.entry.JobEntryBase; import be.ibridge.kettle.job.entry.JobEntryDialogInterface; import be.ibridge.kettle.job.entry.JobEntryInterface; import be.ibridge.kettle.repository.Repository; import com.enterprisedt.net.ftp.FTPClient; import com.enterprisedt.net.ftp.FTPConnectMode; import com.enterprisedt.net.ftp.FTPException; import com.enterprisedt.net.ftp.FTPTransferType; /** * This defines an FTP job entry. * * @author Matt * @since 05-11-2003 * */ public class JobEntryFTP extends JobEntryBase implements JobEntryInterface { private static Logger log4j = Logger.getLogger(JobEntryFTP.class); private String serverName; private String userName; private String password; private String ftpDirectory; private String targetDirectory; private String wildcard; private boolean binaryMode; private int timeout; private boolean remove; private boolean onlyGettingNewFiles; /* Don't overwrite files */ private boolean activeConnection; public JobEntryFTP(String n) { super(n, ""); serverName=null; setID(-1L); setType(JobEntryInterface.TYPE_JOBENTRY_FTP); } public JobEntryFTP() { this(""); } public JobEntryFTP(JobEntryBase jeb) { super(jeb); } public String getXML() { StringBuffer retval = new StringBuffer(128); retval.append(super.getXML()); retval.append(" ").append(XMLHandler.addTagValue("servername", serverName)); retval.append(" ").append(XMLHandler.addTagValue("username", userName)); retval.append(" ").append(XMLHandler.addTagValue("password", password)); retval.append(" ").append(XMLHandler.addTagValue("ftpdirectory", ftpDirectory)); retval.append(" ").append(XMLHandler.addTagValue("targetdirectory", targetDirectory)); retval.append(" ").append(XMLHandler.addTagValue("wildcard", wildcard)); retval.append(" ").append(XMLHandler.addTagValue("binary", binaryMode)); retval.append(" ").append(XMLHandler.addTagValue("timeout", timeout)); retval.append(" ").append(XMLHandler.addTagValue("remove", remove)); retval.append(" ").append(XMLHandler.addTagValue("only_new", onlyGettingNewFiles)); retval.append(" ").append(XMLHandler.addTagValue("active", activeConnection)); return retval.toString(); } public void loadXML(Node entrynode, ArrayList databases, Repository rep) throws KettleXMLException { try { super.loadXML(entrynode, databases); serverName = XMLHandler.getTagValue(entrynode, "servername"); userName = XMLHandler.getTagValue(entrynode, "username"); password = XMLHandler.getTagValue(entrynode, "password"); ftpDirectory = XMLHandler.getTagValue(entrynode, "ftpdirectory"); targetDirectory = XMLHandler.getTagValue(entrynode, "targetdirectory"); wildcard = XMLHandler.getTagValue(entrynode, "wildcard"); binaryMode = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "binary") ); timeout = Const.toInt(XMLHandler.getTagValue(entrynode, "timeout"), 10000); remove = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "remove") ); onlyGettingNewFiles = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "only_new") ); activeConnection = "Y".equalsIgnoreCase( XMLHandler.getTagValue(entrynode, "active") ); } catch(KettleXMLException xe) { throw new KettleXMLException("Unable to load file exists job entry from XML node", xe); } } public void loadRep(Repository rep, long id_jobentry, ArrayList databases) throws KettleException { try { super.loadRep(rep, id_jobentry, databases); serverName = rep.getJobEntryAttributeString(id_jobentry, "servername"); userName = rep.getJobEntryAttributeString(id_jobentry, "username"); password = rep.getJobEntryAttributeString(id_jobentry, "password"); ftpDirectory = rep.getJobEntryAttributeString(id_jobentry, "ftpdirectory"); targetDirectory = rep.getJobEntryAttributeString(id_jobentry, "targetdirectory"); wildcard = rep.getJobEntryAttributeString(id_jobentry, "wildcard"); binaryMode = rep.getJobEntryAttributeBoolean(id_jobentry, "binary"); timeout = (int)rep.getJobEntryAttributeInteger(id_jobentry, "timeout"); remove = rep.getJobEntryAttributeBoolean(id_jobentry, "remove"); onlyGettingNewFiles = rep.getJobEntryAttributeBoolean(id_jobentry, "only_new"); activeConnection = rep.getJobEntryAttributeBoolean(id_jobentry, "active"); } catch(KettleException dbe) { throw new KettleException("Unable to load job entry for type file exists from the repository for id_jobentry="+id_jobentry, dbe); } } public void saveRep(Repository rep, long id_job) throws KettleException { try { super.saveRep(rep, id_job); rep.saveJobEntryAttribute(id_job, getID(), "servername", serverName); rep.saveJobEntryAttribute(id_job, getID(), "username", userName); rep.saveJobEntryAttribute(id_job, getID(), "password", password); rep.saveJobEntryAttribute(id_job, getID(), "ftpdirectory", ftpDirectory); rep.saveJobEntryAttribute(id_job, getID(), "targetdirectory", targetDirectory); rep.saveJobEntryAttribute(id_job, getID(), "wildcard", wildcard); rep.saveJobEntryAttribute(id_job, getID(), "binary", binaryMode); rep.saveJobEntryAttribute(id_job, getID(), "timeout", timeout); rep.saveJobEntryAttribute(id_job, getID(), "remove", remove); rep.saveJobEntryAttribute(id_job, getID(), "only_new", onlyGettingNewFiles); rep.saveJobEntryAttribute(id_job, getID(), "active", activeConnection); } catch(KettleDatabaseException dbe) { throw new KettleException("unable to save jobentry of type 'file exists' to the repository for id_job="+id_job, dbe); } } /** * @return Returns the binaryMode. */ public boolean isBinaryMode() { return binaryMode; } /** * @param binaryMode The binaryMode to set. */ public void setBinaryMode(boolean binaryMode) { this.binaryMode = binaryMode; } /** * @return Returns the directory. */ public String getFtpDirectory() { return ftpDirectory; } /** * @param directory The directory to set. */ public void setFtpDirectory(String directory) { this.ftpDirectory = directory; } /** * @return Returns the password. */ public String getPassword() { return password; } /** * @param password The password to set. */ public void setPassword(String password) { this.password = password; } /** * @return Returns the serverName. */ public String getServerName() { return serverName; } /** * @param serverName The serverName to set. */ public void setServerName(String serverName) { this.serverName = serverName; } /** * @return Returns the userName. */ public String getUserName() { return userName; } /** * @param userName The userName to set. */ public void setUserName(String userName) { this.userName = userName; } /** * @return Returns the wildcard. */ public String getWildcard() { return wildcard; } /** * @param wildcard The wildcard to set. */ public void setWildcard(String wildcard) { this.wildcard = wildcard; } /** * @return Returns the targetDirectory. */ public String getTargetDirectory() { return targetDirectory; } /** * @param targetDirectory The targetDirectory to set. */ public void setTargetDirectory(String targetDirectory) { this.targetDirectory = targetDirectory; } /** * @param timeout The timeout to set. */ public void setTimeout(int timeout) { this.timeout = timeout; } /** * @return Returns the timeout. */ public int getTimeout() { return timeout; } /** * @param remove The remove to set. */ public void setRemove(boolean remove) { this.remove = remove; } /** * @return Returns the remove. */ public boolean getRemove() { return remove; } /** * @return Returns the onlyGettingNewFiles. */ public boolean isOnlyGettingNewFiles() { return onlyGettingNewFiles; } /** * @param onlyGettingNewFiles The onlyGettingNewFiles to set. */ public void setOnlyGettingNewFiles(boolean onlyGettingNewFiles) { this.onlyGettingNewFiles = onlyGettingNewFiles; } public Result execute(Result prev_result, int nr, Repository rep, Job parentJob) { LogWriter log = LogWriter.getInstance(); log4j.info("Started FTP job to "+serverName); Result result = new Result(nr); result.setResult( false ); long filesRetrieved = 0; log.logDetailed(toString(), "Start of FTP job entry"); FTPClient ftpclient=null; try { // Create ftp client to host:port ... ftpclient = new FTPClient(); ftpclient.setRemoteAddr(InetAddress.getByName(serverName)); log.logDetailed(toString(), "Opened FTP connection to server ["+serverName+"]"); // set activeConnection connectmode ... if (activeConnection) { ftpclient.setConnectMode(FTPConnectMode.ACTIVE); log.logDetailed(toString(), "set active ftp connection mode"); } else { ftpclient.setConnectMode(FTPConnectMode.PASV); log.logDetailed(toString(), "set passive ftp connection mode"); } // Set the timeout ftpclient.setTimeout(timeout); log.logDetailed(toString(), "set timeout to "+timeout); // login to ftp host ... ftpclient.connect(); ftpclient.login(userName, password); // Remove password from logging, you don't know where it ends up. log.logDetailed(toString(), "logged in using "+userName); // move to spool dir ... - if (ftpDirectory!=null && ftpDirectory.length()>0) + String realFtpDirectory = StringUtil.environmentSubstitute(ftpDirectory); + if (!Const.isEmpty(realFtpDirectory)) { - ftpclient.chdir(ftpDirectory); - log.logDetailed(toString(), "Changed to directory ["+ftpDirectory+"]"); + ftpclient.chdir(realFtpDirectory); + log.logDetailed(toString(), "Changed to directory ["+realFtpDirectory+"]"); } // Get all the files in the current directory... String[] filelist = ftpclient.dir(); log.logDetailed(toString(), "Found "+filelist.length+" files in the remote ftp directory"); // set transfertype ... if (binaryMode) { ftpclient.setType(FTPTransferType.BINARY); log.logDetailed(toString(), "set binary transfer mode"); } else { ftpclient.setType(FTPTransferType.ASCII); log.logDetailed(toString(), "set ASCII transfer mode"); } // Some FTP servers return a message saying no files found as a string in the filenlist // e.g. Solaris 8 // CHECK THIS !!! if (filelist.length == 1) { String translatedWildcard = StringUtil.environmentSubstitute(wildcard); if (filelist[0].startsWith(translatedWildcard)) { throw new FTPException(filelist[0]); } } Pattern pattern = null; - if (wildcard!=null && wildcard.length()>0) + if (!Const.isEmpty(wildcard)) { - String translatedWildcard = StringUtil.environmentSubstitute(wildcard); - pattern = Pattern.compile(translatedWildcard); + String realWildcard = StringUtil.environmentSubstitute(wildcard); + pattern = Pattern.compile(realWildcard); } // Get the files in the list... for (int i=0;i<filelist.length && !parentJob.isStopped();i++) { boolean getIt = true; // First see if the file matches the regular expression! if (pattern!=null) { Matcher matcher = pattern.matcher(filelist[i]); getIt = matcher.matches(); } if (getIt) { log.logDebug(toString(), "Getting file ["+filelist[i]+"] to directory ["+StringUtil.environmentSubstitute(targetDirectory)+"]"); String targetFilename = getTargetFilename(filelist[i]); File targetFile = new File(targetFilename); if ( (onlyGettingNewFiles == false) || (onlyGettingNewFiles == true) && needsDownload(filelist[i])) { ftpclient.get(targetFilename, filelist[i]); filesRetrieved++; // Add to the result files... ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, targetFile, parentJob.getJobname(), toString()); resultFile.setComment("Downloaded from ftp server "+serverName); result.getResultFiles().add(resultFile); log.logDetailed(toString(), "Got file ["+filelist[i]+"]"); } // Delete the file if this is needed! if (remove) { ftpclient.delete(filelist[i]); log.logDetailed(toString(), "deleted file ["+filelist[i]+"]"); } } } result.setResult( true ); result.setNrFilesRetrieved(filesRetrieved); } catch(Exception e) { result.setNrErrors(1); log.logError(toString(), "Error getting files from FTP : "+e.getMessage()); log.logError(toString(), Const.getStackTracker(e)); } finally { if (ftpclient!=null && ftpclient.connected()) { try { ftpclient.quit(); } catch(Exception e) { log.logError(toString(), "Error quiting FTP connection: "+e.getMessage()); } } } return result; } /** * @param string the filename from the FTP server * * @return the calculated target filename */ protected String getTargetFilename(String string) { return StringUtil.environmentSubstitute(targetDirectory)+Const.FILE_SEPARATOR+string; } public boolean evaluates() { return true; } /** * See if the filename on the FTP server needs downloading. * The default is to check the presence of the file in the target directory. * If you need other functionality, extend this class and build it into a plugin. * * @param filename The filename to check * @return true if the file needs downloading */ protected boolean needsDownload(String filename) { File file = new File(getTargetFilename(filename)); return !file.exists(); } public JobEntryDialogInterface getDialog(Shell shell,JobEntryInterface jei,JobMeta jobMeta,String jobName,Repository rep) { return new JobEntryFTPDialog(shell,this,jobMeta); } /** * @return the activeConnection */ public boolean isActiveConnection() { return activeConnection; } /** * @param activeConnection the activeConnection to set */ public void setActiveConnection(boolean passive) { this.activeConnection = passive; } }
false
true
public Result execute(Result prev_result, int nr, Repository rep, Job parentJob) { LogWriter log = LogWriter.getInstance(); log4j.info("Started FTP job to "+serverName); Result result = new Result(nr); result.setResult( false ); long filesRetrieved = 0; log.logDetailed(toString(), "Start of FTP job entry"); FTPClient ftpclient=null; try { // Create ftp client to host:port ... ftpclient = new FTPClient(); ftpclient.setRemoteAddr(InetAddress.getByName(serverName)); log.logDetailed(toString(), "Opened FTP connection to server ["+serverName+"]"); // set activeConnection connectmode ... if (activeConnection) { ftpclient.setConnectMode(FTPConnectMode.ACTIVE); log.logDetailed(toString(), "set active ftp connection mode"); } else { ftpclient.setConnectMode(FTPConnectMode.PASV); log.logDetailed(toString(), "set passive ftp connection mode"); } // Set the timeout ftpclient.setTimeout(timeout); log.logDetailed(toString(), "set timeout to "+timeout); // login to ftp host ... ftpclient.connect(); ftpclient.login(userName, password); // Remove password from logging, you don't know where it ends up. log.logDetailed(toString(), "logged in using "+userName); // move to spool dir ... if (ftpDirectory!=null && ftpDirectory.length()>0) { ftpclient.chdir(ftpDirectory); log.logDetailed(toString(), "Changed to directory ["+ftpDirectory+"]"); } // Get all the files in the current directory... String[] filelist = ftpclient.dir(); log.logDetailed(toString(), "Found "+filelist.length+" files in the remote ftp directory"); // set transfertype ... if (binaryMode) { ftpclient.setType(FTPTransferType.BINARY); log.logDetailed(toString(), "set binary transfer mode"); } else { ftpclient.setType(FTPTransferType.ASCII); log.logDetailed(toString(), "set ASCII transfer mode"); } // Some FTP servers return a message saying no files found as a string in the filenlist // e.g. Solaris 8 // CHECK THIS !!! if (filelist.length == 1) { String translatedWildcard = StringUtil.environmentSubstitute(wildcard); if (filelist[0].startsWith(translatedWildcard)) { throw new FTPException(filelist[0]); } } Pattern pattern = null; if (wildcard!=null && wildcard.length()>0) { String translatedWildcard = StringUtil.environmentSubstitute(wildcard); pattern = Pattern.compile(translatedWildcard); } // Get the files in the list... for (int i=0;i<filelist.length && !parentJob.isStopped();i++) { boolean getIt = true; // First see if the file matches the regular expression! if (pattern!=null) { Matcher matcher = pattern.matcher(filelist[i]); getIt = matcher.matches(); } if (getIt) { log.logDebug(toString(), "Getting file ["+filelist[i]+"] to directory ["+StringUtil.environmentSubstitute(targetDirectory)+"]"); String targetFilename = getTargetFilename(filelist[i]); File targetFile = new File(targetFilename); if ( (onlyGettingNewFiles == false) || (onlyGettingNewFiles == true) && needsDownload(filelist[i])) { ftpclient.get(targetFilename, filelist[i]); filesRetrieved++; // Add to the result files... ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, targetFile, parentJob.getJobname(), toString()); resultFile.setComment("Downloaded from ftp server "+serverName); result.getResultFiles().add(resultFile); log.logDetailed(toString(), "Got file ["+filelist[i]+"]"); } // Delete the file if this is needed! if (remove) { ftpclient.delete(filelist[i]); log.logDetailed(toString(), "deleted file ["+filelist[i]+"]"); } } } result.setResult( true ); result.setNrFilesRetrieved(filesRetrieved); } catch(Exception e) { result.setNrErrors(1); log.logError(toString(), "Error getting files from FTP : "+e.getMessage()); log.logError(toString(), Const.getStackTracker(e)); } finally { if (ftpclient!=null && ftpclient.connected()) { try { ftpclient.quit(); } catch(Exception e) { log.logError(toString(), "Error quiting FTP connection: "+e.getMessage()); } } } return result; }
public Result execute(Result prev_result, int nr, Repository rep, Job parentJob) { LogWriter log = LogWriter.getInstance(); log4j.info("Started FTP job to "+serverName); Result result = new Result(nr); result.setResult( false ); long filesRetrieved = 0; log.logDetailed(toString(), "Start of FTP job entry"); FTPClient ftpclient=null; try { // Create ftp client to host:port ... ftpclient = new FTPClient(); ftpclient.setRemoteAddr(InetAddress.getByName(serverName)); log.logDetailed(toString(), "Opened FTP connection to server ["+serverName+"]"); // set activeConnection connectmode ... if (activeConnection) { ftpclient.setConnectMode(FTPConnectMode.ACTIVE); log.logDetailed(toString(), "set active ftp connection mode"); } else { ftpclient.setConnectMode(FTPConnectMode.PASV); log.logDetailed(toString(), "set passive ftp connection mode"); } // Set the timeout ftpclient.setTimeout(timeout); log.logDetailed(toString(), "set timeout to "+timeout); // login to ftp host ... ftpclient.connect(); ftpclient.login(userName, password); // Remove password from logging, you don't know where it ends up. log.logDetailed(toString(), "logged in using "+userName); // move to spool dir ... String realFtpDirectory = StringUtil.environmentSubstitute(ftpDirectory); if (!Const.isEmpty(realFtpDirectory)) { ftpclient.chdir(realFtpDirectory); log.logDetailed(toString(), "Changed to directory ["+realFtpDirectory+"]"); } // Get all the files in the current directory... String[] filelist = ftpclient.dir(); log.logDetailed(toString(), "Found "+filelist.length+" files in the remote ftp directory"); // set transfertype ... if (binaryMode) { ftpclient.setType(FTPTransferType.BINARY); log.logDetailed(toString(), "set binary transfer mode"); } else { ftpclient.setType(FTPTransferType.ASCII); log.logDetailed(toString(), "set ASCII transfer mode"); } // Some FTP servers return a message saying no files found as a string in the filenlist // e.g. Solaris 8 // CHECK THIS !!! if (filelist.length == 1) { String translatedWildcard = StringUtil.environmentSubstitute(wildcard); if (filelist[0].startsWith(translatedWildcard)) { throw new FTPException(filelist[0]); } } Pattern pattern = null; if (!Const.isEmpty(wildcard)) { String realWildcard = StringUtil.environmentSubstitute(wildcard); pattern = Pattern.compile(realWildcard); } // Get the files in the list... for (int i=0;i<filelist.length && !parentJob.isStopped();i++) { boolean getIt = true; // First see if the file matches the regular expression! if (pattern!=null) { Matcher matcher = pattern.matcher(filelist[i]); getIt = matcher.matches(); } if (getIt) { log.logDebug(toString(), "Getting file ["+filelist[i]+"] to directory ["+StringUtil.environmentSubstitute(targetDirectory)+"]"); String targetFilename = getTargetFilename(filelist[i]); File targetFile = new File(targetFilename); if ( (onlyGettingNewFiles == false) || (onlyGettingNewFiles == true) && needsDownload(filelist[i])) { ftpclient.get(targetFilename, filelist[i]); filesRetrieved++; // Add to the result files... ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, targetFile, parentJob.getJobname(), toString()); resultFile.setComment("Downloaded from ftp server "+serverName); result.getResultFiles().add(resultFile); log.logDetailed(toString(), "Got file ["+filelist[i]+"]"); } // Delete the file if this is needed! if (remove) { ftpclient.delete(filelist[i]); log.logDetailed(toString(), "deleted file ["+filelist[i]+"]"); } } } result.setResult( true ); result.setNrFilesRetrieved(filesRetrieved); } catch(Exception e) { result.setNrErrors(1); log.logError(toString(), "Error getting files from FTP : "+e.getMessage()); log.logError(toString(), Const.getStackTracker(e)); } finally { if (ftpclient!=null && ftpclient.connected()) { try { ftpclient.quit(); } catch(Exception e) { log.logError(toString(), "Error quiting FTP connection: "+e.getMessage()); } } } return result; }
diff --git a/src/Classe/Vehicule.java b/src/Classe/Vehicule.java index b18d826..205591c 100644 --- a/src/Classe/Vehicule.java +++ b/src/Classe/Vehicule.java @@ -1,186 +1,186 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Classe; import Classe.Strategies.SuivreParcoursOptimal; import Classe.Strategies.AllerNoeudPlusAncien; import Classe.Strategies.AllerNoeudPlusPret; import Classe.Strategies.AttendreNoeud; import Classe.Strategies.AllerPortAttache; import Classe.Strategies.IStrategieAttente; import Classe.Strategies.IStrategieTraitement; import java.awt.geom.Point2D; import java.util.ArrayList; /** * * @author Joseph */ public class Vehicule { private float m_tempsTraitementUrgence; private float m_tempsEcouleSurUrgence; private float m_distanceParcourue; Noeud m_noeudCourant; Noeud m_prochainNoeud; Point2D.Float m_Position; Noeud m_portAttache; IStrategieAttente m_strategieAttente; IStrategieTraitement m_strategieTraitement; public Vehicule (Point2D.Float p_point) { m_Position = p_point; m_tempsTraitementUrgence = 10; m_portAttache = null; m_tempsEcouleSurUrgence = 0; m_distanceParcourue = 0; DefinirStrategieAttente(0); DefinirStrategieTraitement(0); } public void DefinirPortAttache(Noeud p_nouveauPort) { m_portAttache = p_nouveauPort; m_noeudCourant = p_nouveauPort; m_prochainNoeud = p_nouveauPort; m_Position = new Point2D.Float(p_nouveauPort.obtenir_posX(), p_nouveauPort.obtenir_posY()); } public void DefinirTempsTraitement(float nouveauTemps) { m_tempsTraitementUrgence = nouveauTemps; } public void DefinirStrategieAttente(int indexStrategie) { if(indexStrategie == 2) { m_strategieAttente = new AllerPortAttache(); } else { m_strategieAttente = new AttendreNoeud(); } } public void DefinirStrategieTraitement(int indexStrategie) { if(indexStrategie == 2) { m_strategieTraitement = new AllerNoeudPlusPret(); } else { if(indexStrategie == 3) { m_strategieTraitement = new SuivreParcoursOptimal(); } else { m_strategieTraitement = new AllerNoeudPlusAncien(); } } } public void AvancerTemps(ArrayList<Noeud> systemeRoutier, double vitesse) { double rapportDistance; double DistanceSegment; //Verifie si véhicule est sur un noeud if(m_noeudCourant.EstMemePosition(m_Position)) { - if(m_noeudCourant.ContientUrgenceDeclencheeNonTraitee()) + if(m_noeudCourant.ContientUrgenceDeclencheeNonTraitee() && m_strategieTraitement.ObtenirProchainNoeud(m_noeudCourant, systemeRoutier) == null) { AvancerTraitementUrgence(vitesse); } else { if(SystemeContientUrgenceRestante(systemeRoutier)) { m_prochainNoeud = m_strategieTraitement.ObtenirProchainNoeud(m_noeudCourant, systemeRoutier); } else { m_prochainNoeud = m_strategieAttente.ObtenirProchainNoeud(m_noeudCourant, systemeRoutier, m_portAttache); if(m_prochainNoeud == null) { m_prochainNoeud = m_noeudCourant; } } Avancer(vitesse); } } else { Avancer(vitesse); } } private void AvancerTraitementUrgence(double vitesse) { m_tempsEcouleSurUrgence += vitesse; if(m_tempsEcouleSurUrgence >= m_tempsTraitementUrgence) { m_tempsEcouleSurUrgence = 0; m_noeudCourant.ObtenirUrgenceCouranteDeclenchee().DefinirTerminee(); } } private boolean SystemeContientUrgenceRestante(ArrayList<Noeud> systemeRoutier) { boolean systemeContientUrgence = false; int compteur = 0; while(systemeContientUrgence == false && compteur < systemeRoutier.size()) { if(systemeRoutier.get(compteur).ContientUrgenceDeclencheeNonTraitee()) { systemeContientUrgence = true; } compteur++; } return systemeContientUrgence; } private void Avancer(double vitesse) { double distanceSegment, rapportDistance; distanceSegment = m_noeudCourant.GetDistance(m_prochainNoeud.obtenir_Position()); rapportDistance = (distanceSegment == 0) ? 0 : (vitesse / distanceSegment); m_Position.x += rapportDistance * (m_prochainNoeud.obtenir_posX() - m_noeudCourant.obtenir_posX()); m_Position.y += rapportDistance * (m_prochainNoeud.obtenir_posY() - m_noeudCourant.obtenir_posY()); if(m_noeudCourant.GetDistance(m_Position) >= distanceSegment) { m_noeudCourant = m_prochainNoeud; m_Position = new Point2D.Float(m_prochainNoeud.obtenir_posX(), m_prochainNoeud.obtenir_posY()); } m_distanceParcourue += vitesse; } public float ObtenirDistanceParcourue() { return m_distanceParcourue; } public void Reinitialiser() { m_Position = new Point2D.Float(m_portAttache.obtenir_posX(), m_portAttache.obtenir_posY()); m_tempsEcouleSurUrgence = 0; m_distanceParcourue = 0; m_noeudCourant = m_portAttache; m_prochainNoeud = m_portAttache; } }
true
true
public void AvancerTemps(ArrayList<Noeud> systemeRoutier, double vitesse) { double rapportDistance; double DistanceSegment; //Verifie si véhicule est sur un noeud if(m_noeudCourant.EstMemePosition(m_Position)) { if(m_noeudCourant.ContientUrgenceDeclencheeNonTraitee()) { AvancerTraitementUrgence(vitesse); } else { if(SystemeContientUrgenceRestante(systemeRoutier)) { m_prochainNoeud = m_strategieTraitement.ObtenirProchainNoeud(m_noeudCourant, systemeRoutier); } else { m_prochainNoeud = m_strategieAttente.ObtenirProchainNoeud(m_noeudCourant, systemeRoutier, m_portAttache); if(m_prochainNoeud == null) { m_prochainNoeud = m_noeudCourant; } } Avancer(vitesse); } } else { Avancer(vitesse); } }
public void AvancerTemps(ArrayList<Noeud> systemeRoutier, double vitesse) { double rapportDistance; double DistanceSegment; //Verifie si véhicule est sur un noeud if(m_noeudCourant.EstMemePosition(m_Position)) { if(m_noeudCourant.ContientUrgenceDeclencheeNonTraitee() && m_strategieTraitement.ObtenirProchainNoeud(m_noeudCourant, systemeRoutier) == null) { AvancerTraitementUrgence(vitesse); } else { if(SystemeContientUrgenceRestante(systemeRoutier)) { m_prochainNoeud = m_strategieTraitement.ObtenirProchainNoeud(m_noeudCourant, systemeRoutier); } else { m_prochainNoeud = m_strategieAttente.ObtenirProchainNoeud(m_noeudCourant, systemeRoutier, m_portAttache); if(m_prochainNoeud == null) { m_prochainNoeud = m_noeudCourant; } } Avancer(vitesse); } } else { Avancer(vitesse); } }
diff --git a/pmd/src/test/java/net/sourceforge/pmd/lang/java/rule/unnecessary/UnnecessaryRulesTest.java b/pmd/src/test/java/net/sourceforge/pmd/lang/java/rule/unnecessary/UnnecessaryRulesTest.java index e378e8700..10e5707d5 100644 --- a/pmd/src/test/java/net/sourceforge/pmd/lang/java/rule/unnecessary/UnnecessaryRulesTest.java +++ b/pmd/src/test/java/net/sourceforge/pmd/lang/java/rule/unnecessary/UnnecessaryRulesTest.java @@ -1,29 +1,29 @@ /** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.unnecessary; import net.sourceforge.pmd.testframework.SimpleAggregatorTst; import org.junit.Before; public class UnnecessaryRulesTest extends SimpleAggregatorTst { private static final String RULESET = "java-unnecessary"; @Before public void setUp() { addRule(RULESET, "UnnecessaryConversionTemporary"); addRule(RULESET, "UnnecessaryReturn"); addRule(RULESET, "UnnecessaryFinalModifier"); - addRule(RULESET, "UnusedNullCheckInEquals"); + addRule(RULESET, "UnusedNullCheckInEquals"); addRule(RULESET, "UselessOverridingMethod"); addRule(RULESET, "UselessOperationOnImmutable"); addRule(RULESET, "UselessParentheses"); } public static junit.framework.Test suite() { return new junit.framework.JUnit4TestAdapter(UnnecessaryRulesTest.class); } }
true
true
public void setUp() { addRule(RULESET, "UnnecessaryConversionTemporary"); addRule(RULESET, "UnnecessaryReturn"); addRule(RULESET, "UnnecessaryFinalModifier"); addRule(RULESET, "UnusedNullCheckInEquals"); addRule(RULESET, "UselessOverridingMethod"); addRule(RULESET, "UselessOperationOnImmutable"); addRule(RULESET, "UselessParentheses"); }
public void setUp() { addRule(RULESET, "UnnecessaryConversionTemporary"); addRule(RULESET, "UnnecessaryReturn"); addRule(RULESET, "UnnecessaryFinalModifier"); addRule(RULESET, "UnusedNullCheckInEquals"); addRule(RULESET, "UselessOverridingMethod"); addRule(RULESET, "UselessOperationOnImmutable"); addRule(RULESET, "UselessParentheses"); }
diff --git a/src/com/minecraftserver/pvptoolkit/PVPSpawnCampProtection.java b/src/com/minecraftserver/pvptoolkit/PVPSpawnCampProtection.java index f58872f..55005bb 100644 --- a/src/com/minecraftserver/pvptoolkit/PVPSpawnCampProtection.java +++ b/src/com/minecraftserver/pvptoolkit/PVPSpawnCampProtection.java @@ -1,96 +1,96 @@ package com.minecraftserver.pvptoolkit; import java.util.HashMap; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerRespawnEvent; import com.earth2me.essentials.IEssentials; import com.earth2me.essentials.User; public class PVPSpawnCampProtection implements Listener { private final PVPToolkit pvptoolkit; private final IEssentials ess; private int radius; private final HashMap<String, Location> protectedPlayers = new HashMap<String, Location>(); public final String MODULVERSION = "1.01"; private final boolean enabled; public PVPSpawnCampProtection(PVPToolkit toolkit) { pvptoolkit = toolkit; radius = pvptoolkit.getspawnprotectradius(); ess = (IEssentials) toolkit.getServer().getPluginManager() .getPlugin("Essentials"); enabled = true; } @EventHandler(priority = EventPriority.NORMAL) public void onPlayerDamage(EntityDamageEvent event) { if (event.getDamage() == 0 || event.isCancelled()) return; if (event instanceof EntityDamageByEntityEvent) { EntityDamageByEntityEvent e = (EntityDamageByEntityEvent) event; Entity dmgr = e.getDamager(); if (dmgr instanceof Projectile) { dmgr = ((Projectile) dmgr).getShooter(); } if ((dmgr instanceof Player) && (e.getEntity() instanceof Player)) { Player damager = (Player) dmgr; Player receiver = (Player) e.getEntity(); if (protectedPlayers.containsKey(damager.getName())) protectedPlayers.remove(damager.getName()); if (protectedPlayers.containsKey((receiver.getName()))) event.setCancelled(true); } } } @EventHandler(priority = EventPriority.NORMAL) public void onPlayerMove(PlayerMoveEvent event) { if (event.isCancelled()) return; if (protectedPlayers.containsKey(event.getPlayer().getName())) { if ((int) event.getTo().distance( protectedPlayers.get(event.getPlayer().getName())) > radius) { protectedPlayers.remove(event.getPlayer().getName()); } } } @EventHandler(priority = EventPriority.NORMAL) public void onPlayerRespawn(PlayerRespawnEvent event) { if (protectedPlayers.containsKey(event.getPlayer().getName())) protectedPlayers.remove(event.getPlayer().getName()); if (event.getPlayer().hasPermission("pvptoolkit.spawnprot")) { Location home = event.getRespawnLocation(); final User user = ess.getUser(event.getPlayer()); final Location bed = user.getBedSpawnLocation(); if (bed != null && bed.getBlock().getType() == Material.BED_BLOCK) { home = bed; } else { try { home = user.getHome(); } catch (Exception e) { - e.printStackTrace(); + home = event.getRespawnLocation(); } } event.setRespawnLocation(home); protectedPlayers.put(event.getPlayer().getName(), home); } } public void reloadcfg() { radius = pvptoolkit.getspawnprotectradius(); } }
true
true
public void onPlayerRespawn(PlayerRespawnEvent event) { if (protectedPlayers.containsKey(event.getPlayer().getName())) protectedPlayers.remove(event.getPlayer().getName()); if (event.getPlayer().hasPermission("pvptoolkit.spawnprot")) { Location home = event.getRespawnLocation(); final User user = ess.getUser(event.getPlayer()); final Location bed = user.getBedSpawnLocation(); if (bed != null && bed.getBlock().getType() == Material.BED_BLOCK) { home = bed; } else { try { home = user.getHome(); } catch (Exception e) { e.printStackTrace(); } } event.setRespawnLocation(home); protectedPlayers.put(event.getPlayer().getName(), home); } }
public void onPlayerRespawn(PlayerRespawnEvent event) { if (protectedPlayers.containsKey(event.getPlayer().getName())) protectedPlayers.remove(event.getPlayer().getName()); if (event.getPlayer().hasPermission("pvptoolkit.spawnprot")) { Location home = event.getRespawnLocation(); final User user = ess.getUser(event.getPlayer()); final Location bed = user.getBedSpawnLocation(); if (bed != null && bed.getBlock().getType() == Material.BED_BLOCK) { home = bed; } else { try { home = user.getHome(); } catch (Exception e) { home = event.getRespawnLocation(); } } event.setRespawnLocation(home); protectedPlayers.put(event.getPlayer().getName(), home); } }
diff --git a/continuum-builder/src/main/java/org/apache/continuum/builder/distributed/executor/DistributedBuildProjectTaskExecutor.java b/continuum-builder/src/main/java/org/apache/continuum/builder/distributed/executor/DistributedBuildProjectTaskExecutor.java index f3e473b40..696200ae9 100644 --- a/continuum-builder/src/main/java/org/apache/continuum/builder/distributed/executor/DistributedBuildProjectTaskExecutor.java +++ b/continuum-builder/src/main/java/org/apache/continuum/builder/distributed/executor/DistributedBuildProjectTaskExecutor.java @@ -1,426 +1,422 @@ package org.apache.continuum.builder.distributed.executor; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.continuum.builder.utils.ContinuumBuildConstant; import org.apache.continuum.dao.BuildDefinitionDao; import org.apache.continuum.dao.BuildResultDao; import org.apache.continuum.dao.ProjectDao; import org.apache.continuum.dao.ProjectScmRootDao; import org.apache.continuum.distributed.transport.slave.SlaveBuildAgentTransportClient; import org.apache.continuum.model.project.ProjectScmRoot; import org.apache.continuum.model.repository.LocalRepository; import org.apache.continuum.taskqueue.PrepareBuildProjectsTask; import org.apache.continuum.utils.ContinuumUtils; import org.apache.continuum.utils.ProjectSorter; import org.apache.continuum.utils.build.BuildTrigger; import org.apache.maven.continuum.ContinuumException; import org.apache.maven.continuum.model.project.BuildDefinition; import org.apache.maven.continuum.model.project.BuildResult; import org.apache.maven.continuum.model.project.Project; import org.apache.maven.continuum.model.scm.ChangeFile; import org.apache.maven.continuum.model.scm.ChangeSet; import org.apache.maven.continuum.model.scm.ScmResult; import org.apache.maven.continuum.project.ContinuumProjectState; import org.apache.maven.continuum.store.ContinuumStoreException; import org.codehaus.plexus.taskqueue.Task; import org.codehaus.plexus.taskqueue.execution.TaskExecutionException; import org.codehaus.plexus.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DistributedBuildProjectTaskExecutor implements DistributedBuildTaskExecutor { private static final Logger log = LoggerFactory.getLogger( DistributedBuildProjectTaskExecutor.class ); private String buildAgentUrl; private long startTime; private long endTime; /** * @plexus.requirement */ private ProjectDao projectDao; /** * @plexus.requirement */ private ProjectScmRootDao projectScmRootDao; /** * @plexus.requirement */ private BuildDefinitionDao buildDefinitionDao; /** * @plexus.requirement */ private BuildResultDao buildResultDao; public void setBuildAgentUrl( String buildAgentUrl ) { this.buildAgentUrl = buildAgentUrl; } public String getBuildAgentUrl() { return buildAgentUrl; } public void executeTask( Task task ) throws TaskExecutionException { PrepareBuildProjectsTask prepareBuildTask = (PrepareBuildProjectsTask) task; try { SlaveBuildAgentTransportClient client = new SlaveBuildAgentTransportClient( new URL( buildAgentUrl ) ); log.info( "initializing buildContext" ); List<Map<String, Object>> buildContext = initializeBuildContext( prepareBuildTask.getProjectsBuildDefinitionsMap(), prepareBuildTask.getBuildTrigger(), prepareBuildTask.getScmRootAddress(), prepareBuildTask.getProjectScmRootId() ); startTime = System.currentTimeMillis(); client.buildProjects( buildContext ); endTime = System.currentTimeMillis(); } catch ( MalformedURLException e ) { log.error( "Invalid URL " + buildAgentUrl + ", not building" ); throw new TaskExecutionException( "Invalid URL " + buildAgentUrl, e ); } catch ( Exception e ) { log.error( "Error occurred while building task", e ); endTime = System.currentTimeMillis(); createResult( prepareBuildTask, ContinuumUtils.throwableToString( e ) ); } } private List<Map<String, Object>> initializeBuildContext( Map<Integer, Integer> projectsAndBuildDefinitions, BuildTrigger buildTrigger, String scmRootAddress, int scmRootId ) throws ContinuumException { List<Map<String, Object>> buildContext = new ArrayList<Map<String, Object>>(); - List<Project> projects = new ArrayList<Project>(); try { - for ( Integer projectId : projectsAndBuildDefinitions.keySet() ) - { - Project project = projectDao.getProjectWithDependencies( projectId ); - projects.add( project ); - } + ProjectScmRoot scmRoot = projectScmRootDao.getProjectScmRoot( scmRootId ); - projects = ProjectSorter.getSortedProjects( projects, null ); + List<Project> projects = projectDao.getProjectsWithDependenciesByGroupId( scmRoot.getProjectGroup().getId() ); + List<Project> sortedProjects = ProjectSorter.getSortedProjects( projects, null ); - for ( Project project : projects ) + for ( Project project : sortedProjects ) { int buildDefinitionId = projectsAndBuildDefinitions.get( project.getId() ); BuildDefinition buildDef = buildDefinitionDao.getBuildDefinition( buildDefinitionId ); BuildResult buildResult = buildResultDao.getLatestBuildResultForProject( project.getId() ); Map<String, Object> context = new HashMap<String, Object>(); context.put( ContinuumBuildConstant.KEY_PROJECT_GROUP_ID, project.getProjectGroup().getId() ); context.put( ContinuumBuildConstant.KEY_PROJECT_GROUP_NAME, project.getProjectGroup().getName() ); context.put( ContinuumBuildConstant.KEY_SCM_ROOT_ID, scmRootId ); context.put( ContinuumBuildConstant.KEY_SCM_ROOT_ADDRESS, scmRootAddress ); context.put( ContinuumBuildConstant.KEY_PROJECT_ID, project.getId() ); context.put( ContinuumBuildConstant.KEY_PROJECT_NAME, project.getName() ); context.put( ContinuumBuildConstant.KEY_PROJECT_VERSION, project.getVersion() ); context.put( ContinuumBuildConstant.KEY_EXECUTOR_ID, project.getExecutorId() ); context.put( ContinuumBuildConstant.KEY_PROJECT_BUILD_NUMBER, project.getBuildNumber() ); context.put( ContinuumBuildConstant.KEY_SCM_URL, project.getScmUrl() ); context.put( ContinuumBuildConstant.KEY_PROJECT_STATE, project.getState() ); if ( buildResult != null ) { context.put( ContinuumBuildConstant.KEY_LATEST_UPDATE_DATE, new Date( buildResult.getStartTime() ) ); } LocalRepository localRepo = project.getProjectGroup().getLocalRepository(); if ( localRepo != null ) { context.put( ContinuumBuildConstant.KEY_LOCAL_REPOSITORY, localRepo.getLocation() ); } else { context.put( ContinuumBuildConstant.KEY_LOCAL_REPOSITORY, "" ); } if ( project.getScmUsername() == null ) { context.put( ContinuumBuildConstant.KEY_SCM_USERNAME, "" ); } else { context.put( ContinuumBuildConstant.KEY_SCM_USERNAME, project.getScmUsername() ); } if ( project.getScmPassword() == null ) { context.put( ContinuumBuildConstant.KEY_SCM_PASSWORD, "" ); } else { context.put( ContinuumBuildConstant.KEY_SCM_PASSWORD, project.getScmPassword() ); } context.put( ContinuumBuildConstant.KEY_BUILD_DEFINITION_ID, buildDefinitionId ); String buildDefinitionLabel = buildDef.getDescription(); if ( StringUtils.isEmpty( buildDefinitionLabel ) ) { buildDefinitionLabel = buildDef.getGoals(); } context.put( ContinuumBuildConstant.KEY_BUILD_DEFINITION_LABEL, buildDefinitionLabel ); context.put( ContinuumBuildConstant.KEY_BUILD_FILE, buildDef.getBuildFile() ); context.put( ContinuumBuildConstant.KEY_GOALS, buildDef.getGoals() ); if ( buildDef.getArguments() == null ) { context.put( ContinuumBuildConstant.KEY_ARGUMENTS, "" ); } else { context.put( ContinuumBuildConstant.KEY_ARGUMENTS, buildDef.getArguments() ); } context.put( ContinuumBuildConstant.KEY_TRIGGER, buildTrigger.getTrigger() ); context.put( ContinuumBuildConstant.KEY_USERNAME, buildTrigger.getUsername() ); context.put( ContinuumBuildConstant.KEY_BUILD_FRESH, buildDef.isBuildFresh() ); context.put( ContinuumBuildConstant.KEY_ALWAYS_BUILD, buildDef.isAlwaysBuild() ); context.put( ContinuumBuildConstant.KEY_OLD_SCM_CHANGES, getOldScmChanges( project.getId(), buildDefinitionId ) ); context.put( ContinuumBuildConstant.KEY_BUILD_AGENT_URL, buildAgentUrl ); context.put( ContinuumBuildConstant.KEY_MAX_JOB_EXEC_TIME, buildDef.getSchedule().getMaxJobExecutionTime() ); buildContext.add( context ); } return buildContext; } catch ( ContinuumStoreException e ) { throw new ContinuumException( "Error while initializing build context", e ); } } private void createResult( PrepareBuildProjectsTask task, String error ) throws TaskExecutionException { try { ProjectScmRoot scmRoot = projectScmRootDao.getProjectScmRootByProjectGroupAndScmRootAddress( task.getProjectGroupId(), task.getScmRootAddress() ); if ( scmRoot.getState() == ContinuumProjectState.UPDATING ) { scmRoot.setState( ContinuumProjectState.ERROR ); scmRoot.setError( error ); projectScmRootDao.updateProjectScmRoot( scmRoot ); } else { Map<Integer, Integer> map = task.getProjectsBuildDefinitionsMap(); for ( Integer projectId : map.keySet() ) { int buildDefinitionId = map.get( projectId ); Project project = projectDao.getProject( projectId ); BuildDefinition buildDef = buildDefinitionDao.getBuildDefinition( buildDefinitionId ); BuildResult latestBuildResult = buildResultDao. getLatestBuildResultForBuildDefinition( projectId, buildDefinitionId ); if ( latestBuildResult == null || ( latestBuildResult.getStartTime() >= startTime && latestBuildResult.getEndTime() > 0 && latestBuildResult.getEndTime() < endTime ) || latestBuildResult.getStartTime() < startTime ) { BuildResult buildResult = new BuildResult(); buildResult.setBuildDefinition( buildDef ); buildResult.setError( error ); buildResult.setState( ContinuumProjectState.ERROR ); buildResult.setTrigger( task.getBuildTrigger().getTrigger() ); buildResult.setUsername( task.getBuildTrigger().getUsername() ); buildResult.setStartTime( startTime ); buildResult.setEndTime( endTime ); buildResultDao.addBuildResult( project, buildResult ); } } } } catch ( ContinuumStoreException e ) { throw new TaskExecutionException( "Error while creating result", e ); } } private List<Map<String, Object>> getOldScmChanges( int projectId, int buildDefinitionId ) throws ContinuumStoreException { List<Map<String, Object>> scmChanges = new ArrayList<Map<String, Object>>(); BuildResult oldBuildResult = buildResultDao.getLatestBuildResultForBuildDefinition( projectId, buildDefinitionId ); if ( oldBuildResult != null ) { ScmResult scmResult = getOldScmResults( projectId, oldBuildResult.getBuildNumber(), oldBuildResult.getEndTime() ); scmChanges = getScmChanges( scmResult ); } return scmChanges; } private List<Map<String, Object>> getScmChanges( ScmResult scmResult ) { List<Map<String, Object>> scmChanges = new ArrayList<Map<String, Object>>(); if ( scmResult != null && scmResult.getChanges() != null ) { for ( Object obj : scmResult.getChanges() ) { ChangeSet changeSet = (ChangeSet) obj; Map<String, Object> map = new HashMap<String, Object>(); if ( StringUtils.isNotEmpty( changeSet.getAuthor() ) ) { map.put( ContinuumBuildConstant.KEY_CHANGESET_AUTHOR, changeSet.getAuthor() ); } else { map.put( ContinuumBuildConstant.KEY_CHANGESET_AUTHOR, "" ); } if ( StringUtils.isNotEmpty( changeSet.getComment() ) ) { map.put( ContinuumBuildConstant.KEY_CHANGESET_COMMENT, changeSet.getComment() ); } else { map.put( ContinuumBuildConstant.KEY_CHANGESET_COMMENT, "" ); } if ( changeSet.getDateAsDate() != null ) { map.put( ContinuumBuildConstant.KEY_CHANGESET_DATE, changeSet.getDateAsDate() ); } map.put( ContinuumBuildConstant.KEY_CHANGESET_FILES, getScmChangeFiles( changeSet.getFiles() ) ); scmChanges.add( map ); } } return scmChanges; } private List<Map<String, String>> getScmChangeFiles( List<ChangeFile> files ) { List<Map<String, String>> scmChangeFiles = new ArrayList<Map<String, String>>(); if ( files != null ) { for ( ChangeFile changeFile : files ) { Map<String, String> map = new HashMap<String, String>(); if ( StringUtils.isNotEmpty( changeFile.getName() ) ) { map.put( ContinuumBuildConstant.KEY_CHANGEFILE_NAME, changeFile.getName() ); } else { map.put( ContinuumBuildConstant.KEY_CHANGEFILE_NAME, "" ); } if ( StringUtils.isNotEmpty( changeFile.getRevision() ) ) { map.put( ContinuumBuildConstant.KEY_CHANGEFILE_REVISION, changeFile.getRevision() ); } else { map.put( ContinuumBuildConstant.KEY_CHANGEFILE_REVISION, "" ); } if ( StringUtils.isNotEmpty( changeFile.getStatus() ) ) { map.put( ContinuumBuildConstant.KEY_CHANGEFILE_STATUS, changeFile.getStatus() ); } else { map.put( ContinuumBuildConstant.KEY_CHANGEFILE_STATUS, "" ); } scmChangeFiles.add( map ); } } return scmChangeFiles; } private ScmResult getOldScmResults( int projectId, long startId, long fromDate ) throws ContinuumStoreException { List<BuildResult> results = buildResultDao.getBuildResultsForProjectFromId( projectId, startId ); ScmResult res = new ScmResult(); if ( results != null && results.size() > 0 ) { for ( BuildResult result : results ) { ScmResult scmResult = result.getScmResult(); if ( scmResult != null ) { List<ChangeSet> changes = scmResult.getChanges(); if ( changes != null ) { for ( ChangeSet changeSet : changes ) { if ( changeSet.getDate() < fromDate ) { continue; } if ( !res.getChanges().contains( changeSet ) ) { res.addChange( changeSet ); } } } } } } return res; } }
false
true
private List<Map<String, Object>> initializeBuildContext( Map<Integer, Integer> projectsAndBuildDefinitions, BuildTrigger buildTrigger, String scmRootAddress, int scmRootId ) throws ContinuumException { List<Map<String, Object>> buildContext = new ArrayList<Map<String, Object>>(); List<Project> projects = new ArrayList<Project>(); try { for ( Integer projectId : projectsAndBuildDefinitions.keySet() ) { Project project = projectDao.getProjectWithDependencies( projectId ); projects.add( project ); } projects = ProjectSorter.getSortedProjects( projects, null ); for ( Project project : projects ) { int buildDefinitionId = projectsAndBuildDefinitions.get( project.getId() ); BuildDefinition buildDef = buildDefinitionDao.getBuildDefinition( buildDefinitionId ); BuildResult buildResult = buildResultDao.getLatestBuildResultForProject( project.getId() ); Map<String, Object> context = new HashMap<String, Object>(); context.put( ContinuumBuildConstant.KEY_PROJECT_GROUP_ID, project.getProjectGroup().getId() ); context.put( ContinuumBuildConstant.KEY_PROJECT_GROUP_NAME, project.getProjectGroup().getName() ); context.put( ContinuumBuildConstant.KEY_SCM_ROOT_ID, scmRootId ); context.put( ContinuumBuildConstant.KEY_SCM_ROOT_ADDRESS, scmRootAddress ); context.put( ContinuumBuildConstant.KEY_PROJECT_ID, project.getId() ); context.put( ContinuumBuildConstant.KEY_PROJECT_NAME, project.getName() ); context.put( ContinuumBuildConstant.KEY_PROJECT_VERSION, project.getVersion() ); context.put( ContinuumBuildConstant.KEY_EXECUTOR_ID, project.getExecutorId() ); context.put( ContinuumBuildConstant.KEY_PROJECT_BUILD_NUMBER, project.getBuildNumber() ); context.put( ContinuumBuildConstant.KEY_SCM_URL, project.getScmUrl() ); context.put( ContinuumBuildConstant.KEY_PROJECT_STATE, project.getState() ); if ( buildResult != null ) { context.put( ContinuumBuildConstant.KEY_LATEST_UPDATE_DATE, new Date( buildResult.getStartTime() ) ); } LocalRepository localRepo = project.getProjectGroup().getLocalRepository(); if ( localRepo != null ) { context.put( ContinuumBuildConstant.KEY_LOCAL_REPOSITORY, localRepo.getLocation() ); } else { context.put( ContinuumBuildConstant.KEY_LOCAL_REPOSITORY, "" ); } if ( project.getScmUsername() == null ) { context.put( ContinuumBuildConstant.KEY_SCM_USERNAME, "" ); } else { context.put( ContinuumBuildConstant.KEY_SCM_USERNAME, project.getScmUsername() ); } if ( project.getScmPassword() == null ) { context.put( ContinuumBuildConstant.KEY_SCM_PASSWORD, "" ); } else { context.put( ContinuumBuildConstant.KEY_SCM_PASSWORD, project.getScmPassword() ); } context.put( ContinuumBuildConstant.KEY_BUILD_DEFINITION_ID, buildDefinitionId ); String buildDefinitionLabel = buildDef.getDescription(); if ( StringUtils.isEmpty( buildDefinitionLabel ) ) { buildDefinitionLabel = buildDef.getGoals(); } context.put( ContinuumBuildConstant.KEY_BUILD_DEFINITION_LABEL, buildDefinitionLabel ); context.put( ContinuumBuildConstant.KEY_BUILD_FILE, buildDef.getBuildFile() ); context.put( ContinuumBuildConstant.KEY_GOALS, buildDef.getGoals() ); if ( buildDef.getArguments() == null ) { context.put( ContinuumBuildConstant.KEY_ARGUMENTS, "" ); } else { context.put( ContinuumBuildConstant.KEY_ARGUMENTS, buildDef.getArguments() ); } context.put( ContinuumBuildConstant.KEY_TRIGGER, buildTrigger.getTrigger() ); context.put( ContinuumBuildConstant.KEY_USERNAME, buildTrigger.getUsername() ); context.put( ContinuumBuildConstant.KEY_BUILD_FRESH, buildDef.isBuildFresh() ); context.put( ContinuumBuildConstant.KEY_ALWAYS_BUILD, buildDef.isAlwaysBuild() ); context.put( ContinuumBuildConstant.KEY_OLD_SCM_CHANGES, getOldScmChanges( project.getId(), buildDefinitionId ) ); context.put( ContinuumBuildConstant.KEY_BUILD_AGENT_URL, buildAgentUrl ); context.put( ContinuumBuildConstant.KEY_MAX_JOB_EXEC_TIME, buildDef.getSchedule().getMaxJobExecutionTime() ); buildContext.add( context ); } return buildContext; } catch ( ContinuumStoreException e ) { throw new ContinuumException( "Error while initializing build context", e ); } }
private List<Map<String, Object>> initializeBuildContext( Map<Integer, Integer> projectsAndBuildDefinitions, BuildTrigger buildTrigger, String scmRootAddress, int scmRootId ) throws ContinuumException { List<Map<String, Object>> buildContext = new ArrayList<Map<String, Object>>(); try { ProjectScmRoot scmRoot = projectScmRootDao.getProjectScmRoot( scmRootId ); List<Project> projects = projectDao.getProjectsWithDependenciesByGroupId( scmRoot.getProjectGroup().getId() ); List<Project> sortedProjects = ProjectSorter.getSortedProjects( projects, null ); for ( Project project : sortedProjects ) { int buildDefinitionId = projectsAndBuildDefinitions.get( project.getId() ); BuildDefinition buildDef = buildDefinitionDao.getBuildDefinition( buildDefinitionId ); BuildResult buildResult = buildResultDao.getLatestBuildResultForProject( project.getId() ); Map<String, Object> context = new HashMap<String, Object>(); context.put( ContinuumBuildConstant.KEY_PROJECT_GROUP_ID, project.getProjectGroup().getId() ); context.put( ContinuumBuildConstant.KEY_PROJECT_GROUP_NAME, project.getProjectGroup().getName() ); context.put( ContinuumBuildConstant.KEY_SCM_ROOT_ID, scmRootId ); context.put( ContinuumBuildConstant.KEY_SCM_ROOT_ADDRESS, scmRootAddress ); context.put( ContinuumBuildConstant.KEY_PROJECT_ID, project.getId() ); context.put( ContinuumBuildConstant.KEY_PROJECT_NAME, project.getName() ); context.put( ContinuumBuildConstant.KEY_PROJECT_VERSION, project.getVersion() ); context.put( ContinuumBuildConstant.KEY_EXECUTOR_ID, project.getExecutorId() ); context.put( ContinuumBuildConstant.KEY_PROJECT_BUILD_NUMBER, project.getBuildNumber() ); context.put( ContinuumBuildConstant.KEY_SCM_URL, project.getScmUrl() ); context.put( ContinuumBuildConstant.KEY_PROJECT_STATE, project.getState() ); if ( buildResult != null ) { context.put( ContinuumBuildConstant.KEY_LATEST_UPDATE_DATE, new Date( buildResult.getStartTime() ) ); } LocalRepository localRepo = project.getProjectGroup().getLocalRepository(); if ( localRepo != null ) { context.put( ContinuumBuildConstant.KEY_LOCAL_REPOSITORY, localRepo.getLocation() ); } else { context.put( ContinuumBuildConstant.KEY_LOCAL_REPOSITORY, "" ); } if ( project.getScmUsername() == null ) { context.put( ContinuumBuildConstant.KEY_SCM_USERNAME, "" ); } else { context.put( ContinuumBuildConstant.KEY_SCM_USERNAME, project.getScmUsername() ); } if ( project.getScmPassword() == null ) { context.put( ContinuumBuildConstant.KEY_SCM_PASSWORD, "" ); } else { context.put( ContinuumBuildConstant.KEY_SCM_PASSWORD, project.getScmPassword() ); } context.put( ContinuumBuildConstant.KEY_BUILD_DEFINITION_ID, buildDefinitionId ); String buildDefinitionLabel = buildDef.getDescription(); if ( StringUtils.isEmpty( buildDefinitionLabel ) ) { buildDefinitionLabel = buildDef.getGoals(); } context.put( ContinuumBuildConstant.KEY_BUILD_DEFINITION_LABEL, buildDefinitionLabel ); context.put( ContinuumBuildConstant.KEY_BUILD_FILE, buildDef.getBuildFile() ); context.put( ContinuumBuildConstant.KEY_GOALS, buildDef.getGoals() ); if ( buildDef.getArguments() == null ) { context.put( ContinuumBuildConstant.KEY_ARGUMENTS, "" ); } else { context.put( ContinuumBuildConstant.KEY_ARGUMENTS, buildDef.getArguments() ); } context.put( ContinuumBuildConstant.KEY_TRIGGER, buildTrigger.getTrigger() ); context.put( ContinuumBuildConstant.KEY_USERNAME, buildTrigger.getUsername() ); context.put( ContinuumBuildConstant.KEY_BUILD_FRESH, buildDef.isBuildFresh() ); context.put( ContinuumBuildConstant.KEY_ALWAYS_BUILD, buildDef.isAlwaysBuild() ); context.put( ContinuumBuildConstant.KEY_OLD_SCM_CHANGES, getOldScmChanges( project.getId(), buildDefinitionId ) ); context.put( ContinuumBuildConstant.KEY_BUILD_AGENT_URL, buildAgentUrl ); context.put( ContinuumBuildConstant.KEY_MAX_JOB_EXEC_TIME, buildDef.getSchedule().getMaxJobExecutionTime() ); buildContext.add( context ); } return buildContext; } catch ( ContinuumStoreException e ) { throw new ContinuumException( "Error while initializing build context", e ); } }
diff --git a/src/java/org/codehaus/groovy/grails/web/servlet/GrailsDispatcherServlet.java b/src/java/org/codehaus/groovy/grails/web/servlet/GrailsDispatcherServlet.java index 04f2cd57b..ba8c7906a 100644 --- a/src/java/org/codehaus/groovy/grails/web/servlet/GrailsDispatcherServlet.java +++ b/src/java/org/codehaus/groovy/grails/web/servlet/GrailsDispatcherServlet.java @@ -1,463 +1,468 @@ /* * Copyright 2004-2005 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.grails.web.servlet; import grails.util.GrailsUtil; import java.util.Locale; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.codehaus.groovy.grails.commons.BootstrapArtefactHandler; import org.codehaus.groovy.grails.commons.GrailsApplication; import org.codehaus.groovy.grails.commons.GrailsBootstrapClass; import org.codehaus.groovy.grails.commons.GrailsClass; import org.codehaus.groovy.grails.commons.spring.GrailsApplicationContext; import org.codehaus.groovy.grails.web.context.GrailsConfigUtils; import org.codehaus.groovy.grails.web.servlet.mvc.GrailsWebRequest; import org.codehaus.groovy.grails.web.util.WebUtils; import org.springframework.beans.BeansException; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.access.BootstrapException; import org.springframework.context.ApplicationContext; import org.springframework.context.i18n.LocaleContext; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.util.Assert; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.WebRequestInterceptor; import org.springframework.web.context.support.WebApplicationContextUtils; import org.springframework.web.multipart.MultipartException; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.multipart.MultipartResolver; import org.springframework.web.servlet.DispatcherServlet; import org.springframework.web.servlet.HandlerAdapter; import org.springframework.web.servlet.HandlerExecutionChain; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.ModelAndViewDefiningException; import org.springframework.web.servlet.handler.WebRequestHandlerInterceptorAdapter; import org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter; import org.springframework.web.util.NestedServletException; /** * Handles incoming requests for Grails. * <p/> * Loads the Spring configuration based on the Grails application * in the parent application context. * * @author Steven Devijver * @author Graeme Rocher * * @since Jul 2, 2005 */ public class GrailsDispatcherServlet extends DispatcherServlet { private static final long serialVersionUID = 8295472557856192662L; private GrailsApplication application; protected HandlerInterceptor[] interceptors; protected MultipartResolver multipartResolver; private LocaleResolver localeResolver; private static final String EXCEPTION_ATTRIBUTE = "exception"; /** * Constructor. */ public GrailsDispatcherServlet() { setDetectAllHandlerMappings(true); } @Override protected void initFrameworkServlet() throws ServletException, BeansException { super.initFrameworkServlet(); initMultipartResolver(); } /** * Initialize the MultipartResolver used by this class. * If no bean is defined with the given name in the BeanFactory * for this namespace, no multipart handling is provided. * * @throws org.springframework.beans.BeansException Thrown if there is an error initializing the mutlipartResolver */ private void initMultipartResolver() throws BeansException { try { multipartResolver = getWebApplicationContext().getBean(MULTIPART_RESOLVER_BEAN_NAME, MultipartResolver.class); if (logger.isInfoEnabled()) { logger.info("Using MultipartResolver [" + multipartResolver + "]"); } } catch (NoSuchBeanDefinitionException ex) { // Default is no multipart resolver. multipartResolver = null; if (logger.isInfoEnabled()) { logger.info("Unable to locate MultipartResolver with name '" + MULTIPART_RESOLVER_BEAN_NAME + "': no multipart request handling provided"); } } } @Override protected void initStrategies(ApplicationContext context) { super.initStrategies(context); initLocaleResolver(context); } // copied from base class since it's private private void initLocaleResolver(ApplicationContext context) { try { localeResolver = context.getBean(LOCALE_RESOLVER_BEAN_NAME, LocaleResolver.class); if (logger.isDebugEnabled()) { logger.debug("Using LocaleResolver [" + localeResolver + "]"); } } catch (NoSuchBeanDefinitionException ex) { // We need to use the default. localeResolver = getDefaultStrategy(context, LocaleResolver.class); if (logger.isDebugEnabled()) { logger.debug("Unable to locate LocaleResolver with name '" + LOCALE_RESOLVER_BEAN_NAME + "': using default [" + localeResolver + "]"); } } } @Override protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) throws BeansException { WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); // construct the SpringConfig for the container managed application Assert.notNull(parent, "Grails requires a parent ApplicationContext, is the /WEB-INF/applicationContext.xml file missing?"); application = parent.getBean(GrailsApplication.APPLICATION_ID, GrailsApplication.class); WebApplicationContext webContext; if (wac instanceof GrailsApplicationContext) { webContext = wac; } else { webContext = GrailsConfigUtils.configureWebApplicationContext(getServletContext(), parent); try { GrailsConfigUtils.executeGrailsBootstraps(application, webContext, getServletContext()); } catch (Exception e) { GrailsUtil.deepSanitize(e); if (e instanceof BeansException) { throw (BeansException)e; } throw new BootstrapException("Error executing bootstraps", e); } } interceptors = establishInterceptors(webContext); return webContext; } /** * Evalutes the given WebApplicationContext for all HandlerInterceptor and WebRequestInterceptor instances * * @param webContext The WebApplicationContext * @return An array of HandlerInterceptor instances */ protected HandlerInterceptor[] establishInterceptors(WebApplicationContext webContext) { String[] interceptorNames = webContext.getBeanNamesForType(HandlerInterceptor.class); String[] webRequestInterceptors = webContext.getBeanNamesForType( WebRequestInterceptor.class); @SuppressWarnings("hiding") HandlerInterceptor[] interceptors = new HandlerInterceptor[interceptorNames.length + webRequestInterceptors.length]; // Merge the handler and web request interceptors into a single array. Note that we // start with the web request interceptors to ensure that the OpenSessionInViewInterceptor // (which is a web request interceptor) is invoked before the user-defined filters // (which are attached to a handler interceptor). This should ensure that the Hibernate // session is in the proper state if and when users access the database within their filters. int j = 0; for (String webRequestInterceptor : webRequestInterceptors) { interceptors[j++] = new WebRequestHandlerInterceptorAdapter( (WebRequestInterceptor) webContext.getBean(webRequestInterceptor)); } for (String interceptorName : interceptorNames) { interceptors[j++] = (HandlerInterceptor) webContext.getBean(interceptorName); } return interceptors; } @Override public void destroy() { WebApplicationContext webContext = getWebApplicationContext(); GrailsApplication grailsApplication = webContext.getBean(GrailsApplication.APPLICATION_ID, GrailsApplication.class); GrailsClass[] bootstraps = grailsApplication.getArtefacts(BootstrapArtefactHandler.TYPE); for (GrailsClass bootstrap : bootstraps) { ((GrailsBootstrapClass) bootstrap).callDestroy(); } super.destroy(); } /** * Dependency injection for the application. * @param application the application */ public void setApplication(GrailsApplication application) { this.application = application; } /* (non-Javadoc) * @see org.springframework.web.servlet.DispatcherServlet#doDispatch(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override protected void doDispatch(final HttpServletRequest request, HttpServletResponse response) throws Exception { request.setAttribute(LOCALE_RESOLVER_ATTRIBUTE, localeResolver); HttpServletRequest processedRequest = request; HandlerExecutionChain mappedHandler = null; int interceptorIndex = -1; // Expose current LocaleResolver and request as LocaleContext. LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext(); LocaleContextHolder.setLocaleContext(new LocaleContext() { public Locale getLocale() { return localeResolver.resolveLocale(request); } }); // If the request is an include we need to try to use the original wrapped sitemesh // response, otherwise layouts won't work properly if (WebUtils.isIncludeRequest(request)) { response = useWrappedOrOriginalResponse(response); } GrailsWebRequest requestAttributes = null; GrailsWebRequest previousRequestAttributes = null; Exception handlerException = null; try { ModelAndView mv; + boolean errorView = false; try { Object exceptionAttribute = request.getAttribute(EXCEPTION_ATTRIBUTE); // only process multipart requests if an exception hasn't occured if (exceptionAttribute == null) { processedRequest = checkMultipart(request); } // Expose current RequestAttributes to current thread. previousRequestAttributes = (GrailsWebRequest) RequestContextHolder.currentRequestAttributes(); requestAttributes = new GrailsWebRequest(processedRequest, response, getServletContext()); copyParamsFromPreviousRequest(previousRequestAttributes, requestAttributes); // Update the current web request. WebUtils.storeGrailsWebRequest(requestAttributes); if (logger.isDebugEnabled()) { logger.debug("Bound request context to thread: " + request); logger.debug("Using response object: " + response.getClass()); } // Determine handler for the current request. mappedHandler = getHandler(processedRequest, false); if (mappedHandler == null || mappedHandler.getHandler() == null) { noHandlerFound(processedRequest, response); return; } // Apply preHandle methods of registered interceptors. if (mappedHandler.getInterceptors() != null) { for (int i = 0; i < mappedHandler.getInterceptors().length; i++) { HandlerInterceptor interceptor = mappedHandler.getInterceptors()[i]; if (!interceptor.preHandle(processedRequest, response, mappedHandler.getHandler())) { triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, null); return; } interceptorIndex = i; } } // Actually invoke the handler. HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler()); mv = ha.handle(processedRequest, response, mappedHandler.getHandler()); // Do we need view name translation? if ((ha instanceof AnnotationMethodHandlerAdapter) && mv != null && !mv.hasView()) { mv.setViewName(getDefaultViewName(request)); } // Apply postHandle methods of registered interceptors. if (mappedHandler.getInterceptors() != null) { for (int i = mappedHandler.getInterceptors().length - 1; i >= 0; i--) { HandlerInterceptor interceptor = mappedHandler.getInterceptors()[i]; interceptor.postHandle(processedRequest, response, mappedHandler.getHandler(), mv); } } } catch (ModelAndViewDefiningException ex) { GrailsUtil.deepSanitize(ex); handlerException = ex; if (logger.isDebugEnabled()) { logger.debug("ModelAndViewDefiningException encountered", ex); } mv = ex.getModelAndView(); } catch (Exception ex) { GrailsUtil.deepSanitize(ex); handlerException = ex; Object handler = (mappedHandler != null ? mappedHandler.getHandler() : null); mv = processHandlerException(request, response, handler, ex); + errorView = (mv != null); } // Did the handler return a view to render? if (mv != null && !mv.wasCleared()) { // If an exception occurs in here, like a bad closing tag, // we have nothing to render. try { render(mv, processedRequest, response); + if (errorView) { + WebUtils.clearErrorRequestAttributes(request); + } } catch (Exception e) { // Only render the error view if we're not already trying to render it. // This prevents a recursion if the error page itself has errors. if (request.getAttribute(GrailsApplicationAttributes.RENDERING_ERROR_ATTRIBUTE) == null) { request.setAttribute(GrailsApplicationAttributes.RENDERING_ERROR_ATTRIBUTE, Boolean.TRUE); mv = super.processHandlerException(processedRequest, response, mappedHandler, e); handlerException = e; render(mv, processedRequest, response); } else { request.removeAttribute(GrailsApplicationAttributes.RENDERING_ERROR_ATTRIBUTE); logger.warn("Recursive rendering of error view detected.", e); try { response.setContentType("text/plain"); response.getWriter().write("Internal server error"); response.flushBuffer(); } catch (Exception e2) { logger.error("Internal server error - problem rendering error view", e2); } requestAttributes.setRenderView(false); return; } } } else { if (logger.isDebugEnabled()) { logger.debug("Null ModelAndView returned to DispatcherServlet with name '" + getServletName() + "': assuming HandlerAdapter completed request handling"); } } // Trigger after-completion for successful outcome. triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, handlerException); } catch (Exception ex) { // Trigger after-completion for thrown exception. triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, ex); throw ex; } catch (Error err) { ServletException ex = new NestedServletException("Handler processing failed", err); // Trigger after-completion for thrown exception. triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, ex); throw ex; } finally { // Clean up any resources used by a multipart request. if (processedRequest instanceof MultipartHttpServletRequest && processedRequest != request) { if (multipartResolver != null) { multipartResolver.cleanupMultipart((MultipartHttpServletRequest) processedRequest); } } request.removeAttribute(MultipartHttpServletRequest.class.getName()); // Reset thread-bound holders if (requestAttributes != null) { requestAttributes.requestCompleted(); WebUtils.storeGrailsWebRequest(previousRequestAttributes); } LocaleContextHolder.setLocaleContext(previousLocaleContext); if (logger.isDebugEnabled()) { logger.debug("Cleared thread-bound request context: " + request); } } } protected HttpServletResponse useWrappedOrOriginalResponse(HttpServletResponse response) { HttpServletResponse r = WrappedResponseHolder.getWrappedResponse(); if (r != null) return r; return response; } @SuppressWarnings("unchecked") protected void copyParamsFromPreviousRequest(GrailsWebRequest previousRequestAttributes, GrailsWebRequest requestAttributes) { Map previousParams = previousRequestAttributes.getParams(); Map params = requestAttributes.getParams(); for (Object o : previousParams.keySet()) { String name = (String) o; params.put(name, previousParams.get(name)); } } /** * Trigger afterCompletion callbacks on the mapped HandlerInterceptors. * Will just invoke afterCompletion for all interceptors whose preHandle * invocation has successfully completed and returned true. * @param mappedHandler the mapped HandlerExecutionChain * @param interceptorIndex index of last interceptor that successfully completed * @param ex Exception thrown on handler execution, or <code>null</code> if none * @see HandlerInterceptor#afterCompletion */ protected void triggerAfterCompletion( HandlerExecutionChain mappedHandler, int interceptorIndex, HttpServletRequest request, HttpServletResponse response, Exception ex) throws Exception { if (mappedHandler == null || mappedHandler.getInterceptors() == null) { return; } // Apply afterCompletion methods of registered interceptors. for (int i = interceptorIndex; i >= 0; i--) { HandlerInterceptor interceptor = mappedHandler.getInterceptors()[i]; try { interceptor.afterCompletion(request, response, mappedHandler.getHandler(), ex); } catch (Throwable e) { GrailsUtil.deepSanitize(e); logger.error("HandlerInterceptor.afterCompletion threw exception", e); } } } /** * Convert the request into a multipart request. * If no multipart resolver is set, simply use the existing request. * @param request current HTTP request * @return the processed request (multipart wrapper if necessary) */ @Override protected HttpServletRequest checkMultipart(HttpServletRequest request) throws MultipartException { // Lookup from request attribute. The resolver that handles MultiPartRequest is dealt with earlier inside DefaultUrlMappingInfo with Grails HttpServletRequest resolvedRequest = (HttpServletRequest) request.getAttribute(MultipartHttpServletRequest.class.getName()); if (resolvedRequest != null) return resolvedRequest; return request; } @Override public HandlerExecutionChain getHandler(HttpServletRequest request, boolean cache) throws Exception { return super.getHandler(request, cache); } }
false
true
protected void doDispatch(final HttpServletRequest request, HttpServletResponse response) throws Exception { request.setAttribute(LOCALE_RESOLVER_ATTRIBUTE, localeResolver); HttpServletRequest processedRequest = request; HandlerExecutionChain mappedHandler = null; int interceptorIndex = -1; // Expose current LocaleResolver and request as LocaleContext. LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext(); LocaleContextHolder.setLocaleContext(new LocaleContext() { public Locale getLocale() { return localeResolver.resolveLocale(request); } }); // If the request is an include we need to try to use the original wrapped sitemesh // response, otherwise layouts won't work properly if (WebUtils.isIncludeRequest(request)) { response = useWrappedOrOriginalResponse(response); } GrailsWebRequest requestAttributes = null; GrailsWebRequest previousRequestAttributes = null; Exception handlerException = null; try { ModelAndView mv; try { Object exceptionAttribute = request.getAttribute(EXCEPTION_ATTRIBUTE); // only process multipart requests if an exception hasn't occured if (exceptionAttribute == null) { processedRequest = checkMultipart(request); } // Expose current RequestAttributes to current thread. previousRequestAttributes = (GrailsWebRequest) RequestContextHolder.currentRequestAttributes(); requestAttributes = new GrailsWebRequest(processedRequest, response, getServletContext()); copyParamsFromPreviousRequest(previousRequestAttributes, requestAttributes); // Update the current web request. WebUtils.storeGrailsWebRequest(requestAttributes); if (logger.isDebugEnabled()) { logger.debug("Bound request context to thread: " + request); logger.debug("Using response object: " + response.getClass()); } // Determine handler for the current request. mappedHandler = getHandler(processedRequest, false); if (mappedHandler == null || mappedHandler.getHandler() == null) { noHandlerFound(processedRequest, response); return; } // Apply preHandle methods of registered interceptors. if (mappedHandler.getInterceptors() != null) { for (int i = 0; i < mappedHandler.getInterceptors().length; i++) { HandlerInterceptor interceptor = mappedHandler.getInterceptors()[i]; if (!interceptor.preHandle(processedRequest, response, mappedHandler.getHandler())) { triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, null); return; } interceptorIndex = i; } } // Actually invoke the handler. HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler()); mv = ha.handle(processedRequest, response, mappedHandler.getHandler()); // Do we need view name translation? if ((ha instanceof AnnotationMethodHandlerAdapter) && mv != null && !mv.hasView()) { mv.setViewName(getDefaultViewName(request)); } // Apply postHandle methods of registered interceptors. if (mappedHandler.getInterceptors() != null) { for (int i = mappedHandler.getInterceptors().length - 1; i >= 0; i--) { HandlerInterceptor interceptor = mappedHandler.getInterceptors()[i]; interceptor.postHandle(processedRequest, response, mappedHandler.getHandler(), mv); } } } catch (ModelAndViewDefiningException ex) { GrailsUtil.deepSanitize(ex); handlerException = ex; if (logger.isDebugEnabled()) { logger.debug("ModelAndViewDefiningException encountered", ex); } mv = ex.getModelAndView(); } catch (Exception ex) { GrailsUtil.deepSanitize(ex); handlerException = ex; Object handler = (mappedHandler != null ? mappedHandler.getHandler() : null); mv = processHandlerException(request, response, handler, ex); } // Did the handler return a view to render? if (mv != null && !mv.wasCleared()) { // If an exception occurs in here, like a bad closing tag, // we have nothing to render. try { render(mv, processedRequest, response); } catch (Exception e) { // Only render the error view if we're not already trying to render it. // This prevents a recursion if the error page itself has errors. if (request.getAttribute(GrailsApplicationAttributes.RENDERING_ERROR_ATTRIBUTE) == null) { request.setAttribute(GrailsApplicationAttributes.RENDERING_ERROR_ATTRIBUTE, Boolean.TRUE); mv = super.processHandlerException(processedRequest, response, mappedHandler, e); handlerException = e; render(mv, processedRequest, response); } else { request.removeAttribute(GrailsApplicationAttributes.RENDERING_ERROR_ATTRIBUTE); logger.warn("Recursive rendering of error view detected.", e); try { response.setContentType("text/plain"); response.getWriter().write("Internal server error"); response.flushBuffer(); } catch (Exception e2) { logger.error("Internal server error - problem rendering error view", e2); } requestAttributes.setRenderView(false); return; } } } else { if (logger.isDebugEnabled()) { logger.debug("Null ModelAndView returned to DispatcherServlet with name '" + getServletName() + "': assuming HandlerAdapter completed request handling"); } } // Trigger after-completion for successful outcome. triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, handlerException); } catch (Exception ex) { // Trigger after-completion for thrown exception. triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, ex); throw ex; } catch (Error err) { ServletException ex = new NestedServletException("Handler processing failed", err); // Trigger after-completion for thrown exception. triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, ex); throw ex; } finally { // Clean up any resources used by a multipart request. if (processedRequest instanceof MultipartHttpServletRequest && processedRequest != request) { if (multipartResolver != null) { multipartResolver.cleanupMultipart((MultipartHttpServletRequest) processedRequest); } } request.removeAttribute(MultipartHttpServletRequest.class.getName()); // Reset thread-bound holders if (requestAttributes != null) { requestAttributes.requestCompleted(); WebUtils.storeGrailsWebRequest(previousRequestAttributes); } LocaleContextHolder.setLocaleContext(previousLocaleContext); if (logger.isDebugEnabled()) { logger.debug("Cleared thread-bound request context: " + request); } } }
protected void doDispatch(final HttpServletRequest request, HttpServletResponse response) throws Exception { request.setAttribute(LOCALE_RESOLVER_ATTRIBUTE, localeResolver); HttpServletRequest processedRequest = request; HandlerExecutionChain mappedHandler = null; int interceptorIndex = -1; // Expose current LocaleResolver and request as LocaleContext. LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext(); LocaleContextHolder.setLocaleContext(new LocaleContext() { public Locale getLocale() { return localeResolver.resolveLocale(request); } }); // If the request is an include we need to try to use the original wrapped sitemesh // response, otherwise layouts won't work properly if (WebUtils.isIncludeRequest(request)) { response = useWrappedOrOriginalResponse(response); } GrailsWebRequest requestAttributes = null; GrailsWebRequest previousRequestAttributes = null; Exception handlerException = null; try { ModelAndView mv; boolean errorView = false; try { Object exceptionAttribute = request.getAttribute(EXCEPTION_ATTRIBUTE); // only process multipart requests if an exception hasn't occured if (exceptionAttribute == null) { processedRequest = checkMultipart(request); } // Expose current RequestAttributes to current thread. previousRequestAttributes = (GrailsWebRequest) RequestContextHolder.currentRequestAttributes(); requestAttributes = new GrailsWebRequest(processedRequest, response, getServletContext()); copyParamsFromPreviousRequest(previousRequestAttributes, requestAttributes); // Update the current web request. WebUtils.storeGrailsWebRequest(requestAttributes); if (logger.isDebugEnabled()) { logger.debug("Bound request context to thread: " + request); logger.debug("Using response object: " + response.getClass()); } // Determine handler for the current request. mappedHandler = getHandler(processedRequest, false); if (mappedHandler == null || mappedHandler.getHandler() == null) { noHandlerFound(processedRequest, response); return; } // Apply preHandle methods of registered interceptors. if (mappedHandler.getInterceptors() != null) { for (int i = 0; i < mappedHandler.getInterceptors().length; i++) { HandlerInterceptor interceptor = mappedHandler.getInterceptors()[i]; if (!interceptor.preHandle(processedRequest, response, mappedHandler.getHandler())) { triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, null); return; } interceptorIndex = i; } } // Actually invoke the handler. HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler()); mv = ha.handle(processedRequest, response, mappedHandler.getHandler()); // Do we need view name translation? if ((ha instanceof AnnotationMethodHandlerAdapter) && mv != null && !mv.hasView()) { mv.setViewName(getDefaultViewName(request)); } // Apply postHandle methods of registered interceptors. if (mappedHandler.getInterceptors() != null) { for (int i = mappedHandler.getInterceptors().length - 1; i >= 0; i--) { HandlerInterceptor interceptor = mappedHandler.getInterceptors()[i]; interceptor.postHandle(processedRequest, response, mappedHandler.getHandler(), mv); } } } catch (ModelAndViewDefiningException ex) { GrailsUtil.deepSanitize(ex); handlerException = ex; if (logger.isDebugEnabled()) { logger.debug("ModelAndViewDefiningException encountered", ex); } mv = ex.getModelAndView(); } catch (Exception ex) { GrailsUtil.deepSanitize(ex); handlerException = ex; Object handler = (mappedHandler != null ? mappedHandler.getHandler() : null); mv = processHandlerException(request, response, handler, ex); errorView = (mv != null); } // Did the handler return a view to render? if (mv != null && !mv.wasCleared()) { // If an exception occurs in here, like a bad closing tag, // we have nothing to render. try { render(mv, processedRequest, response); if (errorView) { WebUtils.clearErrorRequestAttributes(request); } } catch (Exception e) { // Only render the error view if we're not already trying to render it. // This prevents a recursion if the error page itself has errors. if (request.getAttribute(GrailsApplicationAttributes.RENDERING_ERROR_ATTRIBUTE) == null) { request.setAttribute(GrailsApplicationAttributes.RENDERING_ERROR_ATTRIBUTE, Boolean.TRUE); mv = super.processHandlerException(processedRequest, response, mappedHandler, e); handlerException = e; render(mv, processedRequest, response); } else { request.removeAttribute(GrailsApplicationAttributes.RENDERING_ERROR_ATTRIBUTE); logger.warn("Recursive rendering of error view detected.", e); try { response.setContentType("text/plain"); response.getWriter().write("Internal server error"); response.flushBuffer(); } catch (Exception e2) { logger.error("Internal server error - problem rendering error view", e2); } requestAttributes.setRenderView(false); return; } } } else { if (logger.isDebugEnabled()) { logger.debug("Null ModelAndView returned to DispatcherServlet with name '" + getServletName() + "': assuming HandlerAdapter completed request handling"); } } // Trigger after-completion for successful outcome. triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, handlerException); } catch (Exception ex) { // Trigger after-completion for thrown exception. triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, ex); throw ex; } catch (Error err) { ServletException ex = new NestedServletException("Handler processing failed", err); // Trigger after-completion for thrown exception. triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, ex); throw ex; } finally { // Clean up any resources used by a multipart request. if (processedRequest instanceof MultipartHttpServletRequest && processedRequest != request) { if (multipartResolver != null) { multipartResolver.cleanupMultipart((MultipartHttpServletRequest) processedRequest); } } request.removeAttribute(MultipartHttpServletRequest.class.getName()); // Reset thread-bound holders if (requestAttributes != null) { requestAttributes.requestCompleted(); WebUtils.storeGrailsWebRequest(previousRequestAttributes); } LocaleContextHolder.setLocaleContext(previousLocaleContext); if (logger.isDebugEnabled()) { logger.debug("Cleared thread-bound request context: " + request); } } }
diff --git a/lib/java/src/protocol/TBinaryProtocol.java b/lib/java/src/protocol/TBinaryProtocol.java index 2e487cd..b9167d2 100644 --- a/lib/java/src/protocol/TBinaryProtocol.java +++ b/lib/java/src/protocol/TBinaryProtocol.java @@ -1,339 +1,339 @@ // Copyright (c) 2006- Facebook // Distributed under the Thrift Software License // // See accompanying file LICENSE or visit the Thrift site at: // http://developers.facebook.com/thrift/ package com.facebook.thrift.protocol; import com.facebook.thrift.TException; import com.facebook.thrift.transport.TTransport; import com.facebook.thrift.transport.TTransportException; import java.io.UnsupportedEncodingException; /** * Binary protocol implementation for thrift. * * @author Mark Slee <[email protected]> */ public class TBinaryProtocol extends TProtocol { protected static final int VERSION_MASK = 0xffff0000; protected static final int VERSION_1 = 0x80010000; protected boolean strictRead_ = false; protected boolean strictWrite_ = true; protected int readLength_; protected boolean checkReadLength_ = false; /** * Factory */ public static class Factory implements TProtocolFactory { protected boolean strictRead_ = false; protected boolean strictWrite_ = true; public Factory() { this(false, true); } public Factory(boolean strictRead, boolean strictWrite) { strictRead_ = strictRead; strictWrite_ = strictWrite; } public TProtocol getProtocol(TTransport trans) { return new TBinaryProtocol(trans, strictRead_, strictWrite_); } } /** * Constructor */ public TBinaryProtocol(TTransport trans) { this(trans, false, true); } public TBinaryProtocol(TTransport trans, boolean strictRead, boolean strictWrite) { super(trans); strictRead_ = strictRead; strictWrite_ = strictWrite; } public void writeMessageBegin(TMessage message) throws TException { if (strictWrite_) { int version = VERSION_1 | message.type; writeI32(version); writeString(message.name); writeI32(message.seqid); } else { writeString(message.name); writeByte(message.type); writeI32(message.seqid); } } public void writeMessageEnd() {} public void writeStructBegin(TStruct struct) {} public void writeStructEnd() {} public void writeFieldBegin(TField field) throws TException { writeByte(field.type); writeI16(field.id); } public void writeFieldEnd() {} public void writeFieldStop() throws TException { writeByte(TType.STOP); } public void writeMapBegin(TMap map) throws TException { writeByte(map.keyType); writeByte(map.valueType); writeI32(map.size); } public void writeMapEnd() {} public void writeListBegin(TList list) throws TException { writeByte(list.elemType); writeI32(list.size); } public void writeListEnd() {} public void writeSetBegin(TSet set) throws TException { writeByte(set.elemType); writeI32(set.size); } public void writeSetEnd() {} public void writeBool(boolean b) throws TException { writeByte(b ? (byte)1 : (byte)0); } private byte [] bout = new byte[1]; public void writeByte(byte b) throws TException { bout[0] = b; trans_.write(bout, 0, 1); } private byte[] i16out = new byte[2]; public void writeI16(short i16) throws TException { i16out[0] = (byte)(0xff & (i16 >> 8)); i16out[1] = (byte)(0xff & (i16)); trans_.write(i16out, 0, 2); } private byte[] i32out = new byte[4]; public void writeI32(int i32) throws TException { i32out[0] = (byte)(0xff & (i32 >> 24)); i32out[1] = (byte)(0xff & (i32 >> 16)); i32out[2] = (byte)(0xff & (i32 >> 8)); i32out[3] = (byte)(0xff & (i32)); trans_.write(i32out, 0, 4); } private byte[] i64out = new byte[8]; public void writeI64(long i64) throws TException { i64out[0] = (byte)(0xff & (i64 >> 56)); i64out[1] = (byte)(0xff & (i64 >> 48)); i64out[2] = (byte)(0xff & (i64 >> 40)); i64out[3] = (byte)(0xff & (i64 >> 32)); i64out[4] = (byte)(0xff & (i64 >> 24)); i64out[5] = (byte)(0xff & (i64 >> 16)); i64out[6] = (byte)(0xff & (i64 >> 8)); i64out[7] = (byte)(0xff & (i64)); trans_.write(i64out, 0, 8); } public void writeDouble(double dub) throws TException { writeI64(Double.doubleToLongBits(dub)); } public void writeString(String str) throws TException { try { byte[] dat = str.getBytes("UTF-8"); writeI32(dat.length); trans_.write(dat, 0, dat.length); } catch (UnsupportedEncodingException uex) { throw new TException("JVM DOES NOT SUPPORT UTF-8"); } } public void writeBinary(byte[] bin) throws TException { writeI32(bin.length); trans_.write(bin, 0, bin.length); } /** * Reading methods. */ public TMessage readMessageBegin() throws TException { TMessage message = new TMessage(); int size = readI32(); if (size < 0) { int version = size & VERSION_MASK; if (version != VERSION_1) { throw new TProtocolException(TProtocolException.BAD_VERSION, "Bad version in readMessageBegin"); } - message.type = (byte)(version & 0x000000ff); + message.type = (byte)(size & 0x000000ff); message.name = readString(); message.seqid = readI32(); } else { if (strictRead_) { throw new TProtocolException(TProtocolException.BAD_VERSION, "Missing version in readMessageBegin, old client?"); } message.name = readStringBody(size); message.type = readByte(); message.seqid = readI32(); } return message; } public void readMessageEnd() {} public TStruct readStructBegin() { return new TStruct(); } public void readStructEnd() {} public TField readFieldBegin() throws TException { TField field = new TField(); field.type = readByte(); if (field.type != TType.STOP) { field.id = readI16(); } return field; } public void readFieldEnd() {} public TMap readMapBegin() throws TException { TMap map = new TMap(); map.keyType = readByte(); map.valueType = readByte(); map.size = readI32(); return map; } public void readMapEnd() {} public TList readListBegin() throws TException { TList list = new TList(); list.elemType = readByte(); list.size = readI32(); return list; } public void readListEnd() {} public TSet readSetBegin() throws TException { TSet set = new TSet(); set.elemType = readByte(); set.size = readI32(); return set; } public void readSetEnd() {} public boolean readBool() throws TException { return (readByte() == 1); } private byte[] bin = new byte[1]; public byte readByte() throws TException { readAll(bin, 0, 1); return bin[0]; } private byte[] i16rd = new byte[2]; public short readI16() throws TException { readAll(i16rd, 0, 2); return (short) (((i16rd[0] & 0xff) << 8) | ((i16rd[1] & 0xff))); } private byte[] i32rd = new byte[4]; public int readI32() throws TException { readAll(i32rd, 0, 4); return ((i32rd[0] & 0xff) << 24) | ((i32rd[1] & 0xff) << 16) | ((i32rd[2] & 0xff) << 8) | ((i32rd[3] & 0xff)); } private byte[] i64rd = new byte[8]; public long readI64() throws TException { readAll(i64rd, 0, 8); return ((long)(i64rd[0] & 0xff) << 56) | ((long)(i64rd[1] & 0xff) << 48) | ((long)(i64rd[2] & 0xff) << 40) | ((long)(i64rd[3] & 0xff) << 32) | ((long)(i64rd[4] & 0xff) << 24) | ((long)(i64rd[5] & 0xff) << 16) | ((long)(i64rd[6] & 0xff) << 8) | ((long)(i64rd[7] & 0xff)); } public double readDouble() throws TException { return Double.longBitsToDouble(readI64()); } public String readString() throws TException { int size = readI32(); return readStringBody(size); } public String readStringBody(int size) throws TException { try { checkReadLength(size); byte[] buf = new byte[size]; trans_.readAll(buf, 0, size); return new String(buf, "UTF-8"); } catch (UnsupportedEncodingException uex) { throw new TException("JVM DOES NOT SUPPORT UTF-8"); } } public byte[] readBinary() throws TException { int size = readI32(); checkReadLength(size); byte[] buf = new byte[size]; trans_.readAll(buf, 0, size); return buf; } private int readAll(byte[] buf, int off, int len) throws TException { checkReadLength(len); return trans_.readAll(buf, off, len); } public void setReadLength(int readLength) { readLength_ = readLength; checkReadLength_ = true; } protected void checkReadLength(int length) throws TException { if (checkReadLength_) { readLength_ -= length; if (readLength_ < 0) { throw new TException("Message length exceeded: " + length); } } } }
true
true
public TMessage readMessageBegin() throws TException { TMessage message = new TMessage(); int size = readI32(); if (size < 0) { int version = size & VERSION_MASK; if (version != VERSION_1) { throw new TProtocolException(TProtocolException.BAD_VERSION, "Bad version in readMessageBegin"); } message.type = (byte)(version & 0x000000ff); message.name = readString(); message.seqid = readI32(); } else { if (strictRead_) { throw new TProtocolException(TProtocolException.BAD_VERSION, "Missing version in readMessageBegin, old client?"); } message.name = readStringBody(size); message.type = readByte(); message.seqid = readI32(); } return message; }
public TMessage readMessageBegin() throws TException { TMessage message = new TMessage(); int size = readI32(); if (size < 0) { int version = size & VERSION_MASK; if (version != VERSION_1) { throw new TProtocolException(TProtocolException.BAD_VERSION, "Bad version in readMessageBegin"); } message.type = (byte)(size & 0x000000ff); message.name = readString(); message.seqid = readI32(); } else { if (strictRead_) { throw new TProtocolException(TProtocolException.BAD_VERSION, "Missing version in readMessageBegin, old client?"); } message.name = readStringBody(size); message.type = readByte(); message.seqid = readI32(); } return message; }
diff --git a/org.cloudsmith.geppetto.pp.dsl/src/org/cloudsmith/geppetto/pp/dsl/linking/PPFinder.java b/org.cloudsmith.geppetto.pp.dsl/src/org/cloudsmith/geppetto/pp/dsl/linking/PPFinder.java index 194e91da..aa860a9f 100644 --- a/org.cloudsmith.geppetto.pp.dsl/src/org/cloudsmith/geppetto/pp/dsl/linking/PPFinder.java +++ b/org.cloudsmith.geppetto.pp.dsl/src/org/cloudsmith/geppetto/pp/dsl/linking/PPFinder.java @@ -1,628 +1,628 @@ /** * Copyright (c) 2011 Cloudsmith Inc. and other contributors, as listed below. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Cloudsmith * */ package org.cloudsmith.geppetto.pp.dsl.linking; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import org.cloudsmith.geppetto.common.tracer.ITracer; import org.cloudsmith.geppetto.pp.PPPackage; import org.cloudsmith.geppetto.pp.ResourceBody; import org.cloudsmith.geppetto.pp.dsl.PPDSLConstants; import org.cloudsmith.geppetto.pp.dsl.adapters.PPImportedNamesAdapter; import org.cloudsmith.geppetto.pp.dsl.linking.NameInScopeFilter.Match; import org.cloudsmith.geppetto.pp.dsl.linking.NameInScopeFilter.SearchStrategy; import org.cloudsmith.geppetto.pp.dsl.linking.PPSearchPath.ISearchPathProvider; import org.cloudsmith.geppetto.pp.pptp.PPTPPackage; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.xtext.naming.IQualifiedNameConverter; import org.eclipse.xtext.naming.IQualifiedNameProvider; import org.eclipse.xtext.naming.QualifiedName; import org.eclipse.xtext.resource.IContainer; import org.eclipse.xtext.resource.IEObjectDescription; import org.eclipse.xtext.resource.IResourceDescription; import org.eclipse.xtext.resource.IResourceDescriptions; import org.eclipse.xtext.resource.IResourceServiceProvider; import com.google.common.base.Function; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Iterables; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.Multimaps; import com.google.inject.Inject; import com.google.inject.internal.Lists; import com.google.inject.name.Named; /** * Utility class for finding references. * */ public class PPFinder { public static class SearchResult { private List<IEObjectDescription> adjusted; private List<IEObjectDescription> raw; private SearchResult() { this.adjusted = Collections.emptyList(); this.raw = this.adjusted; } private SearchResult(List<IEObjectDescription> rawAndAdjusted) { this.adjusted = this.raw = rawAndAdjusted; } private SearchResult(List<IEObjectDescription> pathAdjusted, List<IEObjectDescription> raw) { this.adjusted = pathAdjusted; this.raw = raw; } private SearchResult addAll(SearchResult other) { this.adjusted.addAll(other.adjusted); this.raw.addAll(other.raw); return this; } public List<IEObjectDescription> getAdjusted() { return adjusted; } public List<IEObjectDescription> getRaw() { return raw; } } private final static EClass[] CLASSES_FOR_VARIABLES = { PPPackage.Literals.DEFINITION_ARGUMENT, // PPTPPackage.Literals.TP_VARIABLE, // PPTPPackage.Literals.TYPE_ARGUMENT, // PPPackage.Literals.VARIABLE_EXPRESSION }; private final static EClass[] DEF_AND_TYPE_ARGUMENTS = { PPPackage.Literals.DEFINITION_ARGUMENT, PPTPPackage.Literals.TYPE_ARGUMENT }; // Note that order is important private final static EClass[] DEF_AND_TYPE = { PPTPPackage.Literals.TYPE, PPPackage.Literals.DEFINITION }; private static final EClass[] FUNC = { PPTPPackage.Literals.FUNCTION }; private final static EClass[] CLASS_AND_TYPE = { PPPackage.Literals.HOST_CLASS_DEFINITION, PPTPPackage.Literals.TYPE }; private Resource resource; @Inject private ISearchPathProvider searchPathProvider; /** * Access to container manager for PP language */ @Inject private IContainer.Manager manager; private PPSearchPath searchPath; private Multimap<String, IEObjectDescription> exportedPerLastSegment; /** * Access to the 'pp' services (container management and more). */ @Inject private IResourceServiceProvider resourceServiceProvider; /** * Access to naming of model elements. */ @Inject private IQualifiedNameProvider fqnProvider; /** * PP FQN to/from Xtext QualifiedName converter. */ @Inject private IQualifiedNameConverter converter; /** * Access to the global index maintained by Xtext, is made via a special (non guice) provider * that is aware of the context (builder, dirty editors, etc.). It is used to obtain the * index for a particular resource. This special provider is obtained here. */ @Inject private org.eclipse.xtext.resource.impl.ResourceDescriptionsProvider indexProvider; /** * Access to runtime configurable debug trace. */ @Inject @Named(PPDSLConstants.PP_DEBUG_LINKER) private ITracer tracer; private Map<String, IEObjectDescription> metaCache; private Map<String, IEObjectDescription> metaVarCache; private void buildExportedObjectsIndex(IResourceDescription descr, IResourceDescriptions descriptionIndex) { // The current (possibly dirty) exported resources IResourceDescription dirty = resourceServiceProvider.getResourceDescriptionManager().getResourceDescription( resource); String pathToCurrent = resource.getURI().path(); Multimap<String, IEObjectDescription> map = ArrayListMultimap.create(); // add all (possibly dirty in global index) for(IEObjectDescription d : dirty.getExportedObjects()) if(d.getQualifiedName().getSegmentCount() >= 1) // names may be empty while editing map.put(d.getQualifiedName().getLastSegment(), d); // add all from global index, except those for current resource for(IEObjectDescription d : getExportedObjects(descr, descriptionIndex)) if(!d.getEObjectURI().path().equals(pathToCurrent)) map.put(d.getQualifiedName().getLastSegment(), d); exportedPerLastSegment = map; } private void cacheMetaParameters(EObject scopeDetermeningObject) { metaCache = Maps.newHashMap(); metaVarCache = Maps.newHashMap(); Resource scopeDetermeningResource = scopeDetermeningObject.eResource(); IResourceDescriptions descriptionIndex = indexProvider.getResourceDescriptions(scopeDetermeningResource); IResourceDescription descr = descriptionIndex.getResourceDescription(scopeDetermeningResource.getURI()); if(descr == null) return; // give up - some sort of clean build EClass wantedType = PPTPPackage.Literals.TYPE_ARGUMENT; for(IContainer visibleContainer : manager.getVisibleContainers(descr, descriptionIndex)) { for(IEObjectDescription objDesc : visibleContainer.getExportedObjects()) { QualifiedName q = objDesc.getQualifiedName(); if("Type".equals(q.getFirstSegment())) { if(wantedType == objDesc.getEClass() || wantedType.isSuperTypeOf(objDesc.getEClass())) metaCache.put(q.getLastSegment(), objDesc); } else if(objDesc.getEClass() == PPTPPackage.Literals.META_VARIABLE) { metaVarCache.put(q.getLastSegment(), objDesc); } } } } public void configure(EObject o) { configure(o.eResource()); } public void configure(Resource r) { resource = r; IResourceDescriptions descriptionIndex = indexProvider.getResourceDescriptions(resource); IResourceDescription descr = descriptionIndex.getResourceDescription(resource.getURI()); // Happens during start/clean in some state if(descr == null) return; manager = resourceServiceProvider.getContainerManager(); buildExportedObjectsIndex(descr, descriptionIndex); searchPath = searchPathProvider.get(r); } /** * Find an attribute being a DefinitionArgument, Property, or Parameter for the given type, or a * meta Property or Parameter defined for the type 'Type'. * * @param scopeDetermeningObject * @param fqn * @return */ public SearchResult findAttributes(EObject scopeDetermeningObject, QualifiedName fqn, PPImportedNamesAdapter importedNames) { SearchResult result = null; // do meta lookup first as this is made fast via a cache and these are used more frequent // than other parameters (measured). if(metaCache == null) cacheMetaParameters(scopeDetermeningObject); IEObjectDescription d = metaCache.get(fqn.getLastSegment()); if(d == null) result = findInherited( scopeDetermeningObject, fqn, importedNames, Lists.<QualifiedName> newArrayList(), Match.EQUALS, DEF_AND_TYPE_ARGUMENTS); else result = new SearchResult(Lists.newArrayList(d)); return result; } /** * @param resourceBody * @param fqn * @return */ public SearchResult findAttributesWithPrefix(ResourceBody resourceBody, QualifiedName fqn) { // Must be configured for the resource containing resourceBody List<IEObjectDescription> result = Lists.newArrayList(); // do meta lookup first as this is made fast via a cache and these are used more frequent // than other parameters (measured). // TODO: VERIFY that empty last segment matches ok // TODO: Make sure that length of match is same number of segments if(metaCache == null) cacheMetaParameters(resourceBody); String fqnLast = fqn.getLastSegment(); for(String name : metaCache.keySet()) if(name.startsWith(fqnLast)) result.add(metaCache.get(name)); result.addAll(findInherited( resourceBody, fqn, null, Lists.<QualifiedName> newArrayList(), Match.STARTS_WITH, DEF_AND_TYPE_ARGUMENTS).getAdjusted()); return new SearchResult(result); } public SearchResult findDefinitions(EObject scopeDetermeningResource, PPImportedNamesAdapter importedNames) { // make all segments initial char lower case (if references is to the type itself - eg. 'File' instead of // 'file', or 'Aa::Bb' instead of 'aa::bb' QualifiedName fqn2 = QualifiedName.EMPTY; // TODO: Note that order is important, TYPE has higher precedence and should be used for linking // This used to work when list was iterated per type, not it is iterated once with type check // first - thus if a definition is found before a type, it is earlier in the list. return findExternal(scopeDetermeningResource, fqn2, importedNames, Match.STARTS_WITH, DEF_AND_TYPE); } public SearchResult findDefinitions(EObject scopeDetermeningResource, String name, PPImportedNamesAdapter importedNames) { if(name == null) throw new IllegalArgumentException("name is null"); QualifiedName fqn = converter.toQualifiedName(name); // make all segments initial char lower case (if references is to the type itself - eg. 'File' instead of // 'file', or 'Aa::Bb' instead of 'aa::bb' QualifiedName fqn2 = QualifiedName.EMPTY; for(int i = 0; i < fqn.getSegmentCount(); i++) fqn2 = fqn2.append(toInitialLowerCase(fqn.getSegment(i))); // fqn2 = fqn.skipLast(1).append(toInitialLowerCase(fqn.getLastSegment())); // TODO: Note that order is important, TYPE has higher precedence and should be used for linking // This used to work when list was iterated per type, not it is iterated once with type check // first - thus if a definition is found before a type, it is earlier in the list. return findExternal(scopeDetermeningResource, fqn2, importedNames, Match.EQUALS, DEF_AND_TYPE); } private SearchResult findExternal(EObject scopeDetermeningObject, QualifiedName fqn, PPImportedNamesAdapter importedNames, SearchStrategy matchingStrategy, EClass... eClasses) { if(scopeDetermeningObject == null) throw new IllegalArgumentException("scope determening object is null"); if(fqn == null) throw new IllegalArgumentException("name is null"); if(eClasses == null || eClasses.length < 1) throw new IllegalArgumentException("eClass is null or empty"); // if(fqn.getSegmentCount() == 1 && "".equals(fqn.getSegment(0))) // throw new IllegalArgumentException("FQN has one empty segment"); // Not meaningful to record the fact that an Absolute reference was used as nothing // is named with an absolute FQN (i.e. it is only used to do lookup). final boolean absoluteFQN = fqn.getSegmentCount() > 0 && "".equals(fqn.getSegment(0)); if(importedNames != null) importedNames.add(absoluteFQN ? fqn.skipFirst(1) : fqn); List<IEObjectDescription> targets = Lists.newArrayList(); Resource scopeDetermeningResource = scopeDetermeningObject.eResource(); if(scopeDetermeningResource != resource) { // This is a lookup in the perspective of some other resource // GIVE UP (the system is cleaning / is in bad state). - if(resource == null) + if(resource == null || scopeDetermeningResource == null) return new SearchResult(targets, targets); IResourceDescriptions descriptionIndex = indexProvider.getResourceDescriptions(scopeDetermeningResource); IResourceDescription descr = descriptionIndex.getResourceDescription(scopeDetermeningResource.getURI()); // GIVE UP (the system is performing a build clean). if(descr == null) return new SearchResult(targets, targets); QualifiedName nameOfScope = getNameOfScope(scopeDetermeningObject); // for(IContainer visibleContainer : manager.getVisibleContainers(descr, descriptionIndex)) { // for(EClass aClass : eClasses) for(IEObjectDescription objDesc : new NameInScopeFilter(matchingStrategy, getExportedObjects( descr, descriptionIndex), // visibleContainer.getExportedObjects(), fqn, nameOfScope, eClasses)) targets.add(objDesc); } else { // This is lookup from the main resource perspective QualifiedName nameOfScope = getNameOfScope(scopeDetermeningObject); for(IEObjectDescription objDesc : new NameInScopeFilter(matchingStrategy, // matchingStrategy.matchStartsWith() ? exportedPerLastSegment.values() : exportedPerLastSegment.get(fqn.getLastSegment()), // fqn, nameOfScope, eClasses)) targets.add(objDesc); } if(tracer.isTracing()) { for(IEObjectDescription d : targets) tracer.trace(" : ", converter.toString(d.getName()), " in: ", d.getEObjectURI().path()); } return new SearchResult(searchPathAdjusted(targets), targets); } public SearchResult findFunction(EObject scopeDetermeningObject, QualifiedName fqn, PPImportedNamesAdapter importedNames) { return findExternal(scopeDetermeningObject, fqn, importedNames, Match.EQUALS, FUNC); } public SearchResult findFunction(EObject scopeDetermeningObject, String name, PPImportedNamesAdapter importedNames) { return findFunction(scopeDetermeningObject, converter.toQualifiedName(name), importedNames); } public SearchResult findHostClasses(EObject scopeDetermeningResource, String name, PPImportedNamesAdapter importedNames) { if(name == null) throw new IllegalArgumentException("name is null"); QualifiedName fqn = converter.toQualifiedName(name); // make last segments initial char lower case (for references to the type itself - eg. 'File' instead of // 'file'. if(fqn.getSegmentCount() == 0) return new SearchResult(); // can happen while editing fqn = fqn.skipLast(1).append(toInitialLowerCase(fqn.getLastSegment())); return findExternal(scopeDetermeningResource, fqn, importedNames, Match.EQUALS, CLASS_AND_TYPE); } private SearchResult findInherited(EObject scopeDetermeningObject, QualifiedName fqn, PPImportedNamesAdapter importedNames, List<QualifiedName> stack, SearchStrategy matchingStrategy, EClass[] classes) { // Protect against circular inheritance QualifiedName containerName = fqn.skipLast(1); if(stack.contains(containerName)) return new SearchResult(); stack.add(containerName); // find using the given name final List<IEObjectDescription> result = findExternal( scopeDetermeningObject, fqn, importedNames, matchingStrategy, classes).getAdjusted(); // Search up the inheritance chain if no match (on exact match), or if a prefix search if(result.isEmpty() || !matchingStrategy.isExists()) { // find the parent type if(containerName.getSegmentCount() > 0) { // there was a parent List<IEObjectDescription> parentResult = findExternal( scopeDetermeningObject, containerName, importedNames, Match.EQUALS, DEF_AND_TYPE).getAdjusted(); if(!parentResult.isEmpty()) { IEObjectDescription firstFound = parentResult.get(0); String parentName = firstFound.getUserData(PPDSLConstants.PARENT_NAME_DATA); if(parentName != null && parentName.length() > 0) { // find attributes for parent QualifiedName attributeFqn = converter.toQualifiedName(parentName); attributeFqn = attributeFqn.append(fqn.getLastSegment()); result.addAll(findInherited( scopeDetermeningObject, attributeFqn, importedNames, stack, matchingStrategy, classes).getAdjusted()); } } } } return new SearchResult(result); } /** * Finds a parameter or variable with the given name. More than one may be returned if the definition * is ambiguous. * * @param scopeDetermeningResource * @param name * @param importedNames * @return */ public SearchResult findVariable(EObject scopeDetermeningResource, QualifiedName fqn, PPImportedNamesAdapter importedNames) { if(fqn == null) throw new IllegalArgumentException("fqn is null"); return findVariables(scopeDetermeningResource, fqn, importedNames, Match.NO_OUTER); } /** * Finds a parameter or variable with the given name. More than one may be returned if the definition * is ambiguous. * * @param scopeDetermeningResource * @param name * @param importedNames * @return */ public SearchResult findVariable(EObject scopeDetermeningResource, String name, PPImportedNamesAdapter importedNames) { if(name == null) throw new IllegalArgumentException("name is null"); QualifiedName fqn = converter.toQualifiedName(name); return findVariables(scopeDetermeningResource, fqn, importedNames, Match.NO_OUTER_EXISTS); } /** * Finds all matching variables in current and inherited scopes. * * @param scopeDetermeningResource * @param name * @param importedNames * @return */ public SearchResult findVariables(EObject scopeDetermeningResource, QualifiedName fqn, PPImportedNamesAdapter importedNames) { if(fqn == null) throw new IllegalArgumentException("name is null"); return findVariables(scopeDetermeningResource, fqn, importedNames, Match.NO_OUTER); } /** * Fins parameters and/or variables with matching name using the given matching/search strategy. * * @param scopeDetermeningObject * @param fqn * @param importedNames * @param matchingStrategy * @return */ public SearchResult findVariables(EObject scopeDetermeningObject, QualifiedName fqn, PPImportedNamesAdapter importedNames, SearchStrategy matchingStrategy) { if(metaCache == null) cacheMetaParameters(scopeDetermeningObject); final boolean singleSegment = fqn.getSegmentCount() == 1; // If variable is a meta var, it is always found if(singleSegment) { IEObjectDescription metaVar = metaVarCache.get(fqn.getLastSegment()); if(metaVar != null) return new SearchResult(Lists.newArrayList(metaVar), Lists.newArrayList(metaVar)); // what a waste... // if inside a define, all meta parameters are available if(isContainedInDefinition(scopeDetermeningObject)) { IEObjectDescription metaParam = metaCache.get(fqn.getLastSegment()); if(metaParam != null) return new SearchResult(Lists.newArrayList(metaParam), Lists.newArrayList(metaParam)); // what a waste... } } SearchResult result = findExternal( scopeDetermeningObject, fqn, importedNames, matchingStrategy, CLASSES_FOR_VARIABLES); if(result.getAdjusted().size() > 0 && matchingStrategy.isExists()) return result; QualifiedName scopeName = getNameOfScope(scopeDetermeningObject); if(!scopeName.isEmpty()) { fqn = scopeName.append(fqn); return result.addAll(findInherited( scopeDetermeningObject, fqn, importedNames, Lists.<QualifiedName> newArrayList(), matchingStrategy, CLASSES_FOR_VARIABLES)); } return result; } /** * Finds all matching variables in current and inherited scopes. * * @param scopeDetermeningResource * @param name * @param importedNames * @return */ public SearchResult findVariables(EObject scopeDetermeningResource, String name, PPImportedNamesAdapter importedNames) { if(name == null) throw new IllegalArgumentException("name is null"); QualifiedName fqn = converter.toQualifiedName(name); return findVariables(scopeDetermeningResource, fqn, importedNames, Match.NO_OUTER); } public SearchResult findVariablesPrefixed(EObject scopeDetermeningObject, QualifiedName fqn, PPImportedNamesAdapter importedNames) { return findVariables(scopeDetermeningObject, fqn, importedNames, Match.NO_OUTER_STARTS_WITH); } /** * Produces an unmodifiable list of everything visible to the resource. * * @return */ public Collection<IEObjectDescription> getExportedDescriptions() { return Collections.unmodifiableCollection(exportedPerLastSegment.values()); } /** * Produces iterable over all visible exports from all visible containers. * * @param descr * @param descriptionIndex * @return */ private Iterable<IEObjectDescription> getExportedObjects(IResourceDescription descr, IResourceDescriptions descriptionIndex) { return Iterables.concat(Iterables.transform( manager.getVisibleContainers(descr, descriptionIndex), new Function<IContainer, Iterable<IEObjectDescription>>() { @Override public Iterable<IEObjectDescription> apply(IContainer from) { return from.getExportedObjects(); } })); } /** * Produces an unmodifiable Multimap mapping from last segment to list of visible exports * ending with that value. * * @return */ public Multimap<String, IEObjectDescription> getExportedPerLastSegement() { return Multimaps.unmodifiableMultimap(exportedPerLastSegment); } /** * Produces the name of the scope where the given object 'o' is contained. * * @param o * @return */ public QualifiedName getNameOfScope(EObject o) { QualifiedName result = null; for(; o != null; o = o.eContainer()) { result = fqnProvider.getFullyQualifiedName(o); if(result != null) return result; } return QualifiedName.EMPTY; } private boolean isContainedInDefinition(EObject scoped) { for(EObject o = scoped; o != null; o = o.eContainer()) if(o.eClass() == PPPackage.Literals.DEFINITION) return true; return false; } /** * Adjusts the list of found targets in accordance with the search path for the resource being * linked. This potentially resolves ambiguities (if found result is further away on the path). * May return more than one result, if more than one resolution exist with the same path index. * * @param targets * @return list of descriptions with lowest index. */ private List<IEObjectDescription> searchPathAdjusted(List<IEObjectDescription> targets) { int minIdx = Integer.MAX_VALUE; List<IEObjectDescription> result = Lists.newArrayList(); for(IEObjectDescription d : targets) { int idx = searchPath.searchIndexOf(d); if(idx < 0) continue; // not found, skip if(idx < minIdx) { minIdx = idx; result.clear(); // forget worse result } // only remember if equal to best found so far if(idx <= minIdx) result.add(d); } return result; } private String toInitialLowerCase(String s) { if(s.length() < 1 || Character.isLowerCase(s.charAt(0))) return s; StringBuilder buf = new StringBuilder(s); buf.setCharAt(0, Character.toLowerCase(buf.charAt(0))); return buf.toString(); } }
true
true
private SearchResult findExternal(EObject scopeDetermeningObject, QualifiedName fqn, PPImportedNamesAdapter importedNames, SearchStrategy matchingStrategy, EClass... eClasses) { if(scopeDetermeningObject == null) throw new IllegalArgumentException("scope determening object is null"); if(fqn == null) throw new IllegalArgumentException("name is null"); if(eClasses == null || eClasses.length < 1) throw new IllegalArgumentException("eClass is null or empty"); // if(fqn.getSegmentCount() == 1 && "".equals(fqn.getSegment(0))) // throw new IllegalArgumentException("FQN has one empty segment"); // Not meaningful to record the fact that an Absolute reference was used as nothing // is named with an absolute FQN (i.e. it is only used to do lookup). final boolean absoluteFQN = fqn.getSegmentCount() > 0 && "".equals(fqn.getSegment(0)); if(importedNames != null) importedNames.add(absoluteFQN ? fqn.skipFirst(1) : fqn); List<IEObjectDescription> targets = Lists.newArrayList(); Resource scopeDetermeningResource = scopeDetermeningObject.eResource(); if(scopeDetermeningResource != resource) { // This is a lookup in the perspective of some other resource // GIVE UP (the system is cleaning / is in bad state). if(resource == null) return new SearchResult(targets, targets); IResourceDescriptions descriptionIndex = indexProvider.getResourceDescriptions(scopeDetermeningResource); IResourceDescription descr = descriptionIndex.getResourceDescription(scopeDetermeningResource.getURI()); // GIVE UP (the system is performing a build clean). if(descr == null) return new SearchResult(targets, targets); QualifiedName nameOfScope = getNameOfScope(scopeDetermeningObject); // for(IContainer visibleContainer : manager.getVisibleContainers(descr, descriptionIndex)) { // for(EClass aClass : eClasses) for(IEObjectDescription objDesc : new NameInScopeFilter(matchingStrategy, getExportedObjects( descr, descriptionIndex), // visibleContainer.getExportedObjects(), fqn, nameOfScope, eClasses)) targets.add(objDesc); } else { // This is lookup from the main resource perspective QualifiedName nameOfScope = getNameOfScope(scopeDetermeningObject); for(IEObjectDescription objDesc : new NameInScopeFilter(matchingStrategy, // matchingStrategy.matchStartsWith() ? exportedPerLastSegment.values() : exportedPerLastSegment.get(fqn.getLastSegment()), // fqn, nameOfScope, eClasses)) targets.add(objDesc); } if(tracer.isTracing()) { for(IEObjectDescription d : targets) tracer.trace(" : ", converter.toString(d.getName()), " in: ", d.getEObjectURI().path()); } return new SearchResult(searchPathAdjusted(targets), targets); }
private SearchResult findExternal(EObject scopeDetermeningObject, QualifiedName fqn, PPImportedNamesAdapter importedNames, SearchStrategy matchingStrategy, EClass... eClasses) { if(scopeDetermeningObject == null) throw new IllegalArgumentException("scope determening object is null"); if(fqn == null) throw new IllegalArgumentException("name is null"); if(eClasses == null || eClasses.length < 1) throw new IllegalArgumentException("eClass is null or empty"); // if(fqn.getSegmentCount() == 1 && "".equals(fqn.getSegment(0))) // throw new IllegalArgumentException("FQN has one empty segment"); // Not meaningful to record the fact that an Absolute reference was used as nothing // is named with an absolute FQN (i.e. it is only used to do lookup). final boolean absoluteFQN = fqn.getSegmentCount() > 0 && "".equals(fqn.getSegment(0)); if(importedNames != null) importedNames.add(absoluteFQN ? fqn.skipFirst(1) : fqn); List<IEObjectDescription> targets = Lists.newArrayList(); Resource scopeDetermeningResource = scopeDetermeningObject.eResource(); if(scopeDetermeningResource != resource) { // This is a lookup in the perspective of some other resource // GIVE UP (the system is cleaning / is in bad state). if(resource == null || scopeDetermeningResource == null) return new SearchResult(targets, targets); IResourceDescriptions descriptionIndex = indexProvider.getResourceDescriptions(scopeDetermeningResource); IResourceDescription descr = descriptionIndex.getResourceDescription(scopeDetermeningResource.getURI()); // GIVE UP (the system is performing a build clean). if(descr == null) return new SearchResult(targets, targets); QualifiedName nameOfScope = getNameOfScope(scopeDetermeningObject); // for(IContainer visibleContainer : manager.getVisibleContainers(descr, descriptionIndex)) { // for(EClass aClass : eClasses) for(IEObjectDescription objDesc : new NameInScopeFilter(matchingStrategy, getExportedObjects( descr, descriptionIndex), // visibleContainer.getExportedObjects(), fqn, nameOfScope, eClasses)) targets.add(objDesc); } else { // This is lookup from the main resource perspective QualifiedName nameOfScope = getNameOfScope(scopeDetermeningObject); for(IEObjectDescription objDesc : new NameInScopeFilter(matchingStrategy, // matchingStrategy.matchStartsWith() ? exportedPerLastSegment.values() : exportedPerLastSegment.get(fqn.getLastSegment()), // fqn, nameOfScope, eClasses)) targets.add(objDesc); } if(tracer.isTracing()) { for(IEObjectDescription d : targets) tracer.trace(" : ", converter.toString(d.getName()), " in: ", d.getEObjectURI().path()); } return new SearchResult(searchPathAdjusted(targets), targets); }
diff --git a/src/com/ziclix/python/sql/util/PyArgParser.java b/src/com/ziclix/python/sql/util/PyArgParser.java index 77504b02..74451f4e 100644 --- a/src/com/ziclix/python/sql/util/PyArgParser.java +++ b/src/com/ziclix/python/sql/util/PyArgParser.java @@ -1,133 +1,133 @@ /* * Jython Database Specification API 2.0 * * $Id$ * * Copyright (c) 2001 brian zimmer <[email protected]> * */ package com.ziclix.python.sql.util; import org.python.core.Py; import org.python.core.PyObject; import java.util.HashMap; import java.util.Map; /** * Parse the args and kws for a method call. * * @author brian zimmer * @version $Revision$ */ public class PyArgParser extends Object { /** Field keywords. */ protected Map<String, PyObject> keywords; /** Field arguments. */ protected PyObject[] arguments; /** * Construct a parser with the arguments and keywords. */ public PyArgParser(PyObject[] args, String[] kws) { keywords = new HashMap<String, PyObject>(); arguments = null; parse(args, kws); } /** * Method parse * * @param args * @param kws */ protected void parse(PyObject[] args, String[] kws) { // walk backwards through the kws and build the map int largs = args.length; if (kws != null) { - for (String kw: kws) { - keywords.put(kw, args[--largs]); + for (int i = kws.length - 1; i >= 0; i--) { + keywords.put(kws[i], args[--largs]); } } arguments = new PyObject[largs]; System.arraycopy(args, 0, arguments, 0, largs); } /** * How many keywords? */ public int numKw() { return keywords.keySet().size(); } /** * Does the keyword exist? */ public boolean hasKw(String kw) { return keywords.containsKey(kw); } /** * Return the value for the keyword, raise a KeyError if the keyword does * not exist. */ public PyObject kw(String kw) { if (!hasKw(kw)) { throw Py.KeyError(kw); } return keywords.get(kw); } /** * Return the value for the keyword, return the default if the keyword does * not exist. */ public PyObject kw(String kw, PyObject def) { if (!hasKw(kw)) { return def; } return keywords.get(kw); } /** * Get the array of keywords. */ public String[] kws() { return keywords.keySet().toArray(new String[0]); } /** * Get the number of arguments. */ public int numArg() { return arguments.length; } /** * Return the argument at the given index, raise an IndexError if out of range. */ public PyObject arg(int index) { if (index >= 0 && index <= arguments.length - 1) { return arguments[index]; } throw Py.IndexError("index out of range"); } /** * Return the argument at the given index, or the default if the index is out of range. */ public PyObject arg(int index, PyObject def) { if (index >= 0 && index <= arguments.length - 1) { return arguments[index]; } return def; } }
true
true
protected void parse(PyObject[] args, String[] kws) { // walk backwards through the kws and build the map int largs = args.length; if (kws != null) { for (String kw: kws) { keywords.put(kw, args[--largs]); } } arguments = new PyObject[largs]; System.arraycopy(args, 0, arguments, 0, largs); }
protected void parse(PyObject[] args, String[] kws) { // walk backwards through the kws and build the map int largs = args.length; if (kws != null) { for (int i = kws.length - 1; i >= 0; i--) { keywords.put(kws[i], args[--largs]); } } arguments = new PyObject[largs]; System.arraycopy(args, 0, arguments, 0, largs); }
diff --git a/web/src/org/openmrs/module/simplelabentry/web/controller/LabEntryPortletController.java b/web/src/org/openmrs/module/simplelabentry/web/controller/LabEntryPortletController.java index 4f0a773..9600c16 100644 --- a/web/src/org/openmrs/module/simplelabentry/web/controller/LabEntryPortletController.java +++ b/web/src/org/openmrs/module/simplelabentry/web/controller/LabEntryPortletController.java @@ -1,112 +1,112 @@ package org.openmrs.module.simplelabentry.web.controller; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openmrs.Concept; import org.openmrs.Location; import org.openmrs.Order; import org.openmrs.OrderType; import org.openmrs.Patient; import org.openmrs.PatientIdentifierType; import org.openmrs.api.OrderService.ORDER_STATUS; import org.openmrs.api.context.Context; import org.openmrs.module.simplelabentry.SimpleLabEntryService; import org.openmrs.module.simplelabentry.util.SimpleLabEntryUtil; import org.openmrs.web.controller.PortletController; import org.springframework.util.StringUtils; public class LabEntryPortletController extends PortletController { protected final Log log = LogFactory.getLog(getClass()); @SuppressWarnings("unchecked") protected void populateModel(HttpServletRequest request, Map model) { SimpleLabEntryService ls = (SimpleLabEntryService) Context.getService(SimpleLabEntryService.class); // Supported LabTest Sets model.put("labTestConcepts", ls.getSupportedLabSets()); // Retrieve Orders that Match Input Parameters String identifier = (String)model.get("identifier"); String orderLocationId = (String)model.get("orderLocation"); String orderSetConceptId = (String)model.get("orderConcept"); String orderDateStr = (String)model.get("orderDate"); String currentGroupVal = request.getParameter("groupKey"); if (currentGroupVal != null) { String[] split = currentGroupVal.split("\\."); orderLocationId = split.length >= 1 ? split[0] : ""; orderDateStr = split.length >= 2 ? split[1] : ""; orderSetConceptId = split.length >= 3 ? split[2] : ""; // Make sure the concept ID is set in the model. Used by orderEntry.jsp to set the right checkbox model.put("groupConceptId", orderSetConceptId); } //This is a TODO //model.put("failureConceptId", SimpleLabEntryUtil.getTestFailureConcept((String) model.get("groupConceptId"))); String limit = (String)model.get("limit"); // Retrieve global properties OrderType ot = (OrderType) SimpleLabEntryUtil.getLabOrderType(); if (ot == null) throw new RuntimeException("Please set the global property simplelabentry.labOrderType correctly."); String orderTypeId = ot.getOrderTypeId().toString(); model.put("orderTypeId", orderTypeId); log.debug("Retrieving orders for: location="+orderLocationId+",concept="+orderSetConceptId+"," +"date="+orderDateStr+",type="+orderTypeId+",limit="+limit); PatientIdentifierType pit = (PatientIdentifierType) SimpleLabEntryUtil.getPatientIdentifierType(); if (pit == null) throw new RuntimeException("Please set the global property simplelabentry.patientIdentifierType correctly."); model.put("patientIdentifierType", pit); List<Order> labOrderList = new ArrayList<Order>(); try { Concept concept = StringUtils.hasText(orderSetConceptId) ? Context.getConceptService().getConcept(Integer.parseInt(orderSetConceptId)) : null; Location location = StringUtils.hasText(orderLocationId) ? Context.getLocationService().getLocation(Integer.parseInt(orderLocationId)) : null; Date orderDate = StringUtils.hasText(orderDateStr) ? Context.getDateFormat().parse(orderDateStr) : null; ORDER_STATUS status = "open".equals(limit) ? ORDER_STATUS.CURRENT : "closed".equals(limit) ? ORDER_STATUS.COMPLETE : ORDER_STATUS.NOTVOIDED; List<Patient> patients = null; boolean check = true; if (StringUtils.hasText(identifier)) { patients = Context.getPatientService().getPatients(null, identifier, null, true); try { Patient p = Context.getPatientService().getPatient(Integer.parseInt(identifier)); if (p != null && !patients.contains(p)) { patients.add(p); } } catch (Exception e) {} if (patients.isEmpty()) { check = false; } log.debug("Found: " + patients + " for identifier=" + identifier); } if (check) { // Retrieve matching orders if (patients != null || concept != null || location != null || orderDate != null) { labOrderList = ls.getLabOrders(concept, location, orderDate, status, patients); log.debug("Found: " + labOrderList.size() + " LabOrders"); } } } catch (Exception e) { throw new RuntimeException("Server Error: Unable to load order list.", e); } model.put("labOrders", labOrderList); model.put("notTests", SimpleLabEntryUtil.getConceptIdsInLabSetsThatAreNotTests()); model.put("patientIdentifierType", SimpleLabEntryUtil.getPatientIdentifierType()); - model.put("programToDisplay", SimpleLabEntryUtil.getProgram().getName()); + model.put("programToDisplay", SimpleLabEntryUtil.getProgram().getProgramId()); model.put("workflowToDisplay", SimpleLabEntryUtil.getWorkflow().getName()); } }
true
true
protected void populateModel(HttpServletRequest request, Map model) { SimpleLabEntryService ls = (SimpleLabEntryService) Context.getService(SimpleLabEntryService.class); // Supported LabTest Sets model.put("labTestConcepts", ls.getSupportedLabSets()); // Retrieve Orders that Match Input Parameters String identifier = (String)model.get("identifier"); String orderLocationId = (String)model.get("orderLocation"); String orderSetConceptId = (String)model.get("orderConcept"); String orderDateStr = (String)model.get("orderDate"); String currentGroupVal = request.getParameter("groupKey"); if (currentGroupVal != null) { String[] split = currentGroupVal.split("\\."); orderLocationId = split.length >= 1 ? split[0] : ""; orderDateStr = split.length >= 2 ? split[1] : ""; orderSetConceptId = split.length >= 3 ? split[2] : ""; // Make sure the concept ID is set in the model. Used by orderEntry.jsp to set the right checkbox model.put("groupConceptId", orderSetConceptId); } //This is a TODO //model.put("failureConceptId", SimpleLabEntryUtil.getTestFailureConcept((String) model.get("groupConceptId"))); String limit = (String)model.get("limit"); // Retrieve global properties OrderType ot = (OrderType) SimpleLabEntryUtil.getLabOrderType(); if (ot == null) throw new RuntimeException("Please set the global property simplelabentry.labOrderType correctly."); String orderTypeId = ot.getOrderTypeId().toString(); model.put("orderTypeId", orderTypeId); log.debug("Retrieving orders for: location="+orderLocationId+",concept="+orderSetConceptId+"," +"date="+orderDateStr+",type="+orderTypeId+",limit="+limit); PatientIdentifierType pit = (PatientIdentifierType) SimpleLabEntryUtil.getPatientIdentifierType(); if (pit == null) throw new RuntimeException("Please set the global property simplelabentry.patientIdentifierType correctly."); model.put("patientIdentifierType", pit); List<Order> labOrderList = new ArrayList<Order>(); try { Concept concept = StringUtils.hasText(orderSetConceptId) ? Context.getConceptService().getConcept(Integer.parseInt(orderSetConceptId)) : null; Location location = StringUtils.hasText(orderLocationId) ? Context.getLocationService().getLocation(Integer.parseInt(orderLocationId)) : null; Date orderDate = StringUtils.hasText(orderDateStr) ? Context.getDateFormat().parse(orderDateStr) : null; ORDER_STATUS status = "open".equals(limit) ? ORDER_STATUS.CURRENT : "closed".equals(limit) ? ORDER_STATUS.COMPLETE : ORDER_STATUS.NOTVOIDED; List<Patient> patients = null; boolean check = true; if (StringUtils.hasText(identifier)) { patients = Context.getPatientService().getPatients(null, identifier, null, true); try { Patient p = Context.getPatientService().getPatient(Integer.parseInt(identifier)); if (p != null && !patients.contains(p)) { patients.add(p); } } catch (Exception e) {} if (patients.isEmpty()) { check = false; } log.debug("Found: " + patients + " for identifier=" + identifier); } if (check) { // Retrieve matching orders if (patients != null || concept != null || location != null || orderDate != null) { labOrderList = ls.getLabOrders(concept, location, orderDate, status, patients); log.debug("Found: " + labOrderList.size() + " LabOrders"); } } } catch (Exception e) { throw new RuntimeException("Server Error: Unable to load order list.", e); } model.put("labOrders", labOrderList); model.put("notTests", SimpleLabEntryUtil.getConceptIdsInLabSetsThatAreNotTests()); model.put("patientIdentifierType", SimpleLabEntryUtil.getPatientIdentifierType()); model.put("programToDisplay", SimpleLabEntryUtil.getProgram().getName()); model.put("workflowToDisplay", SimpleLabEntryUtil.getWorkflow().getName()); }
protected void populateModel(HttpServletRequest request, Map model) { SimpleLabEntryService ls = (SimpleLabEntryService) Context.getService(SimpleLabEntryService.class); // Supported LabTest Sets model.put("labTestConcepts", ls.getSupportedLabSets()); // Retrieve Orders that Match Input Parameters String identifier = (String)model.get("identifier"); String orderLocationId = (String)model.get("orderLocation"); String orderSetConceptId = (String)model.get("orderConcept"); String orderDateStr = (String)model.get("orderDate"); String currentGroupVal = request.getParameter("groupKey"); if (currentGroupVal != null) { String[] split = currentGroupVal.split("\\."); orderLocationId = split.length >= 1 ? split[0] : ""; orderDateStr = split.length >= 2 ? split[1] : ""; orderSetConceptId = split.length >= 3 ? split[2] : ""; // Make sure the concept ID is set in the model. Used by orderEntry.jsp to set the right checkbox model.put("groupConceptId", orderSetConceptId); } //This is a TODO //model.put("failureConceptId", SimpleLabEntryUtil.getTestFailureConcept((String) model.get("groupConceptId"))); String limit = (String)model.get("limit"); // Retrieve global properties OrderType ot = (OrderType) SimpleLabEntryUtil.getLabOrderType(); if (ot == null) throw new RuntimeException("Please set the global property simplelabentry.labOrderType correctly."); String orderTypeId = ot.getOrderTypeId().toString(); model.put("orderTypeId", orderTypeId); log.debug("Retrieving orders for: location="+orderLocationId+",concept="+orderSetConceptId+"," +"date="+orderDateStr+",type="+orderTypeId+",limit="+limit); PatientIdentifierType pit = (PatientIdentifierType) SimpleLabEntryUtil.getPatientIdentifierType(); if (pit == null) throw new RuntimeException("Please set the global property simplelabentry.patientIdentifierType correctly."); model.put("patientIdentifierType", pit); List<Order> labOrderList = new ArrayList<Order>(); try { Concept concept = StringUtils.hasText(orderSetConceptId) ? Context.getConceptService().getConcept(Integer.parseInt(orderSetConceptId)) : null; Location location = StringUtils.hasText(orderLocationId) ? Context.getLocationService().getLocation(Integer.parseInt(orderLocationId)) : null; Date orderDate = StringUtils.hasText(orderDateStr) ? Context.getDateFormat().parse(orderDateStr) : null; ORDER_STATUS status = "open".equals(limit) ? ORDER_STATUS.CURRENT : "closed".equals(limit) ? ORDER_STATUS.COMPLETE : ORDER_STATUS.NOTVOIDED; List<Patient> patients = null; boolean check = true; if (StringUtils.hasText(identifier)) { patients = Context.getPatientService().getPatients(null, identifier, null, true); try { Patient p = Context.getPatientService().getPatient(Integer.parseInt(identifier)); if (p != null && !patients.contains(p)) { patients.add(p); } } catch (Exception e) {} if (patients.isEmpty()) { check = false; } log.debug("Found: " + patients + " for identifier=" + identifier); } if (check) { // Retrieve matching orders if (patients != null || concept != null || location != null || orderDate != null) { labOrderList = ls.getLabOrders(concept, location, orderDate, status, patients); log.debug("Found: " + labOrderList.size() + " LabOrders"); } } } catch (Exception e) { throw new RuntimeException("Server Error: Unable to load order list.", e); } model.put("labOrders", labOrderList); model.put("notTests", SimpleLabEntryUtil.getConceptIdsInLabSetsThatAreNotTests()); model.put("patientIdentifierType", SimpleLabEntryUtil.getPatientIdentifierType()); model.put("programToDisplay", SimpleLabEntryUtil.getProgram().getProgramId()); model.put("workflowToDisplay", SimpleLabEntryUtil.getWorkflow().getName()); }
diff --git a/gerrit-gwtui/src/main/java/com/google/gerrit/client/changes/CommitMessageBlock.java b/gerrit-gwtui/src/main/java/com/google/gerrit/client/changes/CommitMessageBlock.java index 86a2f5ce7..561b43f6f 100644 --- a/gerrit-gwtui/src/main/java/com/google/gerrit/client/changes/CommitMessageBlock.java +++ b/gerrit-gwtui/src/main/java/com/google/gerrit/client/changes/CommitMessageBlock.java @@ -1,107 +1,109 @@ // Copyright (C) 2010 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.client.changes; import com.google.gerrit.client.Gerrit; import com.google.gerrit.client.ui.ChangeLink; import com.google.gerrit.client.ui.CommentLinkProcessor; import com.google.gerrit.reviewdb.client.Change; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.PreElement; import com.google.gwt.dom.client.Style.Display; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.HTMLPanel; import com.google.gwt.user.client.ui.SimplePanel; import com.google.gwtexpui.clippy.client.CopyableLabel; import com.google.gwtexpui.globalkey.client.KeyCommandSet; import com.google.gwtexpui.safehtml.client.SafeHtml; import com.google.gwtexpui.safehtml.client.SafeHtmlBuilder; public class CommitMessageBlock extends Composite { interface Binder extends UiBinder<HTMLPanel, CommitMessageBlock> { } private static Binder uiBinder = GWT.create(Binder.class); private KeyCommandSet keysAction; @UiField SimplePanel starPanel; @UiField FlowPanel permalinkPanel; @UiField PreElement commitSummaryPre; @UiField PreElement commitBodyPre; public CommitMessageBlock() { initWidget(uiBinder.createAndBindUi(this)); } public CommitMessageBlock(KeyCommandSet keysAction) { this.keysAction = keysAction; initWidget(uiBinder.createAndBindUi(this)); } public void display(final String commitMessage) { display(null, null, commitMessage); } public void display(Change.Id changeId, Boolean starred, String commitMessage) { starPanel.clear(); if (changeId != null && starred != null && Gerrit.isSignedIn()) { StarredChanges.Icon star = StarredChanges.createIcon(changeId, starred); star.setStyleName(Gerrit.RESOURCES.css().changeScreenStarIcon()); starPanel.add(star); if (keysAction != null) { keysAction.add(StarredChanges.newKeyCommand(star)); } } - permalinkPanel.add(new ChangeLink(Util.C.changePermalink(), changeId)); - permalinkPanel.add(new CopyableLabel(ChangeLink.permalink(changeId), false)); + if (changeId != null) { + permalinkPanel.add(new ChangeLink(Util.C.changePermalink(), changeId)); + permalinkPanel.add(new CopyableLabel(ChangeLink.permalink(changeId), false)); + } String[] splitCommitMessage = commitMessage.split("\n", 2); String commitSummary = splitCommitMessage[0]; String commitBody = ""; if (splitCommitMessage.length > 1) { commitBody = splitCommitMessage[1]; } // Linkify commit summary SafeHtml commitSummaryLinkified = new SafeHtmlBuilder().append(commitSummary); commitSummaryLinkified = commitSummaryLinkified.linkify(); commitSummaryLinkified = CommentLinkProcessor.apply(commitSummaryLinkified); commitSummaryPre.setInnerHTML(commitSummaryLinkified.asString()); // Hide commit body if there is no body if (commitBody.trim().isEmpty()) { commitBodyPre.getStyle().setDisplay(Display.NONE); } else { // Linkify commit body SafeHtml commitBodyLinkified = new SafeHtmlBuilder().append(commitBody); commitBodyLinkified = commitBodyLinkified.linkify(); commitBodyLinkified = CommentLinkProcessor.apply(commitBodyLinkified); commitBodyPre.setInnerHTML(commitBodyLinkified.asString()); } } }
true
true
public void display(Change.Id changeId, Boolean starred, String commitMessage) { starPanel.clear(); if (changeId != null && starred != null && Gerrit.isSignedIn()) { StarredChanges.Icon star = StarredChanges.createIcon(changeId, starred); star.setStyleName(Gerrit.RESOURCES.css().changeScreenStarIcon()); starPanel.add(star); if (keysAction != null) { keysAction.add(StarredChanges.newKeyCommand(star)); } } permalinkPanel.add(new ChangeLink(Util.C.changePermalink(), changeId)); permalinkPanel.add(new CopyableLabel(ChangeLink.permalink(changeId), false)); String[] splitCommitMessage = commitMessage.split("\n", 2); String commitSummary = splitCommitMessage[0]; String commitBody = ""; if (splitCommitMessage.length > 1) { commitBody = splitCommitMessage[1]; } // Linkify commit summary SafeHtml commitSummaryLinkified = new SafeHtmlBuilder().append(commitSummary); commitSummaryLinkified = commitSummaryLinkified.linkify(); commitSummaryLinkified = CommentLinkProcessor.apply(commitSummaryLinkified); commitSummaryPre.setInnerHTML(commitSummaryLinkified.asString()); // Hide commit body if there is no body if (commitBody.trim().isEmpty()) { commitBodyPre.getStyle().setDisplay(Display.NONE); } else { // Linkify commit body SafeHtml commitBodyLinkified = new SafeHtmlBuilder().append(commitBody); commitBodyLinkified = commitBodyLinkified.linkify(); commitBodyLinkified = CommentLinkProcessor.apply(commitBodyLinkified); commitBodyPre.setInnerHTML(commitBodyLinkified.asString()); } }
public void display(Change.Id changeId, Boolean starred, String commitMessage) { starPanel.clear(); if (changeId != null && starred != null && Gerrit.isSignedIn()) { StarredChanges.Icon star = StarredChanges.createIcon(changeId, starred); star.setStyleName(Gerrit.RESOURCES.css().changeScreenStarIcon()); starPanel.add(star); if (keysAction != null) { keysAction.add(StarredChanges.newKeyCommand(star)); } } if (changeId != null) { permalinkPanel.add(new ChangeLink(Util.C.changePermalink(), changeId)); permalinkPanel.add(new CopyableLabel(ChangeLink.permalink(changeId), false)); } String[] splitCommitMessage = commitMessage.split("\n", 2); String commitSummary = splitCommitMessage[0]; String commitBody = ""; if (splitCommitMessage.length > 1) { commitBody = splitCommitMessage[1]; } // Linkify commit summary SafeHtml commitSummaryLinkified = new SafeHtmlBuilder().append(commitSummary); commitSummaryLinkified = commitSummaryLinkified.linkify(); commitSummaryLinkified = CommentLinkProcessor.apply(commitSummaryLinkified); commitSummaryPre.setInnerHTML(commitSummaryLinkified.asString()); // Hide commit body if there is no body if (commitBody.trim().isEmpty()) { commitBodyPre.getStyle().setDisplay(Display.NONE); } else { // Linkify commit body SafeHtml commitBodyLinkified = new SafeHtmlBuilder().append(commitBody); commitBodyLinkified = commitBodyLinkified.linkify(); commitBodyLinkified = CommentLinkProcessor.apply(commitBodyLinkified); commitBodyPre.setInnerHTML(commitBodyLinkified.asString()); } }
diff --git a/LittleSmartTool2/src/littlesmarttool2/util/UpdateUtil.java b/LittleSmartTool2/src/littlesmarttool2/util/UpdateUtil.java index 9616064..8b1b9aa 100644 --- a/LittleSmartTool2/src/littlesmarttool2/util/UpdateUtil.java +++ b/LittleSmartTool2/src/littlesmarttool2/util/UpdateUtil.java @@ -1,59 +1,61 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package littlesmarttool2.util; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; /** * * @author Rasmus */ public class UpdateUtil { public static final int FirmwareMain = 0; public static final int FirmwareSub = 2; public static boolean UpdateFirmware(String port) { boolean isWindows = System.getProperty("os.name").toLowerCase().startsWith("windows"); int result; - String prog = (isWindows) ? "avrdude-win/avrdude.exe" : "sudo avrdude-mac/avrdude"; + String prog = (isWindows) ? "avrdude-win/avrdude.exe" : "./avrdude-mac/avrdude"; String conf = (isWindows) ? "avrdude-win/avrdude.conf" : "avrdude-mac/avrdude.conf"; String filename = "firmware/StratoSnapper_v22.cpp.hex"; StringBuilder sb = new StringBuilder(); try { + if(!isWindows) + Runtime.getRuntime().exec("chmod 777 "+prog); Process p = Runtime.getRuntime().exec(prog+" -C"+conf+" -v -v -v -v -patmega328p -carduino -P"+port+" -b57600 -D -Uflash:w:"+filename+":i"); BufferedReader r = new BufferedReader(new InputStreamReader(p.getErrorStream())); String line; while ((line = r.readLine()) != null) { sb.append(line).append("\r\n"); } result = p.waitFor(); } catch (IOException | InterruptedException ex) { sb.append(ex.getClass().getName()); sb.append(ex.getMessage()); result = -1; } if (result != 0) { try { PrintWriter pw = new PrintWriter("logs/avrdude.log"); pw.write("Result from avrdude: " + result + "\r\n"); pw.write(sb.toString()); pw.flush(); pw.close(); } catch (FileNotFoundException ex) { } } return result == 0; } }
false
true
public static boolean UpdateFirmware(String port) { boolean isWindows = System.getProperty("os.name").toLowerCase().startsWith("windows"); int result; String prog = (isWindows) ? "avrdude-win/avrdude.exe" : "sudo avrdude-mac/avrdude"; String conf = (isWindows) ? "avrdude-win/avrdude.conf" : "avrdude-mac/avrdude.conf"; String filename = "firmware/StratoSnapper_v22.cpp.hex"; StringBuilder sb = new StringBuilder(); try { Process p = Runtime.getRuntime().exec(prog+" -C"+conf+" -v -v -v -v -patmega328p -carduino -P"+port+" -b57600 -D -Uflash:w:"+filename+":i"); BufferedReader r = new BufferedReader(new InputStreamReader(p.getErrorStream())); String line; while ((line = r.readLine()) != null) { sb.append(line).append("\r\n"); } result = p.waitFor(); } catch (IOException | InterruptedException ex) { sb.append(ex.getClass().getName()); sb.append(ex.getMessage()); result = -1; } if (result != 0) { try { PrintWriter pw = new PrintWriter("logs/avrdude.log"); pw.write("Result from avrdude: " + result + "\r\n"); pw.write(sb.toString()); pw.flush(); pw.close(); } catch (FileNotFoundException ex) { } } return result == 0; }
public static boolean UpdateFirmware(String port) { boolean isWindows = System.getProperty("os.name").toLowerCase().startsWith("windows"); int result; String prog = (isWindows) ? "avrdude-win/avrdude.exe" : "./avrdude-mac/avrdude"; String conf = (isWindows) ? "avrdude-win/avrdude.conf" : "avrdude-mac/avrdude.conf"; String filename = "firmware/StratoSnapper_v22.cpp.hex"; StringBuilder sb = new StringBuilder(); try { if(!isWindows) Runtime.getRuntime().exec("chmod 777 "+prog); Process p = Runtime.getRuntime().exec(prog+" -C"+conf+" -v -v -v -v -patmega328p -carduino -P"+port+" -b57600 -D -Uflash:w:"+filename+":i"); BufferedReader r = new BufferedReader(new InputStreamReader(p.getErrorStream())); String line; while ((line = r.readLine()) != null) { sb.append(line).append("\r\n"); } result = p.waitFor(); } catch (IOException | InterruptedException ex) { sb.append(ex.getClass().getName()); sb.append(ex.getMessage()); result = -1; } if (result != 0) { try { PrintWriter pw = new PrintWriter("logs/avrdude.log"); pw.write("Result from avrdude: " + result + "\r\n"); pw.write(sb.toString()); pw.flush(); pw.close(); } catch (FileNotFoundException ex) { } } return result == 0; }
diff --git a/app/src/com/halcyonwaves/apps/meinemediathek/fragments/MovieSearchFragment.java b/app/src/com/halcyonwaves/apps/meinemediathek/fragments/MovieSearchFragment.java index 61b70ec..8ce6c7a 100644 --- a/app/src/com/halcyonwaves/apps/meinemediathek/fragments/MovieSearchFragment.java +++ b/app/src/com/halcyonwaves/apps/meinemediathek/fragments/MovieSearchFragment.java @@ -1,112 +1,112 @@ package com.halcyonwaves.apps.meinemediathek.fragments; import java.text.DateFormat; import java.util.Date; import java.util.Locale; import android.app.AlertDialog; import android.app.Fragment; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import com.halcyonwaves.apps.meinemediathek.ChangeLogDialog; import com.halcyonwaves.apps.meinemediathek.Consts; import com.halcyonwaves.apps.meinemediathek.R; import com.halcyonwaves.apps.meinemediathek.activities.SearchResultsActivity; public class MovieSearchFragment extends Fragment { private final static String TAG = "MovieSearchFragment"; private Button btnSearch = null; private EditText etTitleToSearchFor = null; @Override public View onCreateView( final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState ) { // get the basic view layout from the application resources final View v = inflater.inflate( R.layout.fragment_moviesearch, container ); // get the handles to the controls we have to access this.btnSearch = (Button) v.findViewById( R.id.btn_search ); this.etTitleToSearchFor = (EditText) v.findViewById( R.id.et_searchfortitle ); // set the behavior for the search button this.btnSearch.setOnClickListener( new OnClickListener() { @Override public void onClick( final View v ) { final Intent intent = new Intent( MovieSearchFragment.this.getActivity(), SearchResultsActivity.class ); intent.putExtra( "searchFor", MovieSearchFragment.this.etTitleToSearchFor.getText().toString() ); MovieSearchFragment.this.startActivity( intent ); } } ); // get the preferences of the application final SharedPreferences appPreferences = PreferenceManager.getDefaultSharedPreferences( this.getActivity().getApplicationContext() ); // if this is the first time the user uses this application , he or she has to agree that he or she // will not do anything harmful if( !appPreferences.getBoolean( Consts.PREFERENCE_LICENSE_ACCEPTED, false ) ) { // prepare a dialog asking the user he or she really wants to do the download on a mobile connection final AlertDialog.Builder builder = new AlertDialog.Builder( MovieSearchFragment.this.getActivity() ); builder.setMessage( R.string.dlg_msg_license ).setTitle( R.string.dlg_title_license ).setPositiveButton( R.string.btn_agree, new DialogInterface.OnClickListener() { @Override public void onClick( final DialogInterface dialog, final int id ) { // the user accepted the license, so store this in the application settings and proceed Editor prefEditor = appPreferences.edit(); prefEditor.putBoolean( Consts.PREFERENCE_LICENSE_ACCEPTED, true ); - prefEditor.putString( Consts.PREFERENCE_LICENSE_AGREEMENT_TIME, DateFormat.getDateInstance( DateFormat.FULL, Locale.US ).format( new Date() ) ); + prefEditor.putString( Consts.PREFERENCE_LICENSE_AGREEMENT_TIME, DateFormat.getDateTimeInstance( DateFormat.FULL, DateFormat.FULL, Locale.US ).format( new Date() ) ); prefEditor.commit(); prefEditor = null; } } ).setNegativeButton( R.string.btn_disagree, new DialogInterface.OnClickListener() { @Override public void onClick( final DialogInterface dialog, final int id ) { // if the user disagreed, we have to show him the play store for uninstalling the application try { final Intent intent = new Intent( Intent.ACTION_VIEW ); intent.setData( Uri.parse( "market://details?id=com.halcyonwaves.apps.meinemediathek" ) ); MovieSearchFragment.this.startActivity( intent ); } catch( final Exception e ) { Log.e( MovieSearchFragment.TAG, "Failed to open the Google Play store to rate the application!" ); } MovieSearchFragment.this.getActivity().finish(); } } ).setCancelable( false ); // show the dialog to the user final AlertDialog askUserDialog = builder.create(); askUserDialog.show(); // be sure that the changelog dialog won't pop up during the next application start new ChangeLogDialog( this.getActivity() ).markDialogAsAlreadyDisplayed(); } // just show the changelog if its not the first start, otherwise it wont be interesting for the user else { final ChangeLogDialog changelogDlg = new ChangeLogDialog( this.getActivity() ); changelogDlg.show(); } // return the created view for the fragment return v; } }
true
true
public View onCreateView( final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState ) { // get the basic view layout from the application resources final View v = inflater.inflate( R.layout.fragment_moviesearch, container ); // get the handles to the controls we have to access this.btnSearch = (Button) v.findViewById( R.id.btn_search ); this.etTitleToSearchFor = (EditText) v.findViewById( R.id.et_searchfortitle ); // set the behavior for the search button this.btnSearch.setOnClickListener( new OnClickListener() { @Override public void onClick( final View v ) { final Intent intent = new Intent( MovieSearchFragment.this.getActivity(), SearchResultsActivity.class ); intent.putExtra( "searchFor", MovieSearchFragment.this.etTitleToSearchFor.getText().toString() ); MovieSearchFragment.this.startActivity( intent ); } } ); // get the preferences of the application final SharedPreferences appPreferences = PreferenceManager.getDefaultSharedPreferences( this.getActivity().getApplicationContext() ); // if this is the first time the user uses this application , he or she has to agree that he or she // will not do anything harmful if( !appPreferences.getBoolean( Consts.PREFERENCE_LICENSE_ACCEPTED, false ) ) { // prepare a dialog asking the user he or she really wants to do the download on a mobile connection final AlertDialog.Builder builder = new AlertDialog.Builder( MovieSearchFragment.this.getActivity() ); builder.setMessage( R.string.dlg_msg_license ).setTitle( R.string.dlg_title_license ).setPositiveButton( R.string.btn_agree, new DialogInterface.OnClickListener() { @Override public void onClick( final DialogInterface dialog, final int id ) { // the user accepted the license, so store this in the application settings and proceed Editor prefEditor = appPreferences.edit(); prefEditor.putBoolean( Consts.PREFERENCE_LICENSE_ACCEPTED, true ); prefEditor.putString( Consts.PREFERENCE_LICENSE_AGREEMENT_TIME, DateFormat.getDateInstance( DateFormat.FULL, Locale.US ).format( new Date() ) ); prefEditor.commit(); prefEditor = null; } } ).setNegativeButton( R.string.btn_disagree, new DialogInterface.OnClickListener() { @Override public void onClick( final DialogInterface dialog, final int id ) { // if the user disagreed, we have to show him the play store for uninstalling the application try { final Intent intent = new Intent( Intent.ACTION_VIEW ); intent.setData( Uri.parse( "market://details?id=com.halcyonwaves.apps.meinemediathek" ) ); MovieSearchFragment.this.startActivity( intent ); } catch( final Exception e ) { Log.e( MovieSearchFragment.TAG, "Failed to open the Google Play store to rate the application!" ); } MovieSearchFragment.this.getActivity().finish(); } } ).setCancelable( false ); // show the dialog to the user final AlertDialog askUserDialog = builder.create(); askUserDialog.show(); // be sure that the changelog dialog won't pop up during the next application start new ChangeLogDialog( this.getActivity() ).markDialogAsAlreadyDisplayed(); } // just show the changelog if its not the first start, otherwise it wont be interesting for the user else { final ChangeLogDialog changelogDlg = new ChangeLogDialog( this.getActivity() ); changelogDlg.show(); } // return the created view for the fragment return v; }
public View onCreateView( final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState ) { // get the basic view layout from the application resources final View v = inflater.inflate( R.layout.fragment_moviesearch, container ); // get the handles to the controls we have to access this.btnSearch = (Button) v.findViewById( R.id.btn_search ); this.etTitleToSearchFor = (EditText) v.findViewById( R.id.et_searchfortitle ); // set the behavior for the search button this.btnSearch.setOnClickListener( new OnClickListener() { @Override public void onClick( final View v ) { final Intent intent = new Intent( MovieSearchFragment.this.getActivity(), SearchResultsActivity.class ); intent.putExtra( "searchFor", MovieSearchFragment.this.etTitleToSearchFor.getText().toString() ); MovieSearchFragment.this.startActivity( intent ); } } ); // get the preferences of the application final SharedPreferences appPreferences = PreferenceManager.getDefaultSharedPreferences( this.getActivity().getApplicationContext() ); // if this is the first time the user uses this application , he or she has to agree that he or she // will not do anything harmful if( !appPreferences.getBoolean( Consts.PREFERENCE_LICENSE_ACCEPTED, false ) ) { // prepare a dialog asking the user he or she really wants to do the download on a mobile connection final AlertDialog.Builder builder = new AlertDialog.Builder( MovieSearchFragment.this.getActivity() ); builder.setMessage( R.string.dlg_msg_license ).setTitle( R.string.dlg_title_license ).setPositiveButton( R.string.btn_agree, new DialogInterface.OnClickListener() { @Override public void onClick( final DialogInterface dialog, final int id ) { // the user accepted the license, so store this in the application settings and proceed Editor prefEditor = appPreferences.edit(); prefEditor.putBoolean( Consts.PREFERENCE_LICENSE_ACCEPTED, true ); prefEditor.putString( Consts.PREFERENCE_LICENSE_AGREEMENT_TIME, DateFormat.getDateTimeInstance( DateFormat.FULL, DateFormat.FULL, Locale.US ).format( new Date() ) ); prefEditor.commit(); prefEditor = null; } } ).setNegativeButton( R.string.btn_disagree, new DialogInterface.OnClickListener() { @Override public void onClick( final DialogInterface dialog, final int id ) { // if the user disagreed, we have to show him the play store for uninstalling the application try { final Intent intent = new Intent( Intent.ACTION_VIEW ); intent.setData( Uri.parse( "market://details?id=com.halcyonwaves.apps.meinemediathek" ) ); MovieSearchFragment.this.startActivity( intent ); } catch( final Exception e ) { Log.e( MovieSearchFragment.TAG, "Failed to open the Google Play store to rate the application!" ); } MovieSearchFragment.this.getActivity().finish(); } } ).setCancelable( false ); // show the dialog to the user final AlertDialog askUserDialog = builder.create(); askUserDialog.show(); // be sure that the changelog dialog won't pop up during the next application start new ChangeLogDialog( this.getActivity() ).markDialogAsAlreadyDisplayed(); } // just show the changelog if its not the first start, otherwise it wont be interesting for the user else { final ChangeLogDialog changelogDlg = new ChangeLogDialog( this.getActivity() ); changelogDlg.show(); } // return the created view for the fragment return v; }
diff --git a/src/main/java/com/turt2live/antishare/CommandHandler.java b/src/main/java/com/turt2live/antishare/CommandHandler.java index 5a4956ef..dab844eb 100644 --- a/src/main/java/com/turt2live/antishare/CommandHandler.java +++ b/src/main/java/com/turt2live/antishare/CommandHandler.java @@ -1,589 +1,589 @@ /******************************************************************************* * Copyright (c) 2013 Travis Ralston. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html * * Contributors: * turt2live (Travis Ralston) - initial API and implementation ******************************************************************************/ package com.turt2live.antishare; import com.turt2live.antishare.cuboid.Cuboid; import com.turt2live.antishare.inventory.ASInventory; import com.turt2live.antishare.inventory.ASInventory.InventoryType; import com.turt2live.antishare.inventory.DisplayableInventory; import com.turt2live.antishare.regions.Region; import com.turt2live.antishare.regions.RegionKey; import com.turt2live.antishare.util.ASUtils; import com.turt2live.materials.MaterialAPI; import org.bukkit.*; import org.bukkit.command.BlockCommandSender; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import java.util.ArrayList; import java.util.List; import java.util.Set; /** * Command Handler * * @author turt2live */ public class CommandHandler implements CommandExecutor { private final AntiShare plugin = AntiShare.p; private String noPermission = plugin.getMessages().getMessage("no-permission"); private String notPlayer = plugin.getMessages().getMessage("not-a-player"); @Override public boolean onCommand(final CommandSender sender, Command command, String label, String[] args) { if (sender instanceof BlockCommandSender) { return false; } if (command.getName().equalsIgnoreCase("AntiShare")) { if (args.length > 0) { if (args[0].equalsIgnoreCase("version")) { plugin.getMessages().sendTo(sender, ChatColor.YELLOW + "Version: " + ChatColor.GOLD + plugin.getDescription().getVersion() + ChatColor.YELLOW + " Build: " + ChatColor.GOLD + plugin.getBuild(), false); return true; } else if (args[0].equalsIgnoreCase("reload") || args[0].equalsIgnoreCase("rl")) { if (sender.hasPermission(PermissionNodes.RELOAD)) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("reloading"), true); plugin.reload(); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("reloaded"), true); } else { plugin.getMessages().sendTo(sender, noPermission, true); } return true; } else if (args[0].equalsIgnoreCase("mirror")) { // Sanity Check if (!(sender instanceof Player)) { plugin.getMessages().sendTo(sender, notPlayer, true); } else { if (sender.hasPermission(PermissionNodes.MIRROR)) { - if (!plugin.getConfig().getBoolean("handled-actions.gamemode-inventories")) { + if (!plugin.settings().features.inventories) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("inventories-not-enabled"), true); return true; } if (args.length < 2) { //plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("syntax", "/as mirror <player> [enderchest/normal] [gamemode] [world]"), true); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("syntax", "/as mirror <player> [enderchest/normal] [gamemode] [world]"), true); } else { // Setup String playername = args[1]; OfflinePlayer player = plugin.getServer().getPlayer(playername); // Find online player first, then we look for offline players if (player == null) { for (OfflinePlayer offlinePlayer : plugin.getServer().getOfflinePlayers()) { if (offlinePlayer.getName().equalsIgnoreCase(playername) || offlinePlayer.getName().toLowerCase().startsWith(playername.toLowerCase())) { player = offlinePlayer; break; } } } // Sanity check if (player == null) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("player-not-found", playername), true); return true; } // Ender chest check boolean isEnder = false; if (args.length > 2) { if (args[2].equalsIgnoreCase("ender") || args[2].equalsIgnoreCase("enderchest")) { isEnder = true; } else if (args[2].equalsIgnoreCase("normal") || args[2].equalsIgnoreCase("player")) { isEnder = false; } else { isEnder = false; plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("assume-normal-inventory", args[2]), true); } } // Per specific game mode GameMode gamemode = player.isOnline() ? ((Player) player).getGameMode() : GameMode.SURVIVAL; if (args.length > 3) { GameMode temp = ASUtils.getGameMode(args[3]); if (temp != null) { gamemode = temp; } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("assume-gamemode", "Game Mode", args[3], MaterialAPI.capitalize(gamemode.name())), true); } } // World check World world = player.isOnline() ? ((Player) player).getWorld() : plugin.getServer().getWorlds().get(0); if (args.length > 4) { World temp = Bukkit.getWorld(args[4]); if (temp == null) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("assume-world", args[4], world.getName()), true); } else { world = temp; } } // Load all inventories if (player.isOnline()) { Player p = (Player) player; plugin.getInventoryManager().savePlayer(p); } ASInventory chosen = ASInventory.load(playername, gamemode, isEnder ? InventoryType.ENDER : InventoryType.PLAYER, world.getName()); if (chosen == null) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("inventory-not-found"), true); return true; } // Create title String title = player.getName() + " | " + ASUtils.gamemodeAbbreviation(gamemode, false) + " | " + world.getName(); // Create displayable inventory DisplayableInventory display = new DisplayableInventory(chosen, title); // Show inventory if (isEnder) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("mirror-ender-welcome", player.getName()), true); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("mirror-edit"), true); } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("mirror-welcome", player.getName()), true); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("mirror-edit"), true); } ((Player) sender).openInventory(display.getInventory()); // Creates the "live editing" window } } else { plugin.getMessages().sendTo(sender, noPermission, true); } } return true; } else if (args[0].equalsIgnoreCase("region")) { if (sender.hasPermission(PermissionNodes.REGION_CREATE)) { // Sanity Check if (sender instanceof Player) { Player player = (Player) sender; if (args.length < 3) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("syntax", "/as region <gamemode> <name>"), true); } else { String regionName = args[2]; GameMode gamemode = ASUtils.getGameMode(args[1]); if (gamemode != null) { if (!plugin.getRegionManager().isRegionNameTaken(regionName)) { if (plugin.getCuboidManager().isCuboidComplete(player.getName())) { Cuboid cuboid = plugin.getCuboidManager().getCuboid(player.getName()); plugin.getRegionManager().addRegion(cuboid, player.getName(), regionName, gamemode); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("region-created"), true); } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("missing-cuboid"), true); } } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("name-in-use"), true); } } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("unknown-gamemode", args[1]), true); } } } else { plugin.getMessages().sendTo(sender, notPlayer, true); } } else { plugin.getMessages().sendTo(sender, noPermission, true); } return true; } else if (args[0].equalsIgnoreCase("rmregion") || args[0].equalsIgnoreCase("removeregion")) { if (sender.hasPermission(PermissionNodes.REGION_DELETE)) { // Sanity check if (sender instanceof Player) { // Remove region if (args.length == 1) { Location location = ((Player) sender).getLocation(); Region region = plugin.getRegionManager().getRegion(location); if (region != null) { plugin.getRegionManager().removeRegion(region.getName()); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("region-remove"), true); } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("no-foot-region"), true); } } else { String regionName = args[1]; Region region = plugin.getRegionManager().getRegion(regionName); if (region != null) { plugin.getRegionManager().removeRegion(region.getName()); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("region-remove"), true); } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("unknown-region", regionName), true); } } } else { // Remove region if (args.length > 1) { String regionName = args[1]; Region region = plugin.getRegionManager().getRegion(regionName); if (region != null) { plugin.getRegionManager().removeRegion(region.getName()); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("region-remove"), true); } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("unknown-region", regionName), true); } } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("syntax", "/as rmregion <name>"), true); } } } else { plugin.getMessages().sendTo(sender, noPermission, true); } return true; } else if (args[0].equalsIgnoreCase("editregion")) { if (sender.hasPermission(PermissionNodes.REGION_EDIT)) { // Check validity of key boolean valid = false; if (args.length >= 3) { if (RegionKey.isKey(args[2])) { if (!RegionKey.requiresValue(RegionKey.getKey(args[2]))) { valid = true; // we have at least 3 values in args[] and the key does not need a value } } } if (args.length >= 4) { valid = true; } if (!valid) { // Show help if (args.length >= 2) { if (args[1].equalsIgnoreCase("help")) { String key = plugin.getMessages().getMessage("key").toLowerCase(); String value = plugin.getMessages().getMessage("value").toLowerCase(); key = key.substring(0, 1).toUpperCase() + key.substring(1); value = value.substring(0, 1).toUpperCase() + value.substring(1); plugin.getMessages().sendTo(sender, ChatColor.GOLD + "/as editregion <name> <key> <value>", false); plugin.getMessages().sendTo(sender, ChatColor.AQUA + key + ": " + ChatColor.WHITE + "name " + ChatColor.AQUA + value + ": " + ChatColor.WHITE + "<any name>", false); plugin.getMessages().sendTo(sender, ChatColor.AQUA + key + ": " + ChatColor.WHITE + "ShowEnterMessage " + ChatColor.AQUA + value + ": " + ChatColor.WHITE + "true/false", false); plugin.getMessages().sendTo(sender, ChatColor.AQUA + key + ": " + ChatColor.WHITE + "ShowExitMessage " + ChatColor.AQUA + value + ": " + ChatColor.WHITE + "true/false", false); plugin.getMessages().sendTo(sender, ChatColor.AQUA + key + ": " + ChatColor.WHITE + "EnterMessage " + ChatColor.AQUA + value + ": " + ChatColor.WHITE + "<enter message>", false); plugin.getMessages().sendTo(sender, ChatColor.AQUA + key + ": " + ChatColor.WHITE + "ExitMessage " + ChatColor.AQUA + value + ": " + ChatColor.WHITE + "<exit message>", false); plugin.getMessages().sendTo(sender, ChatColor.AQUA + key + ": " + ChatColor.WHITE + "inventory " + ChatColor.AQUA + value + ": " + ChatColor.WHITE + "'none'/'set'", false); plugin.getMessages().sendTo(sender, ChatColor.AQUA + key + ": " + ChatColor.WHITE + "gamemode " + ChatColor.AQUA + value + ": " + ChatColor.WHITE + "survival/creative", false); plugin.getMessages().sendTo(sender, ChatColor.AQUA + key + ": " + ChatColor.WHITE + "area " + ChatColor.AQUA + value + ": " + ChatColor.WHITE + "No Value", false); } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("syntax", "/as editregion <name> <key> <value>"), true); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("extra-help", "/as editregion help"), true); } } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("syntax", "/as editregion <name> <key> <value>"), true); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("extra-help", "/as editregion help"), true); } } else { // Setup String name = args[1]; String key = args[2]; String value = args.length > 3 ? args[3] : ""; // Merge message if (args.length > 4) { for (int i = 4; i < args.length; i++) { // Starts at args[4] value = value + args[i] + " "; } value = value.substring(0, value.length() - 1); } // Check region if (plugin.getRegionManager().getRegion(name) == null) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("unknown-region", name), true); } else { // Update region if needed if (RegionKey.isKey(key)) { plugin.getRegionManager().updateRegion(plugin.getRegionManager().getRegion(name), RegionKey.getKey(key), value, sender); } else { plugin.getMessages().sendTo(sender, ChatColor.DARK_RED + plugin.getMessages().getMessage("unknown-key", key), true); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("extra-help", "/as editregion help"), true); } } } } else { plugin.getMessages().sendTo(sender, noPermission, true); } return true; } else if (args[0].equalsIgnoreCase("listregions")) { if (sender.hasPermission(PermissionNodes.REGION_LIST)) { // Sanity check on page number int page = 1; if (args.length >= 2) { try { page = Integer.parseInt(args[1]); } catch (NumberFormatException e) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("unknown-value", args[1]), true); return true; } } // Setup page = Math.abs(page); int resultsPerPage = 6; // Put as a variable for ease of changing Set<Region> set = plugin.getRegionManager().getAllRegions(); List<Region> regions = new ArrayList<Region>(); regions.addAll(set); // Check for empty list if (regions.size() <= 0) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("no-regions"), true); return true; } // Math Double maxPagesD = Math.ceil(regions.size() / resultsPerPage); if (maxPagesD < 1) { maxPagesD = 1.0; } int maxPages = maxPagesD.intValue(); if (maxPagesD < page) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("page-not-found", String.valueOf(page), String.valueOf(maxPages)), true); return true; } // Generate pages String pagenation = ChatColor.DARK_GREEN + "=======[ " + ChatColor.GREEN + "AntiShare Regions " + ChatColor.DARK_GREEN + "|" + ChatColor.GREEN + " Page " + page + "/" + maxPages + ChatColor.DARK_GREEN + " ]======="; plugin.getMessages().sendTo(sender, pagenation, false); for (int i = (page - 1) * resultsPerPage; i < (resultsPerPage < regions.size() ? resultsPerPage * page : regions.size()); i++) { plugin.getMessages().sendTo(sender, ChatColor.DARK_AQUA + "#" + (i + 1) + " " + ChatColor.GOLD + regions.get(i).getName() + ChatColor.YELLOW + " Creator: " + ChatColor.AQUA + regions.get(i).getOwner() + ChatColor.YELLOW + " World: " + ChatColor.AQUA + regions.get(i).getWorldName(), false); } plugin.getMessages().sendTo(sender, pagenation, false); } else { plugin.getMessages().sendTo(sender, noPermission, true); } return true; } else if (args[0].equalsIgnoreCase("tool")) { if (sender.hasPermission(PermissionNodes.TOOL_GET)) { // Sanity check if (!(sender instanceof Player)) { plugin.getMessages().sendTo(sender, notPlayer, true); } else { // Setup Player player = (Player) sender; PlayerInventory inventory = player.getInventory(); // Check inventory if (inventory.firstEmpty() != -1 && inventory.firstEmpty() <= inventory.getSize()) { if (ASUtils.hasTool(AntiShare.ANTISHARE_TOOL, player)) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("have-tool", MaterialAPI.capitalize(AntiShare.ANTISHARE_TOOL.name())), true); } else { ASUtils.giveTool(AntiShare.ANTISHARE_TOOL, player); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("get-tool", MaterialAPI.capitalize(AntiShare.ANTISHARE_TOOL.name())), true); } } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("no-space", String.valueOf(1)), true); } } } else { plugin.getMessages().sendTo(sender, noPermission, true); } return true; } else if (args[0].equalsIgnoreCase("settool")) { if (sender.hasPermission(PermissionNodes.TOOL_GET)) { // Sanity check if (!(sender instanceof Player)) { plugin.getMessages().sendTo(sender, notPlayer, true); } else { // Setup Player player = (Player) sender; PlayerInventory inventory = player.getInventory(); // Check inventory if (inventory.firstEmpty() != -1 && inventory.firstEmpty() <= inventory.getSize()) { if (ASUtils.hasTool(AntiShare.ANTISHARE_SET_TOOL, player)) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("have-tool", MaterialAPI.capitalize(AntiShare.ANTISHARE_SET_TOOL.name())), true); } else { ASUtils.giveTool(AntiShare.ANTISHARE_SET_TOOL, player); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("get-tool", MaterialAPI.capitalize(AntiShare.ANTISHARE_SET_TOOL.name())), true); } } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("no-space", String.valueOf(1)), true); } } } else { plugin.getMessages().sendTo(sender, noPermission, true); } return true; } else if (args[0].equalsIgnoreCase("toolbox")) { if (sender.hasPermission(PermissionNodes.TOOL_GET)) { // Sanity check if (!(sender instanceof Player)) { plugin.getMessages().sendTo(sender, notPlayer, true); } else { // Setup Player player = (Player) sender; PlayerInventory inventory = player.getInventory(); // Find clear spots int clearSpots = 0; for (ItemStack stack : inventory.getContents()) { if (stack == null || stack.getType() == Material.AIR) { clearSpots++; } } // Check inventory if (clearSpots >= 3) { if (!ASUtils.hasTool(AntiShare.ANTISHARE_TOOL, player)) { ASUtils.giveTool(AntiShare.ANTISHARE_TOOL, player, 1); } if (!ASUtils.hasTool(AntiShare.ANTISHARE_SET_TOOL, player)) { ASUtils.giveTool(AntiShare.ANTISHARE_SET_TOOL, player, 2); } if (sender.hasPermission(PermissionNodes.CREATE_CUBOID)) { if (!ASUtils.hasTool(AntiShare.ANTISHARE_CUBOID_TOOL, player)) { ASUtils.giveTool(AntiShare.ANTISHARE_CUBOID_TOOL, player, 3); } } else { plugin.getMessages().sendTo(player, plugin.getMessages().getMessage("cannot-have-cuboid"), true); } plugin.getMessages().sendTo(player, plugin.getMessages().getMessage("tools-give"), true); player.getInventory().setHeldItemSlot(1); } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("no-space", String.valueOf(3)), true); } } } else { plugin.getMessages().sendTo(sender, noPermission, true); } return true; } else if (args[0].equalsIgnoreCase("money")) { if (args.length < 2) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("syntax", "/as money <on/off/status>"), true); } else { if (args[1].equalsIgnoreCase("status") || args[1].equalsIgnoreCase("state")) { plugin.getMessages().sendTo(sender, plugin.getMoneyManager().isSilent(sender.getName()) ? plugin.getMessages().getMessage("fines-not-getting") : plugin.getMessages().getMessage("fines-getting"), true); return true; } if (ASUtils.getBoolean(args[1]) == null) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("syntax", "/as money <on/off/status>"), true); return true; } boolean silent = !ASUtils.getBoolean(args[1]); if (silent) { plugin.getMoneyManager().addToSilentList(sender.getName()); } else { plugin.getMoneyManager().removeFromSilentList(sender.getName()); } plugin.getMessages().sendTo(sender, silent ? plugin.getMessages().getMessage("fines-not-getting") : plugin.getMessages().getMessage("fines-getting"), true); } return true; } else if (args[0].equalsIgnoreCase("simplenotice") || args[0].equalsIgnoreCase("sn")) { if (sender instanceof Player) { Player player = (Player) sender; if (player.getListeningPluginChannels().contains("SimpleNotice")) { if (plugin.isSimpleNoticeEnabled(player.getName())) { plugin.disableSimpleNotice(player.getName()); plugin.getMessages().sendTo(player, plugin.getMessages().getMessage("simplenotice-off"), false); } else { plugin.enableSimpleNotice(player.getName()); plugin.getMessages().sendTo(player, plugin.getMessages().getMessage("simplenotice-on"), false); } } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("simplenotice-missing"), false); } } else { plugin.getMessages().sendTo(sender, notPlayer, true); } return true; } else if (args[0].equalsIgnoreCase("check") || args[0].equalsIgnoreCase("gamemode") || args[0].equalsIgnoreCase("gm")) { if (sender.hasPermission(PermissionNodes.CHECK)) { GameMode gm = null; if (args.length > 1 && !args[1].equalsIgnoreCase("all")) { gm = ASUtils.getGameMode(args[1]); if (gm == null) { Player player = plugin.getServer().getPlayer(args[1]); if (player != null) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("check", player.getName(), MaterialAPI.capitalize(player.getGameMode().name())), false); } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("player-not-found", args[1]), true); } return true; } } if (gm == null) { for (GameMode gamemode : GameMode.values()) { if (ASUtils.findGameModePlayers(gamemode).size() > 0) { plugin.getMessages().sendTo(sender, ChatColor.GOLD + gamemode.name() + ": " + ChatColor.YELLOW + ASUtils.commas(ASUtils.findGameModePlayers(gamemode)), false); } else { plugin.getMessages().sendTo(sender, ChatColor.GOLD + gamemode.name() + ": " + ChatColor.YELLOW + "no one", false); } } } else { plugin.getMessages().sendTo(sender, ChatColor.GOLD + gm.name() + ": " + ChatColor.YELLOW + ASUtils.commas(ASUtils.findGameModePlayers(gm)), false); } } else { plugin.getMessages().sendTo(sender, noPermission, true); } return true; } else if (args[0].equalsIgnoreCase("cuboid")) { if (!sender.hasPermission(PermissionNodes.CREATE_CUBOID)) { plugin.getMessages().sendTo(sender, noPermission, true); return true; } if (args.length > 1) { if (args[1].equalsIgnoreCase("clear")) { if (plugin.getCuboidManager().isCuboidComplete(sender.getName())) { plugin.getCuboidManager().removeCuboid(sender.getName()); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("cuboid-removed"), true); } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("missing-cuboid"), true); } } else if (args[1].equalsIgnoreCase("tool")) { if (!(sender instanceof Player)) { plugin.getMessages().sendTo(sender, notPlayer, true); } else { // Setup Player player = (Player) sender; PlayerInventory inventory = player.getInventory(); // Check inventory if (inventory.firstEmpty() != -1 && inventory.firstEmpty() <= inventory.getSize()) { if (ASUtils.hasTool(AntiShare.ANTISHARE_CUBOID_TOOL, player)) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("have-tool", MaterialAPI.capitalize(AntiShare.ANTISHARE_CUBOID_TOOL.name())), true); } else { ASUtils.giveTool(AntiShare.ANTISHARE_CUBOID_TOOL, player); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("get-tool", MaterialAPI.capitalize(AntiShare.ANTISHARE_CUBOID_TOOL.name())), true); } } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("no-space", String.valueOf(1)), true); } } } else if (args[1].equalsIgnoreCase("status")) { Cuboid cuboid = plugin.getCuboidManager().getCuboid(sender.getName()); if (cuboid == null) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("missing-cuboid"), false); } else { Location min = cuboid.isValid() ? cuboid.getMinimumPoint() : cuboid.getPoint1(); Location max = cuboid.isValid() ? cuboid.getMaximumPoint() : cuboid.getPoint2(); if (min != null) { plugin.getMessages().sendTo(sender, ChatColor.GOLD + "1: " + ChatColor.YELLOW + "(" + min.getBlockX() + ", " + min.getBlockY() + ", " + min.getBlockZ() + ", " + min.getWorld().getName() + ")", false); } else { plugin.getMessages().sendTo(sender, ChatColor.GOLD + "1: " + ChatColor.YELLOW + "not set", false); } if (max != null) { plugin.getMessages().sendTo(sender, ChatColor.GOLD + "2: " + ChatColor.YELLOW + "(" + max.getBlockX() + ", " + max.getBlockY() + ", " + max.getBlockZ() + ", " + max.getWorld().getName() + ")", false); } else { plugin.getMessages().sendTo(sender, ChatColor.GOLD + "2: " + ChatColor.YELLOW + "not set", false); } } } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("syntax", "/as cuboid <clear | tool | status>"), true); } } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("syntax", "/as cuboid <clear | tool | status>"), true); } return true; } else { // This is for all extra commands, like /as help. // This is also for all "non-commands", like /as sakjdha return false; //Shows usage in plugin.yml } } } return false; //Shows usage in plugin.yml } }
true
true
public boolean onCommand(final CommandSender sender, Command command, String label, String[] args) { if (sender instanceof BlockCommandSender) { return false; } if (command.getName().equalsIgnoreCase("AntiShare")) { if (args.length > 0) { if (args[0].equalsIgnoreCase("version")) { plugin.getMessages().sendTo(sender, ChatColor.YELLOW + "Version: " + ChatColor.GOLD + plugin.getDescription().getVersion() + ChatColor.YELLOW + " Build: " + ChatColor.GOLD + plugin.getBuild(), false); return true; } else if (args[0].equalsIgnoreCase("reload") || args[0].equalsIgnoreCase("rl")) { if (sender.hasPermission(PermissionNodes.RELOAD)) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("reloading"), true); plugin.reload(); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("reloaded"), true); } else { plugin.getMessages().sendTo(sender, noPermission, true); } return true; } else if (args[0].equalsIgnoreCase("mirror")) { // Sanity Check if (!(sender instanceof Player)) { plugin.getMessages().sendTo(sender, notPlayer, true); } else { if (sender.hasPermission(PermissionNodes.MIRROR)) { if (!plugin.getConfig().getBoolean("handled-actions.gamemode-inventories")) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("inventories-not-enabled"), true); return true; } if (args.length < 2) { //plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("syntax", "/as mirror <player> [enderchest/normal] [gamemode] [world]"), true); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("syntax", "/as mirror <player> [enderchest/normal] [gamemode] [world]"), true); } else { // Setup String playername = args[1]; OfflinePlayer player = plugin.getServer().getPlayer(playername); // Find online player first, then we look for offline players if (player == null) { for (OfflinePlayer offlinePlayer : plugin.getServer().getOfflinePlayers()) { if (offlinePlayer.getName().equalsIgnoreCase(playername) || offlinePlayer.getName().toLowerCase().startsWith(playername.toLowerCase())) { player = offlinePlayer; break; } } } // Sanity check if (player == null) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("player-not-found", playername), true); return true; } // Ender chest check boolean isEnder = false; if (args.length > 2) { if (args[2].equalsIgnoreCase("ender") || args[2].equalsIgnoreCase("enderchest")) { isEnder = true; } else if (args[2].equalsIgnoreCase("normal") || args[2].equalsIgnoreCase("player")) { isEnder = false; } else { isEnder = false; plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("assume-normal-inventory", args[2]), true); } } // Per specific game mode GameMode gamemode = player.isOnline() ? ((Player) player).getGameMode() : GameMode.SURVIVAL; if (args.length > 3) { GameMode temp = ASUtils.getGameMode(args[3]); if (temp != null) { gamemode = temp; } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("assume-gamemode", "Game Mode", args[3], MaterialAPI.capitalize(gamemode.name())), true); } } // World check World world = player.isOnline() ? ((Player) player).getWorld() : plugin.getServer().getWorlds().get(0); if (args.length > 4) { World temp = Bukkit.getWorld(args[4]); if (temp == null) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("assume-world", args[4], world.getName()), true); } else { world = temp; } } // Load all inventories if (player.isOnline()) { Player p = (Player) player; plugin.getInventoryManager().savePlayer(p); } ASInventory chosen = ASInventory.load(playername, gamemode, isEnder ? InventoryType.ENDER : InventoryType.PLAYER, world.getName()); if (chosen == null) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("inventory-not-found"), true); return true; } // Create title String title = player.getName() + " | " + ASUtils.gamemodeAbbreviation(gamemode, false) + " | " + world.getName(); // Create displayable inventory DisplayableInventory display = new DisplayableInventory(chosen, title); // Show inventory if (isEnder) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("mirror-ender-welcome", player.getName()), true); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("mirror-edit"), true); } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("mirror-welcome", player.getName()), true); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("mirror-edit"), true); } ((Player) sender).openInventory(display.getInventory()); // Creates the "live editing" window } } else { plugin.getMessages().sendTo(sender, noPermission, true); } } return true; } else if (args[0].equalsIgnoreCase("region")) { if (sender.hasPermission(PermissionNodes.REGION_CREATE)) { // Sanity Check if (sender instanceof Player) { Player player = (Player) sender; if (args.length < 3) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("syntax", "/as region <gamemode> <name>"), true); } else { String regionName = args[2]; GameMode gamemode = ASUtils.getGameMode(args[1]); if (gamemode != null) { if (!plugin.getRegionManager().isRegionNameTaken(regionName)) { if (plugin.getCuboidManager().isCuboidComplete(player.getName())) { Cuboid cuboid = plugin.getCuboidManager().getCuboid(player.getName()); plugin.getRegionManager().addRegion(cuboid, player.getName(), regionName, gamemode); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("region-created"), true); } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("missing-cuboid"), true); } } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("name-in-use"), true); } } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("unknown-gamemode", args[1]), true); } } } else { plugin.getMessages().sendTo(sender, notPlayer, true); } } else { plugin.getMessages().sendTo(sender, noPermission, true); } return true; } else if (args[0].equalsIgnoreCase("rmregion") || args[0].equalsIgnoreCase("removeregion")) { if (sender.hasPermission(PermissionNodes.REGION_DELETE)) { // Sanity check if (sender instanceof Player) { // Remove region if (args.length == 1) { Location location = ((Player) sender).getLocation(); Region region = plugin.getRegionManager().getRegion(location); if (region != null) { plugin.getRegionManager().removeRegion(region.getName()); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("region-remove"), true); } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("no-foot-region"), true); } } else { String regionName = args[1]; Region region = plugin.getRegionManager().getRegion(regionName); if (region != null) { plugin.getRegionManager().removeRegion(region.getName()); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("region-remove"), true); } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("unknown-region", regionName), true); } } } else { // Remove region if (args.length > 1) { String regionName = args[1]; Region region = plugin.getRegionManager().getRegion(regionName); if (region != null) { plugin.getRegionManager().removeRegion(region.getName()); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("region-remove"), true); } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("unknown-region", regionName), true); } } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("syntax", "/as rmregion <name>"), true); } } } else { plugin.getMessages().sendTo(sender, noPermission, true); } return true; } else if (args[0].equalsIgnoreCase("editregion")) { if (sender.hasPermission(PermissionNodes.REGION_EDIT)) { // Check validity of key boolean valid = false; if (args.length >= 3) { if (RegionKey.isKey(args[2])) { if (!RegionKey.requiresValue(RegionKey.getKey(args[2]))) { valid = true; // we have at least 3 values in args[] and the key does not need a value } } } if (args.length >= 4) { valid = true; } if (!valid) { // Show help if (args.length >= 2) { if (args[1].equalsIgnoreCase("help")) { String key = plugin.getMessages().getMessage("key").toLowerCase(); String value = plugin.getMessages().getMessage("value").toLowerCase(); key = key.substring(0, 1).toUpperCase() + key.substring(1); value = value.substring(0, 1).toUpperCase() + value.substring(1); plugin.getMessages().sendTo(sender, ChatColor.GOLD + "/as editregion <name> <key> <value>", false); plugin.getMessages().sendTo(sender, ChatColor.AQUA + key + ": " + ChatColor.WHITE + "name " + ChatColor.AQUA + value + ": " + ChatColor.WHITE + "<any name>", false); plugin.getMessages().sendTo(sender, ChatColor.AQUA + key + ": " + ChatColor.WHITE + "ShowEnterMessage " + ChatColor.AQUA + value + ": " + ChatColor.WHITE + "true/false", false); plugin.getMessages().sendTo(sender, ChatColor.AQUA + key + ": " + ChatColor.WHITE + "ShowExitMessage " + ChatColor.AQUA + value + ": " + ChatColor.WHITE + "true/false", false); plugin.getMessages().sendTo(sender, ChatColor.AQUA + key + ": " + ChatColor.WHITE + "EnterMessage " + ChatColor.AQUA + value + ": " + ChatColor.WHITE + "<enter message>", false); plugin.getMessages().sendTo(sender, ChatColor.AQUA + key + ": " + ChatColor.WHITE + "ExitMessage " + ChatColor.AQUA + value + ": " + ChatColor.WHITE + "<exit message>", false); plugin.getMessages().sendTo(sender, ChatColor.AQUA + key + ": " + ChatColor.WHITE + "inventory " + ChatColor.AQUA + value + ": " + ChatColor.WHITE + "'none'/'set'", false); plugin.getMessages().sendTo(sender, ChatColor.AQUA + key + ": " + ChatColor.WHITE + "gamemode " + ChatColor.AQUA + value + ": " + ChatColor.WHITE + "survival/creative", false); plugin.getMessages().sendTo(sender, ChatColor.AQUA + key + ": " + ChatColor.WHITE + "area " + ChatColor.AQUA + value + ": " + ChatColor.WHITE + "No Value", false); } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("syntax", "/as editregion <name> <key> <value>"), true); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("extra-help", "/as editregion help"), true); } } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("syntax", "/as editregion <name> <key> <value>"), true); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("extra-help", "/as editregion help"), true); } } else { // Setup String name = args[1]; String key = args[2]; String value = args.length > 3 ? args[3] : ""; // Merge message if (args.length > 4) { for (int i = 4; i < args.length; i++) { // Starts at args[4] value = value + args[i] + " "; } value = value.substring(0, value.length() - 1); } // Check region if (plugin.getRegionManager().getRegion(name) == null) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("unknown-region", name), true); } else { // Update region if needed if (RegionKey.isKey(key)) { plugin.getRegionManager().updateRegion(plugin.getRegionManager().getRegion(name), RegionKey.getKey(key), value, sender); } else { plugin.getMessages().sendTo(sender, ChatColor.DARK_RED + plugin.getMessages().getMessage("unknown-key", key), true); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("extra-help", "/as editregion help"), true); } } } } else { plugin.getMessages().sendTo(sender, noPermission, true); } return true; } else if (args[0].equalsIgnoreCase("listregions")) { if (sender.hasPermission(PermissionNodes.REGION_LIST)) { // Sanity check on page number int page = 1; if (args.length >= 2) { try { page = Integer.parseInt(args[1]); } catch (NumberFormatException e) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("unknown-value", args[1]), true); return true; } } // Setup page = Math.abs(page); int resultsPerPage = 6; // Put as a variable for ease of changing Set<Region> set = plugin.getRegionManager().getAllRegions(); List<Region> regions = new ArrayList<Region>(); regions.addAll(set); // Check for empty list if (regions.size() <= 0) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("no-regions"), true); return true; } // Math Double maxPagesD = Math.ceil(regions.size() / resultsPerPage); if (maxPagesD < 1) { maxPagesD = 1.0; } int maxPages = maxPagesD.intValue(); if (maxPagesD < page) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("page-not-found", String.valueOf(page), String.valueOf(maxPages)), true); return true; } // Generate pages String pagenation = ChatColor.DARK_GREEN + "=======[ " + ChatColor.GREEN + "AntiShare Regions " + ChatColor.DARK_GREEN + "|" + ChatColor.GREEN + " Page " + page + "/" + maxPages + ChatColor.DARK_GREEN + " ]======="; plugin.getMessages().sendTo(sender, pagenation, false); for (int i = (page - 1) * resultsPerPage; i < (resultsPerPage < regions.size() ? resultsPerPage * page : regions.size()); i++) { plugin.getMessages().sendTo(sender, ChatColor.DARK_AQUA + "#" + (i + 1) + " " + ChatColor.GOLD + regions.get(i).getName() + ChatColor.YELLOW + " Creator: " + ChatColor.AQUA + regions.get(i).getOwner() + ChatColor.YELLOW + " World: " + ChatColor.AQUA + regions.get(i).getWorldName(), false); } plugin.getMessages().sendTo(sender, pagenation, false); } else { plugin.getMessages().sendTo(sender, noPermission, true); } return true; } else if (args[0].equalsIgnoreCase("tool")) { if (sender.hasPermission(PermissionNodes.TOOL_GET)) { // Sanity check if (!(sender instanceof Player)) { plugin.getMessages().sendTo(sender, notPlayer, true); } else { // Setup Player player = (Player) sender; PlayerInventory inventory = player.getInventory(); // Check inventory if (inventory.firstEmpty() != -1 && inventory.firstEmpty() <= inventory.getSize()) { if (ASUtils.hasTool(AntiShare.ANTISHARE_TOOL, player)) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("have-tool", MaterialAPI.capitalize(AntiShare.ANTISHARE_TOOL.name())), true); } else { ASUtils.giveTool(AntiShare.ANTISHARE_TOOL, player); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("get-tool", MaterialAPI.capitalize(AntiShare.ANTISHARE_TOOL.name())), true); } } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("no-space", String.valueOf(1)), true); } } } else { plugin.getMessages().sendTo(sender, noPermission, true); } return true; } else if (args[0].equalsIgnoreCase("settool")) { if (sender.hasPermission(PermissionNodes.TOOL_GET)) { // Sanity check if (!(sender instanceof Player)) { plugin.getMessages().sendTo(sender, notPlayer, true); } else { // Setup Player player = (Player) sender; PlayerInventory inventory = player.getInventory(); // Check inventory if (inventory.firstEmpty() != -1 && inventory.firstEmpty() <= inventory.getSize()) { if (ASUtils.hasTool(AntiShare.ANTISHARE_SET_TOOL, player)) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("have-tool", MaterialAPI.capitalize(AntiShare.ANTISHARE_SET_TOOL.name())), true); } else { ASUtils.giveTool(AntiShare.ANTISHARE_SET_TOOL, player); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("get-tool", MaterialAPI.capitalize(AntiShare.ANTISHARE_SET_TOOL.name())), true); } } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("no-space", String.valueOf(1)), true); } } } else { plugin.getMessages().sendTo(sender, noPermission, true); } return true; } else if (args[0].equalsIgnoreCase("toolbox")) { if (sender.hasPermission(PermissionNodes.TOOL_GET)) { // Sanity check if (!(sender instanceof Player)) { plugin.getMessages().sendTo(sender, notPlayer, true); } else { // Setup Player player = (Player) sender; PlayerInventory inventory = player.getInventory(); // Find clear spots int clearSpots = 0; for (ItemStack stack : inventory.getContents()) { if (stack == null || stack.getType() == Material.AIR) { clearSpots++; } } // Check inventory if (clearSpots >= 3) { if (!ASUtils.hasTool(AntiShare.ANTISHARE_TOOL, player)) { ASUtils.giveTool(AntiShare.ANTISHARE_TOOL, player, 1); } if (!ASUtils.hasTool(AntiShare.ANTISHARE_SET_TOOL, player)) { ASUtils.giveTool(AntiShare.ANTISHARE_SET_TOOL, player, 2); } if (sender.hasPermission(PermissionNodes.CREATE_CUBOID)) { if (!ASUtils.hasTool(AntiShare.ANTISHARE_CUBOID_TOOL, player)) { ASUtils.giveTool(AntiShare.ANTISHARE_CUBOID_TOOL, player, 3); } } else { plugin.getMessages().sendTo(player, plugin.getMessages().getMessage("cannot-have-cuboid"), true); } plugin.getMessages().sendTo(player, plugin.getMessages().getMessage("tools-give"), true); player.getInventory().setHeldItemSlot(1); } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("no-space", String.valueOf(3)), true); } } } else { plugin.getMessages().sendTo(sender, noPermission, true); } return true; } else if (args[0].equalsIgnoreCase("money")) { if (args.length < 2) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("syntax", "/as money <on/off/status>"), true); } else { if (args[1].equalsIgnoreCase("status") || args[1].equalsIgnoreCase("state")) { plugin.getMessages().sendTo(sender, plugin.getMoneyManager().isSilent(sender.getName()) ? plugin.getMessages().getMessage("fines-not-getting") : plugin.getMessages().getMessage("fines-getting"), true); return true; } if (ASUtils.getBoolean(args[1]) == null) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("syntax", "/as money <on/off/status>"), true); return true; } boolean silent = !ASUtils.getBoolean(args[1]); if (silent) { plugin.getMoneyManager().addToSilentList(sender.getName()); } else { plugin.getMoneyManager().removeFromSilentList(sender.getName()); } plugin.getMessages().sendTo(sender, silent ? plugin.getMessages().getMessage("fines-not-getting") : plugin.getMessages().getMessage("fines-getting"), true); } return true; } else if (args[0].equalsIgnoreCase("simplenotice") || args[0].equalsIgnoreCase("sn")) { if (sender instanceof Player) { Player player = (Player) sender; if (player.getListeningPluginChannels().contains("SimpleNotice")) { if (plugin.isSimpleNoticeEnabled(player.getName())) { plugin.disableSimpleNotice(player.getName()); plugin.getMessages().sendTo(player, plugin.getMessages().getMessage("simplenotice-off"), false); } else { plugin.enableSimpleNotice(player.getName()); plugin.getMessages().sendTo(player, plugin.getMessages().getMessage("simplenotice-on"), false); } } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("simplenotice-missing"), false); } } else { plugin.getMessages().sendTo(sender, notPlayer, true); } return true; } else if (args[0].equalsIgnoreCase("check") || args[0].equalsIgnoreCase("gamemode") || args[0].equalsIgnoreCase("gm")) { if (sender.hasPermission(PermissionNodes.CHECK)) { GameMode gm = null; if (args.length > 1 && !args[1].equalsIgnoreCase("all")) { gm = ASUtils.getGameMode(args[1]); if (gm == null) { Player player = plugin.getServer().getPlayer(args[1]); if (player != null) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("check", player.getName(), MaterialAPI.capitalize(player.getGameMode().name())), false); } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("player-not-found", args[1]), true); } return true; } } if (gm == null) { for (GameMode gamemode : GameMode.values()) { if (ASUtils.findGameModePlayers(gamemode).size() > 0) { plugin.getMessages().sendTo(sender, ChatColor.GOLD + gamemode.name() + ": " + ChatColor.YELLOW + ASUtils.commas(ASUtils.findGameModePlayers(gamemode)), false); } else { plugin.getMessages().sendTo(sender, ChatColor.GOLD + gamemode.name() + ": " + ChatColor.YELLOW + "no one", false); } } } else { plugin.getMessages().sendTo(sender, ChatColor.GOLD + gm.name() + ": " + ChatColor.YELLOW + ASUtils.commas(ASUtils.findGameModePlayers(gm)), false); } } else { plugin.getMessages().sendTo(sender, noPermission, true); } return true; } else if (args[0].equalsIgnoreCase("cuboid")) { if (!sender.hasPermission(PermissionNodes.CREATE_CUBOID)) { plugin.getMessages().sendTo(sender, noPermission, true); return true; } if (args.length > 1) { if (args[1].equalsIgnoreCase("clear")) { if (plugin.getCuboidManager().isCuboidComplete(sender.getName())) { plugin.getCuboidManager().removeCuboid(sender.getName()); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("cuboid-removed"), true); } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("missing-cuboid"), true); } } else if (args[1].equalsIgnoreCase("tool")) { if (!(sender instanceof Player)) { plugin.getMessages().sendTo(sender, notPlayer, true); } else { // Setup Player player = (Player) sender; PlayerInventory inventory = player.getInventory(); // Check inventory if (inventory.firstEmpty() != -1 && inventory.firstEmpty() <= inventory.getSize()) { if (ASUtils.hasTool(AntiShare.ANTISHARE_CUBOID_TOOL, player)) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("have-tool", MaterialAPI.capitalize(AntiShare.ANTISHARE_CUBOID_TOOL.name())), true); } else { ASUtils.giveTool(AntiShare.ANTISHARE_CUBOID_TOOL, player); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("get-tool", MaterialAPI.capitalize(AntiShare.ANTISHARE_CUBOID_TOOL.name())), true); } } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("no-space", String.valueOf(1)), true); } } } else if (args[1].equalsIgnoreCase("status")) { Cuboid cuboid = plugin.getCuboidManager().getCuboid(sender.getName()); if (cuboid == null) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("missing-cuboid"), false); } else { Location min = cuboid.isValid() ? cuboid.getMinimumPoint() : cuboid.getPoint1(); Location max = cuboid.isValid() ? cuboid.getMaximumPoint() : cuboid.getPoint2(); if (min != null) { plugin.getMessages().sendTo(sender, ChatColor.GOLD + "1: " + ChatColor.YELLOW + "(" + min.getBlockX() + ", " + min.getBlockY() + ", " + min.getBlockZ() + ", " + min.getWorld().getName() + ")", false); } else { plugin.getMessages().sendTo(sender, ChatColor.GOLD + "1: " + ChatColor.YELLOW + "not set", false); } if (max != null) { plugin.getMessages().sendTo(sender, ChatColor.GOLD + "2: " + ChatColor.YELLOW + "(" + max.getBlockX() + ", " + max.getBlockY() + ", " + max.getBlockZ() + ", " + max.getWorld().getName() + ")", false); } else { plugin.getMessages().sendTo(sender, ChatColor.GOLD + "2: " + ChatColor.YELLOW + "not set", false); } } } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("syntax", "/as cuboid <clear | tool | status>"), true); } } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("syntax", "/as cuboid <clear | tool | status>"), true); } return true; } else { // This is for all extra commands, like /as help. // This is also for all "non-commands", like /as sakjdha return false; //Shows usage in plugin.yml } } } return false; //Shows usage in plugin.yml }
public boolean onCommand(final CommandSender sender, Command command, String label, String[] args) { if (sender instanceof BlockCommandSender) { return false; } if (command.getName().equalsIgnoreCase("AntiShare")) { if (args.length > 0) { if (args[0].equalsIgnoreCase("version")) { plugin.getMessages().sendTo(sender, ChatColor.YELLOW + "Version: " + ChatColor.GOLD + plugin.getDescription().getVersion() + ChatColor.YELLOW + " Build: " + ChatColor.GOLD + plugin.getBuild(), false); return true; } else if (args[0].equalsIgnoreCase("reload") || args[0].equalsIgnoreCase("rl")) { if (sender.hasPermission(PermissionNodes.RELOAD)) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("reloading"), true); plugin.reload(); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("reloaded"), true); } else { plugin.getMessages().sendTo(sender, noPermission, true); } return true; } else if (args[0].equalsIgnoreCase("mirror")) { // Sanity Check if (!(sender instanceof Player)) { plugin.getMessages().sendTo(sender, notPlayer, true); } else { if (sender.hasPermission(PermissionNodes.MIRROR)) { if (!plugin.settings().features.inventories) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("inventories-not-enabled"), true); return true; } if (args.length < 2) { //plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("syntax", "/as mirror <player> [enderchest/normal] [gamemode] [world]"), true); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("syntax", "/as mirror <player> [enderchest/normal] [gamemode] [world]"), true); } else { // Setup String playername = args[1]; OfflinePlayer player = plugin.getServer().getPlayer(playername); // Find online player first, then we look for offline players if (player == null) { for (OfflinePlayer offlinePlayer : plugin.getServer().getOfflinePlayers()) { if (offlinePlayer.getName().equalsIgnoreCase(playername) || offlinePlayer.getName().toLowerCase().startsWith(playername.toLowerCase())) { player = offlinePlayer; break; } } } // Sanity check if (player == null) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("player-not-found", playername), true); return true; } // Ender chest check boolean isEnder = false; if (args.length > 2) { if (args[2].equalsIgnoreCase("ender") || args[2].equalsIgnoreCase("enderchest")) { isEnder = true; } else if (args[2].equalsIgnoreCase("normal") || args[2].equalsIgnoreCase("player")) { isEnder = false; } else { isEnder = false; plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("assume-normal-inventory", args[2]), true); } } // Per specific game mode GameMode gamemode = player.isOnline() ? ((Player) player).getGameMode() : GameMode.SURVIVAL; if (args.length > 3) { GameMode temp = ASUtils.getGameMode(args[3]); if (temp != null) { gamemode = temp; } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("assume-gamemode", "Game Mode", args[3], MaterialAPI.capitalize(gamemode.name())), true); } } // World check World world = player.isOnline() ? ((Player) player).getWorld() : plugin.getServer().getWorlds().get(0); if (args.length > 4) { World temp = Bukkit.getWorld(args[4]); if (temp == null) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("assume-world", args[4], world.getName()), true); } else { world = temp; } } // Load all inventories if (player.isOnline()) { Player p = (Player) player; plugin.getInventoryManager().savePlayer(p); } ASInventory chosen = ASInventory.load(playername, gamemode, isEnder ? InventoryType.ENDER : InventoryType.PLAYER, world.getName()); if (chosen == null) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("inventory-not-found"), true); return true; } // Create title String title = player.getName() + " | " + ASUtils.gamemodeAbbreviation(gamemode, false) + " | " + world.getName(); // Create displayable inventory DisplayableInventory display = new DisplayableInventory(chosen, title); // Show inventory if (isEnder) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("mirror-ender-welcome", player.getName()), true); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("mirror-edit"), true); } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("mirror-welcome", player.getName()), true); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("mirror-edit"), true); } ((Player) sender).openInventory(display.getInventory()); // Creates the "live editing" window } } else { plugin.getMessages().sendTo(sender, noPermission, true); } } return true; } else if (args[0].equalsIgnoreCase("region")) { if (sender.hasPermission(PermissionNodes.REGION_CREATE)) { // Sanity Check if (sender instanceof Player) { Player player = (Player) sender; if (args.length < 3) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("syntax", "/as region <gamemode> <name>"), true); } else { String regionName = args[2]; GameMode gamemode = ASUtils.getGameMode(args[1]); if (gamemode != null) { if (!plugin.getRegionManager().isRegionNameTaken(regionName)) { if (plugin.getCuboidManager().isCuboidComplete(player.getName())) { Cuboid cuboid = plugin.getCuboidManager().getCuboid(player.getName()); plugin.getRegionManager().addRegion(cuboid, player.getName(), regionName, gamemode); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("region-created"), true); } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("missing-cuboid"), true); } } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("name-in-use"), true); } } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("unknown-gamemode", args[1]), true); } } } else { plugin.getMessages().sendTo(sender, notPlayer, true); } } else { plugin.getMessages().sendTo(sender, noPermission, true); } return true; } else if (args[0].equalsIgnoreCase("rmregion") || args[0].equalsIgnoreCase("removeregion")) { if (sender.hasPermission(PermissionNodes.REGION_DELETE)) { // Sanity check if (sender instanceof Player) { // Remove region if (args.length == 1) { Location location = ((Player) sender).getLocation(); Region region = plugin.getRegionManager().getRegion(location); if (region != null) { plugin.getRegionManager().removeRegion(region.getName()); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("region-remove"), true); } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("no-foot-region"), true); } } else { String regionName = args[1]; Region region = plugin.getRegionManager().getRegion(regionName); if (region != null) { plugin.getRegionManager().removeRegion(region.getName()); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("region-remove"), true); } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("unknown-region", regionName), true); } } } else { // Remove region if (args.length > 1) { String regionName = args[1]; Region region = plugin.getRegionManager().getRegion(regionName); if (region != null) { plugin.getRegionManager().removeRegion(region.getName()); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("region-remove"), true); } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("unknown-region", regionName), true); } } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("syntax", "/as rmregion <name>"), true); } } } else { plugin.getMessages().sendTo(sender, noPermission, true); } return true; } else if (args[0].equalsIgnoreCase("editregion")) { if (sender.hasPermission(PermissionNodes.REGION_EDIT)) { // Check validity of key boolean valid = false; if (args.length >= 3) { if (RegionKey.isKey(args[2])) { if (!RegionKey.requiresValue(RegionKey.getKey(args[2]))) { valid = true; // we have at least 3 values in args[] and the key does not need a value } } } if (args.length >= 4) { valid = true; } if (!valid) { // Show help if (args.length >= 2) { if (args[1].equalsIgnoreCase("help")) { String key = plugin.getMessages().getMessage("key").toLowerCase(); String value = plugin.getMessages().getMessage("value").toLowerCase(); key = key.substring(0, 1).toUpperCase() + key.substring(1); value = value.substring(0, 1).toUpperCase() + value.substring(1); plugin.getMessages().sendTo(sender, ChatColor.GOLD + "/as editregion <name> <key> <value>", false); plugin.getMessages().sendTo(sender, ChatColor.AQUA + key + ": " + ChatColor.WHITE + "name " + ChatColor.AQUA + value + ": " + ChatColor.WHITE + "<any name>", false); plugin.getMessages().sendTo(sender, ChatColor.AQUA + key + ": " + ChatColor.WHITE + "ShowEnterMessage " + ChatColor.AQUA + value + ": " + ChatColor.WHITE + "true/false", false); plugin.getMessages().sendTo(sender, ChatColor.AQUA + key + ": " + ChatColor.WHITE + "ShowExitMessage " + ChatColor.AQUA + value + ": " + ChatColor.WHITE + "true/false", false); plugin.getMessages().sendTo(sender, ChatColor.AQUA + key + ": " + ChatColor.WHITE + "EnterMessage " + ChatColor.AQUA + value + ": " + ChatColor.WHITE + "<enter message>", false); plugin.getMessages().sendTo(sender, ChatColor.AQUA + key + ": " + ChatColor.WHITE + "ExitMessage " + ChatColor.AQUA + value + ": " + ChatColor.WHITE + "<exit message>", false); plugin.getMessages().sendTo(sender, ChatColor.AQUA + key + ": " + ChatColor.WHITE + "inventory " + ChatColor.AQUA + value + ": " + ChatColor.WHITE + "'none'/'set'", false); plugin.getMessages().sendTo(sender, ChatColor.AQUA + key + ": " + ChatColor.WHITE + "gamemode " + ChatColor.AQUA + value + ": " + ChatColor.WHITE + "survival/creative", false); plugin.getMessages().sendTo(sender, ChatColor.AQUA + key + ": " + ChatColor.WHITE + "area " + ChatColor.AQUA + value + ": " + ChatColor.WHITE + "No Value", false); } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("syntax", "/as editregion <name> <key> <value>"), true); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("extra-help", "/as editregion help"), true); } } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("syntax", "/as editregion <name> <key> <value>"), true); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("extra-help", "/as editregion help"), true); } } else { // Setup String name = args[1]; String key = args[2]; String value = args.length > 3 ? args[3] : ""; // Merge message if (args.length > 4) { for (int i = 4; i < args.length; i++) { // Starts at args[4] value = value + args[i] + " "; } value = value.substring(0, value.length() - 1); } // Check region if (plugin.getRegionManager().getRegion(name) == null) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("unknown-region", name), true); } else { // Update region if needed if (RegionKey.isKey(key)) { plugin.getRegionManager().updateRegion(plugin.getRegionManager().getRegion(name), RegionKey.getKey(key), value, sender); } else { plugin.getMessages().sendTo(sender, ChatColor.DARK_RED + plugin.getMessages().getMessage("unknown-key", key), true); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("extra-help", "/as editregion help"), true); } } } } else { plugin.getMessages().sendTo(sender, noPermission, true); } return true; } else if (args[0].equalsIgnoreCase("listregions")) { if (sender.hasPermission(PermissionNodes.REGION_LIST)) { // Sanity check on page number int page = 1; if (args.length >= 2) { try { page = Integer.parseInt(args[1]); } catch (NumberFormatException e) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("unknown-value", args[1]), true); return true; } } // Setup page = Math.abs(page); int resultsPerPage = 6; // Put as a variable for ease of changing Set<Region> set = plugin.getRegionManager().getAllRegions(); List<Region> regions = new ArrayList<Region>(); regions.addAll(set); // Check for empty list if (regions.size() <= 0) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("no-regions"), true); return true; } // Math Double maxPagesD = Math.ceil(regions.size() / resultsPerPage); if (maxPagesD < 1) { maxPagesD = 1.0; } int maxPages = maxPagesD.intValue(); if (maxPagesD < page) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("page-not-found", String.valueOf(page), String.valueOf(maxPages)), true); return true; } // Generate pages String pagenation = ChatColor.DARK_GREEN + "=======[ " + ChatColor.GREEN + "AntiShare Regions " + ChatColor.DARK_GREEN + "|" + ChatColor.GREEN + " Page " + page + "/" + maxPages + ChatColor.DARK_GREEN + " ]======="; plugin.getMessages().sendTo(sender, pagenation, false); for (int i = (page - 1) * resultsPerPage; i < (resultsPerPage < regions.size() ? resultsPerPage * page : regions.size()); i++) { plugin.getMessages().sendTo(sender, ChatColor.DARK_AQUA + "#" + (i + 1) + " " + ChatColor.GOLD + regions.get(i).getName() + ChatColor.YELLOW + " Creator: " + ChatColor.AQUA + regions.get(i).getOwner() + ChatColor.YELLOW + " World: " + ChatColor.AQUA + regions.get(i).getWorldName(), false); } plugin.getMessages().sendTo(sender, pagenation, false); } else { plugin.getMessages().sendTo(sender, noPermission, true); } return true; } else if (args[0].equalsIgnoreCase("tool")) { if (sender.hasPermission(PermissionNodes.TOOL_GET)) { // Sanity check if (!(sender instanceof Player)) { plugin.getMessages().sendTo(sender, notPlayer, true); } else { // Setup Player player = (Player) sender; PlayerInventory inventory = player.getInventory(); // Check inventory if (inventory.firstEmpty() != -1 && inventory.firstEmpty() <= inventory.getSize()) { if (ASUtils.hasTool(AntiShare.ANTISHARE_TOOL, player)) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("have-tool", MaterialAPI.capitalize(AntiShare.ANTISHARE_TOOL.name())), true); } else { ASUtils.giveTool(AntiShare.ANTISHARE_TOOL, player); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("get-tool", MaterialAPI.capitalize(AntiShare.ANTISHARE_TOOL.name())), true); } } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("no-space", String.valueOf(1)), true); } } } else { plugin.getMessages().sendTo(sender, noPermission, true); } return true; } else if (args[0].equalsIgnoreCase("settool")) { if (sender.hasPermission(PermissionNodes.TOOL_GET)) { // Sanity check if (!(sender instanceof Player)) { plugin.getMessages().sendTo(sender, notPlayer, true); } else { // Setup Player player = (Player) sender; PlayerInventory inventory = player.getInventory(); // Check inventory if (inventory.firstEmpty() != -1 && inventory.firstEmpty() <= inventory.getSize()) { if (ASUtils.hasTool(AntiShare.ANTISHARE_SET_TOOL, player)) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("have-tool", MaterialAPI.capitalize(AntiShare.ANTISHARE_SET_TOOL.name())), true); } else { ASUtils.giveTool(AntiShare.ANTISHARE_SET_TOOL, player); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("get-tool", MaterialAPI.capitalize(AntiShare.ANTISHARE_SET_TOOL.name())), true); } } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("no-space", String.valueOf(1)), true); } } } else { plugin.getMessages().sendTo(sender, noPermission, true); } return true; } else if (args[0].equalsIgnoreCase("toolbox")) { if (sender.hasPermission(PermissionNodes.TOOL_GET)) { // Sanity check if (!(sender instanceof Player)) { plugin.getMessages().sendTo(sender, notPlayer, true); } else { // Setup Player player = (Player) sender; PlayerInventory inventory = player.getInventory(); // Find clear spots int clearSpots = 0; for (ItemStack stack : inventory.getContents()) { if (stack == null || stack.getType() == Material.AIR) { clearSpots++; } } // Check inventory if (clearSpots >= 3) { if (!ASUtils.hasTool(AntiShare.ANTISHARE_TOOL, player)) { ASUtils.giveTool(AntiShare.ANTISHARE_TOOL, player, 1); } if (!ASUtils.hasTool(AntiShare.ANTISHARE_SET_TOOL, player)) { ASUtils.giveTool(AntiShare.ANTISHARE_SET_TOOL, player, 2); } if (sender.hasPermission(PermissionNodes.CREATE_CUBOID)) { if (!ASUtils.hasTool(AntiShare.ANTISHARE_CUBOID_TOOL, player)) { ASUtils.giveTool(AntiShare.ANTISHARE_CUBOID_TOOL, player, 3); } } else { plugin.getMessages().sendTo(player, plugin.getMessages().getMessage("cannot-have-cuboid"), true); } plugin.getMessages().sendTo(player, plugin.getMessages().getMessage("tools-give"), true); player.getInventory().setHeldItemSlot(1); } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("no-space", String.valueOf(3)), true); } } } else { plugin.getMessages().sendTo(sender, noPermission, true); } return true; } else if (args[0].equalsIgnoreCase("money")) { if (args.length < 2) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("syntax", "/as money <on/off/status>"), true); } else { if (args[1].equalsIgnoreCase("status") || args[1].equalsIgnoreCase("state")) { plugin.getMessages().sendTo(sender, plugin.getMoneyManager().isSilent(sender.getName()) ? plugin.getMessages().getMessage("fines-not-getting") : plugin.getMessages().getMessage("fines-getting"), true); return true; } if (ASUtils.getBoolean(args[1]) == null) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("syntax", "/as money <on/off/status>"), true); return true; } boolean silent = !ASUtils.getBoolean(args[1]); if (silent) { plugin.getMoneyManager().addToSilentList(sender.getName()); } else { plugin.getMoneyManager().removeFromSilentList(sender.getName()); } plugin.getMessages().sendTo(sender, silent ? plugin.getMessages().getMessage("fines-not-getting") : plugin.getMessages().getMessage("fines-getting"), true); } return true; } else if (args[0].equalsIgnoreCase("simplenotice") || args[0].equalsIgnoreCase("sn")) { if (sender instanceof Player) { Player player = (Player) sender; if (player.getListeningPluginChannels().contains("SimpleNotice")) { if (plugin.isSimpleNoticeEnabled(player.getName())) { plugin.disableSimpleNotice(player.getName()); plugin.getMessages().sendTo(player, plugin.getMessages().getMessage("simplenotice-off"), false); } else { plugin.enableSimpleNotice(player.getName()); plugin.getMessages().sendTo(player, plugin.getMessages().getMessage("simplenotice-on"), false); } } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("simplenotice-missing"), false); } } else { plugin.getMessages().sendTo(sender, notPlayer, true); } return true; } else if (args[0].equalsIgnoreCase("check") || args[0].equalsIgnoreCase("gamemode") || args[0].equalsIgnoreCase("gm")) { if (sender.hasPermission(PermissionNodes.CHECK)) { GameMode gm = null; if (args.length > 1 && !args[1].equalsIgnoreCase("all")) { gm = ASUtils.getGameMode(args[1]); if (gm == null) { Player player = plugin.getServer().getPlayer(args[1]); if (player != null) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("check", player.getName(), MaterialAPI.capitalize(player.getGameMode().name())), false); } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("player-not-found", args[1]), true); } return true; } } if (gm == null) { for (GameMode gamemode : GameMode.values()) { if (ASUtils.findGameModePlayers(gamemode).size() > 0) { plugin.getMessages().sendTo(sender, ChatColor.GOLD + gamemode.name() + ": " + ChatColor.YELLOW + ASUtils.commas(ASUtils.findGameModePlayers(gamemode)), false); } else { plugin.getMessages().sendTo(sender, ChatColor.GOLD + gamemode.name() + ": " + ChatColor.YELLOW + "no one", false); } } } else { plugin.getMessages().sendTo(sender, ChatColor.GOLD + gm.name() + ": " + ChatColor.YELLOW + ASUtils.commas(ASUtils.findGameModePlayers(gm)), false); } } else { plugin.getMessages().sendTo(sender, noPermission, true); } return true; } else if (args[0].equalsIgnoreCase("cuboid")) { if (!sender.hasPermission(PermissionNodes.CREATE_CUBOID)) { plugin.getMessages().sendTo(sender, noPermission, true); return true; } if (args.length > 1) { if (args[1].equalsIgnoreCase("clear")) { if (plugin.getCuboidManager().isCuboidComplete(sender.getName())) { plugin.getCuboidManager().removeCuboid(sender.getName()); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("cuboid-removed"), true); } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("missing-cuboid"), true); } } else if (args[1].equalsIgnoreCase("tool")) { if (!(sender instanceof Player)) { plugin.getMessages().sendTo(sender, notPlayer, true); } else { // Setup Player player = (Player) sender; PlayerInventory inventory = player.getInventory(); // Check inventory if (inventory.firstEmpty() != -1 && inventory.firstEmpty() <= inventory.getSize()) { if (ASUtils.hasTool(AntiShare.ANTISHARE_CUBOID_TOOL, player)) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("have-tool", MaterialAPI.capitalize(AntiShare.ANTISHARE_CUBOID_TOOL.name())), true); } else { ASUtils.giveTool(AntiShare.ANTISHARE_CUBOID_TOOL, player); plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("get-tool", MaterialAPI.capitalize(AntiShare.ANTISHARE_CUBOID_TOOL.name())), true); } } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("no-space", String.valueOf(1)), true); } } } else if (args[1].equalsIgnoreCase("status")) { Cuboid cuboid = plugin.getCuboidManager().getCuboid(sender.getName()); if (cuboid == null) { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("missing-cuboid"), false); } else { Location min = cuboid.isValid() ? cuboid.getMinimumPoint() : cuboid.getPoint1(); Location max = cuboid.isValid() ? cuboid.getMaximumPoint() : cuboid.getPoint2(); if (min != null) { plugin.getMessages().sendTo(sender, ChatColor.GOLD + "1: " + ChatColor.YELLOW + "(" + min.getBlockX() + ", " + min.getBlockY() + ", " + min.getBlockZ() + ", " + min.getWorld().getName() + ")", false); } else { plugin.getMessages().sendTo(sender, ChatColor.GOLD + "1: " + ChatColor.YELLOW + "not set", false); } if (max != null) { plugin.getMessages().sendTo(sender, ChatColor.GOLD + "2: " + ChatColor.YELLOW + "(" + max.getBlockX() + ", " + max.getBlockY() + ", " + max.getBlockZ() + ", " + max.getWorld().getName() + ")", false); } else { plugin.getMessages().sendTo(sender, ChatColor.GOLD + "2: " + ChatColor.YELLOW + "not set", false); } } } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("syntax", "/as cuboid <clear | tool | status>"), true); } } else { plugin.getMessages().sendTo(sender, plugin.getMessages().getMessage("syntax", "/as cuboid <clear | tool | status>"), true); } return true; } else { // This is for all extra commands, like /as help. // This is also for all "non-commands", like /as sakjdha return false; //Shows usage in plugin.yml } } } return false; //Shows usage in plugin.yml }
diff --git a/src/main/java/servlet/CreateTaskServlet.java b/src/main/java/servlet/CreateTaskServlet.java index dcdc54f..b16f405 100644 --- a/src/main/java/servlet/CreateTaskServlet.java +++ b/src/main/java/servlet/CreateTaskServlet.java @@ -1,112 +1,114 @@ package servlet; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.LinkedList; import java.util.List; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import crowdtrust.AnnotationType; import crowdtrust.InputType; import crowdtrust.MediaType; import db.TaskDb; public class CreateTaskServlet extends HttpServlet { private static final long serialVersionUID = -2917901106721177733L; private static final String TASKS_DIRECTORY = "/vol/project/2012/362/g1236218/TaskFiles/"; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); //validate user credentials HttpSession session = request.getSession(); if (session == null||session.getAttribute("account_id") == null) { response.sendRedirect("/"); return; } int accountID = (Integer) session.getAttribute("account_id"); //validate user, add task to db, maked task directory String name = request.getParameter("name"); float accuracy; int max_labels; int num_answers = 0; int min = 0; int max = 0; double step = 0; MediaType media_type; AnnotationType annotation_type; InputType input_type; try { accuracy = Float.parseFloat(request.getParameter("accuracy")); max_labels = Integer.parseInt(request.getParameter("max_labels")); media_type = MediaType.valueOf(request.getParameter("media_type")); annotation_type = AnnotationType.valueOf(request.getParameter("annotation_type")); if(annotation_type.equals(AnnotationType.CONTINUOUS)) { min = Integer.parseInt(request.getParameter("min")); max = Integer.parseInt(request.getParameter("max")); step = Double.parseDouble(request.getParameter("step")); - }else { + } else if(annotation_type.equals(AnnotationType.BINARY)) { + num_answers = 2; + } else { num_answers = Integer.parseInt(request.getParameter("num_answers")); } input_type = InputType.valueOf(request.getParameter("input_type")); } catch (NumberFormatException e) { printAndRedirect(out, "invalid input"); e.printStackTrace(); return; } long expiry; try { expiry = getLongDate(request); } catch (ParseException e) { printAndRedirect(out, "invalid date format"); return; } List<String> answers = new LinkedList<String>(); String answer = request.getParameter("answer1"); for(int i = 2 ; i < num_answers ; i++) { answers.add(answer); answer = request.getParameter("answer" + i); } int tid = TaskDb.addTask(accountID, name, request.getParameter("question"), accuracy, media_type, annotation_type, input_type, max_labels, expiry, answers, min, max, step); if( tid > 0) { File taskFolder = new File(TASKS_DIRECTORY + "/" + tid); taskFolder.mkdirs(); response.sendRedirect("/client/upload.jsp"); } } private void printAndRedirect(PrintWriter out, String string) { out.println("<html>"); out.println("<head>"); out.println("<meta http-equiv=\"Refresh\" content=\"3\"; url=\"addtask.jsp\">"); out.println("</head>"); out.println("<body>"); out.println(string + ", returning to add task page"); out.println("</body>"); out.println("</html>"); } private long getLongDate(HttpServletRequest request) throws ParseException{ String expiryDateStr = request.getParameter("day") + request.getParameter("month") + request.getParameter("year"); Date expiryDate = new SimpleDateFormat("ddMMyyyy").parse(expiryDateStr); return expiryDate.getTime(); } }
true
true
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); //validate user credentials HttpSession session = request.getSession(); if (session == null||session.getAttribute("account_id") == null) { response.sendRedirect("/"); return; } int accountID = (Integer) session.getAttribute("account_id"); //validate user, add task to db, maked task directory String name = request.getParameter("name"); float accuracy; int max_labels; int num_answers = 0; int min = 0; int max = 0; double step = 0; MediaType media_type; AnnotationType annotation_type; InputType input_type; try { accuracy = Float.parseFloat(request.getParameter("accuracy")); max_labels = Integer.parseInt(request.getParameter("max_labels")); media_type = MediaType.valueOf(request.getParameter("media_type")); annotation_type = AnnotationType.valueOf(request.getParameter("annotation_type")); if(annotation_type.equals(AnnotationType.CONTINUOUS)) { min = Integer.parseInt(request.getParameter("min")); max = Integer.parseInt(request.getParameter("max")); step = Double.parseDouble(request.getParameter("step")); }else { num_answers = Integer.parseInt(request.getParameter("num_answers")); } input_type = InputType.valueOf(request.getParameter("input_type")); } catch (NumberFormatException e) { printAndRedirect(out, "invalid input"); e.printStackTrace(); return; } long expiry; try { expiry = getLongDate(request); } catch (ParseException e) { printAndRedirect(out, "invalid date format"); return; } List<String> answers = new LinkedList<String>(); String answer = request.getParameter("answer1"); for(int i = 2 ; i < num_answers ; i++) { answers.add(answer); answer = request.getParameter("answer" + i); } int tid = TaskDb.addTask(accountID, name, request.getParameter("question"), accuracy, media_type, annotation_type, input_type, max_labels, expiry, answers, min, max, step); if( tid > 0) { File taskFolder = new File(TASKS_DIRECTORY + "/" + tid); taskFolder.mkdirs(); response.sendRedirect("/client/upload.jsp"); } }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); //validate user credentials HttpSession session = request.getSession(); if (session == null||session.getAttribute("account_id") == null) { response.sendRedirect("/"); return; } int accountID = (Integer) session.getAttribute("account_id"); //validate user, add task to db, maked task directory String name = request.getParameter("name"); float accuracy; int max_labels; int num_answers = 0; int min = 0; int max = 0; double step = 0; MediaType media_type; AnnotationType annotation_type; InputType input_type; try { accuracy = Float.parseFloat(request.getParameter("accuracy")); max_labels = Integer.parseInt(request.getParameter("max_labels")); media_type = MediaType.valueOf(request.getParameter("media_type")); annotation_type = AnnotationType.valueOf(request.getParameter("annotation_type")); if(annotation_type.equals(AnnotationType.CONTINUOUS)) { min = Integer.parseInt(request.getParameter("min")); max = Integer.parseInt(request.getParameter("max")); step = Double.parseDouble(request.getParameter("step")); } else if(annotation_type.equals(AnnotationType.BINARY)) { num_answers = 2; } else { num_answers = Integer.parseInt(request.getParameter("num_answers")); } input_type = InputType.valueOf(request.getParameter("input_type")); } catch (NumberFormatException e) { printAndRedirect(out, "invalid input"); e.printStackTrace(); return; } long expiry; try { expiry = getLongDate(request); } catch (ParseException e) { printAndRedirect(out, "invalid date format"); return; } List<String> answers = new LinkedList<String>(); String answer = request.getParameter("answer1"); for(int i = 2 ; i < num_answers ; i++) { answers.add(answer); answer = request.getParameter("answer" + i); } int tid = TaskDb.addTask(accountID, name, request.getParameter("question"), accuracy, media_type, annotation_type, input_type, max_labels, expiry, answers, min, max, step); if( tid > 0) { File taskFolder = new File(TASKS_DIRECTORY + "/" + tid); taskFolder.mkdirs(); response.sendRedirect("/client/upload.jsp"); } }
diff --git a/cmd/src/iumfs/hdfs/HdfsFile.java b/cmd/src/iumfs/hdfs/HdfsFile.java index d86e8aa..91cdbef 100644 --- a/cmd/src/iumfs/hdfs/HdfsFile.java +++ b/cmd/src/iumfs/hdfs/HdfsFile.java @@ -1,297 +1,299 @@ /* * Copyright 2011 Kazuyoshi Aizawa * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package iumfs.hdfs; import iumfs.FileExistsException; import iumfs.IumfsFile; import iumfs.NotSupportedException; import iumfs.Request; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.logging.Logger; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.*; import org.apache.hadoop.hdfs.protocol.AlreadyBeingCreatedException; /** * * @author ka78231 */ public class HdfsFile extends IumfsFile { private FileSystem fs; protected static final Logger logger = Logger.getLogger(Main.class.getName()); private String server; HdfsFile(String server, String pathname) { super(pathname); this.server = server; fs = getFileSystem(); Date now = new Date(); setAtime(now.getTime()); setCtime(now.getTime()); setMtime(now.getTime()); } @Override public long read(ByteBuffer buf, long size, long offset) throws FileNotFoundException, IOException, NotSupportedException { int ret; FSDataInputStream fsdis = fs.open(new Path(getPath())); ret = fsdis.read(offset, buf.array(), Request.RESPONSE_HEADER_SIZE, (int) size); fsdis.close(); logger.fine("read offset=" + offset + ",size=" + size); return ret; } @Override public long write(byte[] buf, long size, long offset) throws FileNotFoundException, IOException, NotSupportedException { // ファイルの属性を得る FileStatus fstat = fs.getFileStatus(new Path(getPath())); long filesize = fstat.getLen(); + int written = 0; /* * この iumfscntl から受け取る write リクエストのオフセット値 は必ず PAGE 境界上。そして受け取るデータは PAGE * 境界からの データ。(既存データ含む) * * PAGESIZE PAGESIZE |---------------------|---------------------| * |<---------- filesize -------->| |<---- offset ------->|<-- size * --->| * * HDFS の append は filesize 直後からの追記しか許さないので iumfs * から渡されたデータから、追記すべき分を算出し、 HDFS に要求する。 */ if (offset + size < filesize) { // ファイルサイズ未満のデータ書き込み要求。すなわち変更。 throw new NotSupportedException(); } FSDataOutputStream fsdos = fs.append(new Path(getPath())); /* * ファイルの最後に/サイズのデータを書き込み用バッファに読み込む 現在はオフセットの指定はできず Append だけ。 */ try { if (offset > filesize) { // オフセットがファイルサイズを超える要求。 // まず、空白部分を null で埋める。 fsdos.write(new byte[(int) (offset - filesize)]); fsdos.write(getDataByRange(buf, 0, size)); } else { // オフセットがファイルサイズ未満の要求。 logger.warning("offset=" + (int) (filesize - offset)); fsdos.write(getDataByRange(buf, filesize - offset, size)); } } finally { + written = fsdos.size(); fsdos.close(); } - return fsdos.size(); + return written; } /* * <p>FileSystem.mkdir won't return with err even directory already exits. * So here we need to check the existance by ourself and return false. */ @Override public boolean mkdir() { try { /* * Create new directory on HDFS */ if (fs.exists(new Path(getPath())) == true) { logger.fine("cannot create directory"); return false; } if (fs.mkdirs(new Path(getPath())) == false) { logger.fine("cannot create directory"); return false; } return true; } catch (IOException ex) { /* * can't throw IOException here. So return false, and iumfs.mkdir * would back this 'false' to IOException... */ return false; } } @Override public boolean delete() { try { Path path = new Path(getPath()); if (fs.delete(path, true) == false) { logger.fine("cannot remove " + path.getName()); return false; } } catch (IOException ex) { return false; } return true; } /** * List files under directory which expres this object. This corresponds * readdir. * * @return */ @Override public File[] listFiles() { List<File> filelist = new ArrayList<File>(); FileStatus fstats[]; try { fstats = fs.listStatus(new Path(getPath())); } catch (IOException ex) { return null; } for (FileStatus fstat : fstats) { filelist.add(new File(fstat.getPath().getName())); } return filelist.toArray(new File[0]); } @Override public long getFileType() { try { if (fs.getFileStatus(new Path(getPath())).isDir()) { return IumfsFile.VDIR; } else { return IumfsFile.VREG; } } catch (IOException ex) { return IumfsFile.VREG; } } @Override public long getPermission() { if (isDirectory()) { return (long) 0040755; // directory } else { return (long) 0100444; // regular file } } @Override public boolean isDirectory() { try { return fs.getFileStatus(new Path(getPath())).isDir(); } catch (IOException ex) { return false; } } /** * <p>FileSystem.create を実行する</p> <p>creat(2) が呼ばれたということは既存ファイルがあった場合 * 既存データを削除(O_TRUNC相当)しなければならないが、 HDFS では データの途中 * 変更はできないので、既存ファイルがあったらエラーリターンする</p> */ @Override public void create() throws IOException { /* * HDFS 上に新規ファイルを作成し、結果をレスポンスヘッダをセットする */ try { Path path = new Path(getPath()); //ファイルが存在したら EEXIST を返す if (fs.exists(path) == true) { logger.fine("cannot create file"); throw new FileExistsException(); } FSDataOutputStream fsdos = fs.create(path); /* * レスポンスヘッダをセット */ fsdos.close(); } catch (AlreadyBeingCreatedException ex) { logger.fine("AlreadyBeingCreatedException when writing"); throw new FileExistsException(); } catch (IOException ex) { logger.fine("IOException happend when writing"); throw ex; } } private FileSystem getFileSystem() { if (fs == null) { try { Configuration conf = new Configuration(); conf.set("fs.defaultFS", server); logger.finer("server=" + server); fs = FileSystem.get(conf); } catch (IOException ex) { ex.printStackTrace(); System.exit(1); } } return fs; } public static IumfsFile getFile(String server, String pathname) { return new HdfsFile(server, pathname); } /** * @return the server */ public String getServer() { return server; } /** * @param server the server to set */ public void setServer(String server) { this.server = server; } @Override public boolean exists() { try { return getFileSystem().exists(new Path(getPath())); } catch (IOException ex) { ex.printStackTrace(); return false; } } @Override public long length() { // ファイルの属性を得る FileStatus fstat; try { fstat = fs.getFileStatus(new Path(getPath())); } catch (IOException ex) { return 0; } return fstat.getLen(); } public byte[] getDataByRange(byte[] data, long from, long to) { logger.finer("from=" + from + "to=" + to); return Arrays.copyOfRange(data, (int) from, (int) to); } }
false
true
public long write(byte[] buf, long size, long offset) throws FileNotFoundException, IOException, NotSupportedException { // ファイルの属性を得る FileStatus fstat = fs.getFileStatus(new Path(getPath())); long filesize = fstat.getLen(); /* * この iumfscntl から受け取る write リクエストのオフセット値 は必ず PAGE 境界上。そして受け取るデータは PAGE * 境界からの データ。(既存データ含む) * * PAGESIZE PAGESIZE |---------------------|---------------------| * |<---------- filesize -------->| |<---- offset ------->|<-- size * --->| * * HDFS の append は filesize 直後からの追記しか許さないので iumfs * から渡されたデータから、追記すべき分を算出し、 HDFS に要求する。 */ if (offset + size < filesize) { // ファイルサイズ未満のデータ書き込み要求。すなわち変更。 throw new NotSupportedException(); } FSDataOutputStream fsdos = fs.append(new Path(getPath())); /* * ファイルの最後に/サイズのデータを書き込み用バッファに読み込む 現在はオフセットの指定はできず Append だけ。 */ try { if (offset > filesize) { // オフセットがファイルサイズを超える要求。 // まず、空白部分を null で埋める。 fsdos.write(new byte[(int) (offset - filesize)]); fsdos.write(getDataByRange(buf, 0, size)); } else { // オフセットがファイルサイズ未満の要求。 logger.warning("offset=" + (int) (filesize - offset)); fsdos.write(getDataByRange(buf, filesize - offset, size)); } } finally { fsdos.close(); } return fsdos.size(); }
public long write(byte[] buf, long size, long offset) throws FileNotFoundException, IOException, NotSupportedException { // ファイルの属性を得る FileStatus fstat = fs.getFileStatus(new Path(getPath())); long filesize = fstat.getLen(); int written = 0; /* * この iumfscntl から受け取る write リクエストのオフセット値 は必ず PAGE 境界上。そして受け取るデータは PAGE * 境界からの データ。(既存データ含む) * * PAGESIZE PAGESIZE |---------------------|---------------------| * |<---------- filesize -------->| |<---- offset ------->|<-- size * --->| * * HDFS の append は filesize 直後からの追記しか許さないので iumfs * から渡されたデータから、追記すべき分を算出し、 HDFS に要求する。 */ if (offset + size < filesize) { // ファイルサイズ未満のデータ書き込み要求。すなわち変更。 throw new NotSupportedException(); } FSDataOutputStream fsdos = fs.append(new Path(getPath())); /* * ファイルの最後に/サイズのデータを書き込み用バッファに読み込む 現在はオフセットの指定はできず Append だけ。 */ try { if (offset > filesize) { // オフセットがファイルサイズを超える要求。 // まず、空白部分を null で埋める。 fsdos.write(new byte[(int) (offset - filesize)]); fsdos.write(getDataByRange(buf, 0, size)); } else { // オフセットがファイルサイズ未満の要求。 logger.warning("offset=" + (int) (filesize - offset)); fsdos.write(getDataByRange(buf, filesize - offset, size)); } } finally { written = fsdos.size(); fsdos.close(); } return written; }
diff --git a/herbal2/src/tw/edu/ntust/dt/herbal2/activity/AskActivity.java b/herbal2/src/tw/edu/ntust/dt/herbal2/activity/AskActivity.java index f71828b..c2fc19f 100644 --- a/herbal2/src/tw/edu/ntust/dt/herbal2/activity/AskActivity.java +++ b/herbal2/src/tw/edu/ntust/dt/herbal2/activity/AskActivity.java @@ -1,156 +1,156 @@ package tw.edu.ntust.dt.herbal2.activity; import java.util.ArrayList; import java.util.List; import tw.edu.ntust.dt.herbal2.R; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.util.SparseArray; import android.view.Menu; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; public class AskActivity extends Activity { // private final static Map<Integer, List<Integer>> edge = new // HashMap<Integer, List<Integer>>(); private final static SparseArray<List<Integer>> edge = new SparseArray<List<Integer>>(); private static Animation animationFadeIn; private static Animation animationFadeIn2; private ImageView askQ, askYes, askNo; private int[][] ask = new int[][] { { R.drawable.ask_0, R.drawable.ask_0_yes, R.drawable.ask_0_no }, { R.drawable.ask_1, R.drawable.ask_1_yes, R.drawable.ask_1_no }, { R.drawable.ask_2, R.drawable.ask_2_yes, R.drawable.ask_2_no }, { R.drawable.ask_3, R.drawable.ask_3_yes, R.drawable.ask_3_no }, { R.drawable.ask_4, R.drawable.ask_4_yes, R.drawable.ask_4_no }, { R.drawable.ask_5, R.drawable.ask_5_yes, R.drawable.ask_5_no }, { R.drawable.ask_6, R.drawable.ask_6_yes, R.drawable.ask_6_no }, { R.drawable.ask_7, R.drawable.ask_7_yes, R.drawable.ask_7_no } }; static { for (int i = 0; i < 8 * 3; i++) { edge.put(i, new ArrayList<Integer>()); } edge.get(0).add(5); edge.get(0).add(4); edge.get(5).add(1); edge.get(5).add(8 + 4); edge.get(1).add(R.drawable.result_yenyen); edge.get(1).add(6); edge.get(6).add(R.drawable.result_jie); edge.get(6).add(R.drawable.result_ya); edge.get(8 + 4).add(7); edge.get(8 + 4).add(2); edge.get(7).add(3); edge.get(7).add(6); edge.get(3).add(R.drawable.result_nee); edge.get(3).add(R.drawable.result_yenyen); edge.get(6).add(R.drawable.result_jie); edge.get(6).add(R.drawable.result_ya); edge.get(2).add(R.drawable.result_yen); edge.get(2).add(R.drawable.result_jian); edge.get(4).add(8 + 7); edge.get(4).add(8 + 3); edge.get(8 + 7).add(8 * 2 + 3); edge.get(8 + 7).add(8 + 6); edge.get(8 * 2 + 3).add(R.drawable.result_nee); edge.get(8 * 2 + 3).add(R.drawable.result_ya); edge.get(8 + 6).add(R.drawable.result_jie); edge.get(8 + 6).add(R.drawable.result_yen); edge.get(8 + 3).add(8 * 2 + 2); edge.get(8 + 3).add(8 * 2 + 7); edge.get(8 * 2 + 2).add(R.drawable.result_yen); edge.get(8 * 2 + 2).add(R.drawable.result_jian); edge.get(8 * 2 + 7).add(R.drawable.result_yen); edge.get(8 * 2 + 7).add(R.drawable.result_nee); } private int currentState = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_ask); askQ = (ImageView) findViewById(R.id.ask_question); askYes = (ImageView) findViewById(R.id.ask_yes); askNo = (ImageView) findViewById(R.id.ask_no); animationFadeIn = AnimationUtils.loadAnimation(this, R.anim.fadein); animationFadeIn2 = AnimationUtils.loadAnimation(this, R.anim.fadein2); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } public void clickImage(View view) { Log.d("debug", "currentState:" + currentState); int state; if (view.getId() == R.id.ask_yes) { state = edge.get(currentState).get(0); } else { state = edge.get(currentState).get(1); } currentState = state; if (state < 8 * 3) { askQ.setImageResource(ask[state % 8][0]); askYes.setImageResource(ask[state % 8][1]); askNo.setImageResource(ask[state % 8][2]); askQ.startAnimation(animationFadeIn); askYes.startAnimation(animationFadeIn2); askNo.startAnimation(animationFadeIn2); } else { - SharedPreferences sp = getSharedPreferences("herbal", - Context.MODE_PRIVATE); - sp.edit().putInt("resId", currentState); - sp.edit().commit(); + SharedPreferences.Editor editor = getSharedPreferences("herbal", + Context.MODE_PRIVATE).edit(); + editor.putInt("resId", currentState); + editor.commit(); Intent intent = new Intent(); intent.setClass(this, ResultActivity.class); intent.putExtra("result", currentState); startActivity(intent); } } }
true
true
public void clickImage(View view) { Log.d("debug", "currentState:" + currentState); int state; if (view.getId() == R.id.ask_yes) { state = edge.get(currentState).get(0); } else { state = edge.get(currentState).get(1); } currentState = state; if (state < 8 * 3) { askQ.setImageResource(ask[state % 8][0]); askYes.setImageResource(ask[state % 8][1]); askNo.setImageResource(ask[state % 8][2]); askQ.startAnimation(animationFadeIn); askYes.startAnimation(animationFadeIn2); askNo.startAnimation(animationFadeIn2); } else { SharedPreferences sp = getSharedPreferences("herbal", Context.MODE_PRIVATE); sp.edit().putInt("resId", currentState); sp.edit().commit(); Intent intent = new Intent(); intent.setClass(this, ResultActivity.class); intent.putExtra("result", currentState); startActivity(intent); } }
public void clickImage(View view) { Log.d("debug", "currentState:" + currentState); int state; if (view.getId() == R.id.ask_yes) { state = edge.get(currentState).get(0); } else { state = edge.get(currentState).get(1); } currentState = state; if (state < 8 * 3) { askQ.setImageResource(ask[state % 8][0]); askYes.setImageResource(ask[state % 8][1]); askNo.setImageResource(ask[state % 8][2]); askQ.startAnimation(animationFadeIn); askYes.startAnimation(animationFadeIn2); askNo.startAnimation(animationFadeIn2); } else { SharedPreferences.Editor editor = getSharedPreferences("herbal", Context.MODE_PRIVATE).edit(); editor.putInt("resId", currentState); editor.commit(); Intent intent = new Intent(); intent.setClass(this, ResultActivity.class); intent.putExtra("result", currentState); startActivity(intent); } }