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/davmail/Settings.java b/src/java/davmail/Settings.java index 21e3f32..823477b 100644 --- a/src/java/davmail/Settings.java +++ b/src/java/davmail/Settings.java @@ -1,363 +1,363 @@ /* * DavMail POP/IMAP/SMTP/CalDav/LDAP Exchange Gateway * Copyright (C) 2009 Mickael Guessant * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package davmail; import davmail.ui.tray.DavGatewayTray; import java.util.Properties; import java.io.*; import org.apache.log4j.*; /** * Settings facade. * DavMail settings are stored in the .davmail.properties file in current * user home directory or in the file specified on the command line. */ public final class Settings { private Settings() { } private static final Properties SETTINGS = new Properties(); private static String configFilePath; private static boolean isFirstStart; /** * Set config file path (from command line parameter). * * @param path davmail properties file path */ public static synchronized void setConfigFilePath(String path) { configFilePath = path; } /** * Detect first launch (properties file does not exist). * * @return true if this is the first start with the current file path */ public static synchronized boolean isFirstStart() { return isFirstStart; } /** * Load properties from provided stream (used in webapp mode). * * @param inputStream properties stream * @throws IOException on error */ public static synchronized void load(InputStream inputStream) throws IOException { SETTINGS.load(inputStream); } /** * Load properties from current file path (command line or default). */ public static synchronized void load() { FileInputStream fileInputStream = null; try { if (configFilePath == null) { //noinspection AccessOfSystemProperties configFilePath = System.getProperty("user.home") + "/.davmail.properties"; } File configFile = new File(configFilePath); if (configFile.exists()) { fileInputStream = new FileInputStream(configFile); load(fileInputStream); } else { isFirstStart = true; // first start : set default values, ports above 1024 for unix/linux SETTINGS.put("davmail.url", "http://exchangeServer/exchange/"); SETTINGS.put("davmail.popPort", "1110"); SETTINGS.put("davmail.imapPort", "1143"); SETTINGS.put("davmail.smtpPort", "1025"); SETTINGS.put("davmail.caldavPort", "1080"); SETTINGS.put("davmail.ldapPort", "1389"); SETTINGS.put("davmail.keepDelay", "30"); SETTINGS.put("davmail.sentKeepDelay", "90"); SETTINGS.put("davmail.caldavPastDelay", "90"); SETTINGS.put("davmail.allowRemote", Boolean.FALSE.toString()); SETTINGS.put("davmail.bindAddress", ""); SETTINGS.put("davmail.enableProxy", Boolean.FALSE.toString()); SETTINGS.put("davmail.proxyHost", ""); SETTINGS.put("davmail.proxyPort", ""); SETTINGS.put("davmail.proxyUser", ""); SETTINGS.put("davmail.proxyPassword", ""); SETTINGS.put("davmail.server", Boolean.FALSE.toString()); SETTINGS.put("davmail.server.certificate.hash", ""); SETTINGS.put("davmail.ssl.keystoreType", ""); SETTINGS.put("davmail.ssl.keystoreFile", ""); SETTINGS.put("davmail.ssl.keystorePass", ""); SETTINGS.put("davmail.ssl.keyPass", ""); SETTINGS.put("davmail.ssl.pkcs11Library", ""); SETTINGS.put("davmail.ssl.pkcs11Config", ""); // logging SETTINGS.put("log4j.rootLogger", Level.WARN.toString()); SETTINGS.put("log4j.logger.davmail", Level.DEBUG.toString()); SETTINGS.put("log4j.logger.httpclient.wire", Level.WARN.toString()); SETTINGS.put("log4j.logger.org.apache.commons.httpclient", Level.WARN.toString()); - SETTINGS.put("log4j.logFilePath", ""); + SETTINGS.put("davmail.logFilePath", ""); save(); } } catch (IOException e) { DavGatewayTray.error(new BundleMessage("LOG_UNABLE_TO_LOAD_SETTINGS"), e); } finally { if (fileInputStream != null) { try { fileInputStream.close(); } catch (IOException e) { DavGatewayTray.debug(new BundleMessage("LOG_ERROR_CLOGING_CONFIG_FILE"), e); } } } updateLoggingConfig(); } /** * Return DavMail log file path * * @return full log file path */ public static String getLogFilePath() { String logFilePath = Settings.getProperty("davmail.logFilePath"); // use default log file path on Mac OS X if ((logFilePath == null || logFilePath.length() == 0) && System.getProperty("os.name").toLowerCase().startsWith("mac os x")) { logFilePath = System.getProperty("user.home") + "/Library/Logs/DavMail/davmail.log"; } return logFilePath; } /** * Return DavMail log file directory * * @return full log file directory */ public static String getLogFileDirectory() { String logFilePath = getLogFilePath(); if (logFilePath == null || logFilePath.length() == 0) { return ""; } int lastSlashIndex = logFilePath.lastIndexOf('/'); if (lastSlashIndex == -1) { lastSlashIndex = logFilePath.lastIndexOf('\\'); } if (lastSlashIndex >= 0) { return logFilePath.substring(0, lastSlashIndex); } else { return ""; } } /** * Update Log4J config from settings. */ private static void updateLoggingConfig() { String logFilePath = getLogFilePath(); Logger rootLogger = Logger.getRootLogger(); try { if (logFilePath != null && logFilePath.length() > 0) { File logFile = new File(logFilePath); // create parent directory if needed File logFileDir = logFile.getParentFile(); if (logFileDir != null && !logFileDir.exists()) { if (!logFileDir.mkdirs()) { DavGatewayTray.error(new BundleMessage("LOG_UNABLE_TO_CREATE_LOG_FILE_DIR")); throw new IOException(); } } } else { logFilePath = "davmail.log"; } // Build file appender RollingFileAppender fileAppender = ((RollingFileAppender) rootLogger.getAppender("FileAppender")); if (fileAppender == null) { fileAppender = new RollingFileAppender(); fileAppender.setName("FileAppender"); fileAppender.setMaxBackupIndex(2); fileAppender.setMaxFileSize("1MB"); fileAppender.setLayout(new PatternLayout("%d{ISO8601} %-5p [%t] %c %x - %m%n")); } fileAppender.setFile(logFilePath, true, false, 8192); rootLogger.addAppender(fileAppender); } catch (IOException e) { DavGatewayTray.error(new BundleMessage("LOG_UNABLE_TO_SET_LOG_FILE_PATH")); } // update logging levels Settings.setLoggingLevel("rootLogger", Settings.getLoggingLevel("rootLogger")); Settings.setLoggingLevel("davmail", Settings.getLoggingLevel("davmail")); Settings.setLoggingLevel("httpclient.wire", Settings.getLoggingLevel("httpclient.wire")); Settings.setLoggingLevel("org.apache.commons.httpclient", Settings.getLoggingLevel("org.apache.commons.httpclient")); } /** * Save settings in current file path (command line or default). */ public static synchronized void save() { FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(configFilePath); SETTINGS.store(fileOutputStream, "DavMail settings"); } catch (IOException e) { DavGatewayTray.error(new BundleMessage("LOG_UNABLE_TO_STORE_SETTINGS"), e); } finally { if (fileOutputStream != null) { try { fileOutputStream.close(); } catch (IOException e) { DavGatewayTray.debug(new BundleMessage("LOG_ERROR_CLOSING_CONFIG_FILE"), e); } } } updateLoggingConfig(); } /** * Get a property value as String. * * @param property property name * @return property value */ public static synchronized String getProperty(String property) { return SETTINGS.getProperty(property); } /** * Set a property value. * * @param property property name * @param value property value */ public static synchronized void setProperty(String property, String value) { if (value != null) { SETTINGS.setProperty(property, value); } else { SETTINGS.setProperty(property, ""); } } /** * Get a property value as int. * * @param property property name * @return property value */ public static synchronized int getIntProperty(String property) { return getIntProperty(property, 0); } /** * Get a property value as int, return default value if null. * * @param property property name * @param defaultValue default property value * @return property value */ public static synchronized int getIntProperty(String property, int defaultValue) { int value = defaultValue; try { String propertyValue = SETTINGS.getProperty(property); if (propertyValue != null && propertyValue.length() > 0) { value = Integer.parseInt(propertyValue); } } catch (NumberFormatException e) { DavGatewayTray.error(new BundleMessage("LOG_INVALID_SETTING_VALUE", property), e); } return value; } /** * Get a property value as boolean. * * @param property property name * @return property value */ public static synchronized boolean getBooleanProperty(String property) { String propertyValue = SETTINGS.getProperty(property); return Boolean.parseBoolean(propertyValue); } /** * Build logging properties prefix. * * @param category logging category * @return prefix */ private static String getLoggingPrefix(String category) { String prefix; if ("rootLogger".equals(category)) { prefix = "log4j."; } else { prefix = "log4j.logger."; } return prefix; } /** * Return Log4J logging level for the category. * * @param category logging category * @return logging level */ public static synchronized Level getLoggingLevel(String category) { String prefix = getLoggingPrefix(category); String currentValue = SETTINGS.getProperty(prefix + category); if (currentValue != null && currentValue.length() > 0) { return Level.toLevel(currentValue); } else if ("rootLogger".equals(category)) { return Logger.getRootLogger().getLevel(); } else { return Logger.getLogger(category).getLevel(); } } /** * Set Log4J logging level for the category * * @param category logging category * @param level logging level */ public static synchronized void setLoggingLevel(String category, Level level) { String prefix = getLoggingPrefix(category); SETTINGS.setProperty(prefix + category, level.toString()); if ("rootLogger".equals(category)) { Logger.getRootLogger().setLevel(level); } else { Logger.getLogger(category).setLevel(level); } } /** * Change and save a single property. * * @param property property name * @param value property value */ public static synchronized void saveProperty(String property, String value) { Settings.load(); Settings.setProperty(property, value); Settings.save(); } }
true
true
public static synchronized void load() { FileInputStream fileInputStream = null; try { if (configFilePath == null) { //noinspection AccessOfSystemProperties configFilePath = System.getProperty("user.home") + "/.davmail.properties"; } File configFile = new File(configFilePath); if (configFile.exists()) { fileInputStream = new FileInputStream(configFile); load(fileInputStream); } else { isFirstStart = true; // first start : set default values, ports above 1024 for unix/linux SETTINGS.put("davmail.url", "http://exchangeServer/exchange/"); SETTINGS.put("davmail.popPort", "1110"); SETTINGS.put("davmail.imapPort", "1143"); SETTINGS.put("davmail.smtpPort", "1025"); SETTINGS.put("davmail.caldavPort", "1080"); SETTINGS.put("davmail.ldapPort", "1389"); SETTINGS.put("davmail.keepDelay", "30"); SETTINGS.put("davmail.sentKeepDelay", "90"); SETTINGS.put("davmail.caldavPastDelay", "90"); SETTINGS.put("davmail.allowRemote", Boolean.FALSE.toString()); SETTINGS.put("davmail.bindAddress", ""); SETTINGS.put("davmail.enableProxy", Boolean.FALSE.toString()); SETTINGS.put("davmail.proxyHost", ""); SETTINGS.put("davmail.proxyPort", ""); SETTINGS.put("davmail.proxyUser", ""); SETTINGS.put("davmail.proxyPassword", ""); SETTINGS.put("davmail.server", Boolean.FALSE.toString()); SETTINGS.put("davmail.server.certificate.hash", ""); SETTINGS.put("davmail.ssl.keystoreType", ""); SETTINGS.put("davmail.ssl.keystoreFile", ""); SETTINGS.put("davmail.ssl.keystorePass", ""); SETTINGS.put("davmail.ssl.keyPass", ""); SETTINGS.put("davmail.ssl.pkcs11Library", ""); SETTINGS.put("davmail.ssl.pkcs11Config", ""); // logging SETTINGS.put("log4j.rootLogger", Level.WARN.toString()); SETTINGS.put("log4j.logger.davmail", Level.DEBUG.toString()); SETTINGS.put("log4j.logger.httpclient.wire", Level.WARN.toString()); SETTINGS.put("log4j.logger.org.apache.commons.httpclient", Level.WARN.toString()); SETTINGS.put("log4j.logFilePath", ""); save(); } } catch (IOException e) { DavGatewayTray.error(new BundleMessage("LOG_UNABLE_TO_LOAD_SETTINGS"), e); } finally { if (fileInputStream != null) { try { fileInputStream.close(); } catch (IOException e) { DavGatewayTray.debug(new BundleMessage("LOG_ERROR_CLOGING_CONFIG_FILE"), e); } } } updateLoggingConfig(); }
public static synchronized void load() { FileInputStream fileInputStream = null; try { if (configFilePath == null) { //noinspection AccessOfSystemProperties configFilePath = System.getProperty("user.home") + "/.davmail.properties"; } File configFile = new File(configFilePath); if (configFile.exists()) { fileInputStream = new FileInputStream(configFile); load(fileInputStream); } else { isFirstStart = true; // first start : set default values, ports above 1024 for unix/linux SETTINGS.put("davmail.url", "http://exchangeServer/exchange/"); SETTINGS.put("davmail.popPort", "1110"); SETTINGS.put("davmail.imapPort", "1143"); SETTINGS.put("davmail.smtpPort", "1025"); SETTINGS.put("davmail.caldavPort", "1080"); SETTINGS.put("davmail.ldapPort", "1389"); SETTINGS.put("davmail.keepDelay", "30"); SETTINGS.put("davmail.sentKeepDelay", "90"); SETTINGS.put("davmail.caldavPastDelay", "90"); SETTINGS.put("davmail.allowRemote", Boolean.FALSE.toString()); SETTINGS.put("davmail.bindAddress", ""); SETTINGS.put("davmail.enableProxy", Boolean.FALSE.toString()); SETTINGS.put("davmail.proxyHost", ""); SETTINGS.put("davmail.proxyPort", ""); SETTINGS.put("davmail.proxyUser", ""); SETTINGS.put("davmail.proxyPassword", ""); SETTINGS.put("davmail.server", Boolean.FALSE.toString()); SETTINGS.put("davmail.server.certificate.hash", ""); SETTINGS.put("davmail.ssl.keystoreType", ""); SETTINGS.put("davmail.ssl.keystoreFile", ""); SETTINGS.put("davmail.ssl.keystorePass", ""); SETTINGS.put("davmail.ssl.keyPass", ""); SETTINGS.put("davmail.ssl.pkcs11Library", ""); SETTINGS.put("davmail.ssl.pkcs11Config", ""); // logging SETTINGS.put("log4j.rootLogger", Level.WARN.toString()); SETTINGS.put("log4j.logger.davmail", Level.DEBUG.toString()); SETTINGS.put("log4j.logger.httpclient.wire", Level.WARN.toString()); SETTINGS.put("log4j.logger.org.apache.commons.httpclient", Level.WARN.toString()); SETTINGS.put("davmail.logFilePath", ""); save(); } } catch (IOException e) { DavGatewayTray.error(new BundleMessage("LOG_UNABLE_TO_LOAD_SETTINGS"), e); } finally { if (fileInputStream != null) { try { fileInputStream.close(); } catch (IOException e) { DavGatewayTray.debug(new BundleMessage("LOG_ERROR_CLOGING_CONFIG_FILE"), e); } } } updateLoggingConfig(); }
diff --git a/activemq-core/src/main/java/org/apache/activemq/broker/ft/MasterConnector.java b/activemq-core/src/main/java/org/apache/activemq/broker/ft/MasterConnector.java index 18cb96056..038b22292 100644 --- a/activemq-core/src/main/java/org/apache/activemq/broker/ft/MasterConnector.java +++ b/activemq-core/src/main/java/org/apache/activemq/broker/ft/MasterConnector.java @@ -1,369 +1,369 @@ /** * 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.activemq.broker.ft; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.activemq.Service; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.BrokerServiceAware; import org.apache.activemq.broker.TransportConnector; import org.apache.activemq.command.BrokerInfo; import org.apache.activemq.command.Command; import org.apache.activemq.command.CommandTypes; import org.apache.activemq.command.ConnectionId; import org.apache.activemq.command.ConnectionInfo; import org.apache.activemq.command.MessageDispatch; import org.apache.activemq.command.ProducerInfo; import org.apache.activemq.command.Response; import org.apache.activemq.command.SessionInfo; import org.apache.activemq.command.ShutdownInfo; import org.apache.activemq.transport.DefaultTransportListener; import org.apache.activemq.transport.Transport; import org.apache.activemq.transport.TransportDisposedIOException; import org.apache.activemq.transport.TransportFactory; import org.apache.activemq.util.IdGenerator; import org.apache.activemq.util.ServiceStopper; import org.apache.activemq.util.ServiceSupport; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Connects a Slave Broker to a Master when using <a * href="http://activemq.apache.org/masterslave.html">Master Slave</a> for High * Availability of messages. * * @org.apache.xbean.XBean * @version $Revision$ */ public class MasterConnector implements Service, BrokerServiceAware { private static final Log LOG = LogFactory.getLog(MasterConnector.class); private BrokerService broker; private URI remoteURI; private URI localURI; private Transport localBroker; private Transport remoteBroker; private TransportConnector connector; private AtomicBoolean started = new AtomicBoolean(false); private AtomicBoolean stoppedBeforeStart = new AtomicBoolean(false); private final IdGenerator idGenerator = new IdGenerator(); private String userName; private String password; private ConnectionInfo connectionInfo; private SessionInfo sessionInfo; private ProducerInfo producerInfo; private final AtomicBoolean masterActive = new AtomicBoolean(); private BrokerInfo brokerInfo; private boolean firstConnection=true; private boolean failedToStart; public MasterConnector() { } public MasterConnector(String remoteUri) throws URISyntaxException { remoteURI = new URI(remoteUri); } public void setBrokerService(BrokerService broker) { this.broker = broker; if (localURI == null) { localURI = broker.getVmConnectorURI(); } if (connector == null) { List transportConnectors = broker.getTransportConnectors(); if (!transportConnectors.isEmpty()) { connector = (TransportConnector)transportConnectors.get(0); } } } public boolean isSlave() { return masterActive.get(); } protected void restartBridge() throws Exception { localBroker.oneway(connectionInfo); remoteBroker.oneway(connectionInfo); localBroker.oneway(sessionInfo); remoteBroker.oneway(sessionInfo); remoteBroker.oneway(producerInfo); remoteBroker.oneway(brokerInfo); } public void start() throws Exception { if (!started.compareAndSet(false, true)) { return; } if (remoteURI == null) { throw new IllegalArgumentException("You must specify a remoteURI"); } localBroker = TransportFactory.connect(localURI); remoteBroker = TransportFactory.connect(remoteURI); LOG.info("Starting a slave connection between " + localBroker + " and " + remoteBroker); localBroker.setTransportListener(new DefaultTransportListener() { public void onCommand(Object command) { } public void onException(IOException error) { if (started.get()) { serviceLocalException(error); } } }); remoteBroker.setTransportListener(new DefaultTransportListener() { public void onCommand(Object o) { Command command = (Command)o; if (started.get()) { serviceRemoteCommand(command); } } public void onException(IOException error) { - if (started.get() && remoteBroker.isDisposed()) { + if (started.get()) { serviceRemoteException(error); } } public void transportResumed() { try{ if(!firstConnection){ localBroker = TransportFactory.connect(localURI); localBroker.setTransportListener(new DefaultTransportListener() { public void onCommand(Object command) { } public void onException(IOException error) { if (started.get()) { serviceLocalException(error); } } }); localBroker.start(); restartBridge(); LOG.info("Slave connection between " + localBroker + " and " + remoteBroker + " has been reestablished."); }else{ firstConnection=false; } }catch(IOException e){ LOG.error("MasterConnector failed to send BrokerInfo in transportResumed:", e); }catch(Exception e){ LOG.error("MasterConnector failed to restart localBroker in transportResumed:", e); } } }); try { localBroker.start(); remoteBroker.start(); startBridge(); masterActive.set(true); } catch (Exception e) { masterActive.set(false); if(!stoppedBeforeStart.get()){ LOG.error("Failed to start network bridge: " + e, e); }else{ LOG.info("Slave stopped before connected to the master."); } setFailedToStart(true); } } protected void startBridge() throws Exception { connectionInfo = new ConnectionInfo(); connectionInfo.setConnectionId(new ConnectionId(idGenerator.generateId())); connectionInfo.setClientId(idGenerator.generateId()); connectionInfo.setUserName(userName); connectionInfo.setPassword(password); connectionInfo.setBrokerMasterConnector(true); sessionInfo = new SessionInfo(connectionInfo, 1); producerInfo = new ProducerInfo(sessionInfo, 1); producerInfo.setResponseRequired(false); if (connector != null) { brokerInfo = connector.getBrokerInfo(); } else { brokerInfo = new BrokerInfo(); } brokerInfo.setBrokerName(broker.getBrokerName()); brokerInfo.setPeerBrokerInfos(broker.getBroker().getPeerBrokerInfos()); brokerInfo.setSlaveBroker(true); brokerInfo.setPassiveSlave(broker.isPassiveSlave()); restartBridge(); LOG.info("Slave connection between " + localBroker + " and " + remoteBroker + " has been established."); } public void stop() throws Exception { if (!started.compareAndSet(true, false)||!masterActive.get()) { return; } masterActive.set(false); try { // if (connectionInfo!=null){ // localBroker.request(connectionInfo.createRemoveCommand()); // } // localBroker.setTransportListener(null); // remoteBroker.setTransportListener(null); remoteBroker.oneway(new ShutdownInfo()); localBroker.oneway(new ShutdownInfo()); } catch (IOException e) { LOG.debug("Caught exception stopping", e); } finally { ServiceStopper ss = new ServiceStopper(); ss.stop(localBroker); ss.stop(remoteBroker); ss.throwFirstException(); } } public void stopBeforeConnected()throws Exception{ masterActive.set(false); started.set(false); stoppedBeforeStart.set(true); ServiceStopper ss = new ServiceStopper(); ss.stop(localBroker); ss.stop(remoteBroker); } protected void serviceRemoteException(IOException error) { LOG.error("Network connection between " + localBroker + " and " + remoteBroker + " shutdown: " + error.getMessage(), error); shutDown(); } protected void serviceRemoteCommand(Command command) { try { if (command.isMessageDispatch()) { MessageDispatch md = (MessageDispatch)command; command = md.getMessage(); } if (command.getDataStructureType() == CommandTypes.SHUTDOWN_INFO) { LOG.warn("The Master has shutdown"); shutDown(); } else { boolean responseRequired = command.isResponseRequired(); int commandId = command.getCommandId(); if (responseRequired) { Response response = (Response)localBroker.request(command); response.setCorrelationId(commandId); remoteBroker.oneway(response); } else { localBroker.oneway(command); } } } catch (IOException e) { serviceRemoteException(e); } } protected void serviceLocalException(Throwable error) { if (!(error instanceof TransportDisposedIOException) || localBroker.isDisposed()){ LOG.info("Network connection between " + localBroker + " and " + remoteBroker + " shutdown: " + error.getMessage(), error); ServiceSupport.dispose(this); }else{ LOG.info(error.getMessage()); } } /** * @return Returns the localURI. */ public URI getLocalURI() { return localURI; } /** * @param localURI The localURI to set. */ public void setLocalURI(URI localURI) { this.localURI = localURI; } /** * @return Returns the remoteURI. */ public URI getRemoteURI() { return remoteURI; } /** * @param remoteURI The remoteURI to set. */ public void setRemoteURI(URI remoteURI) { this.remoteURI = remoteURI; } /** * @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 userName. */ public String getUserName() { return userName; } /** * @param userName The userName to set. */ public void setUserName(String userName) { this.userName = userName; } private void shutDown() { masterActive.set(false); broker.masterFailed(); ServiceSupport.dispose(this); } public boolean isStoppedBeforeStart() { return stoppedBeforeStart.get(); } /** * Get the failedToStart * @return the failedToStart */ public boolean isFailedToStart() { return this.failedToStart; } /** * Set the failedToStart * @param failedToStart the failedToStart to set */ public void setFailedToStart(boolean failedToStart) { this.failedToStart = failedToStart; } }
true
true
public void start() throws Exception { if (!started.compareAndSet(false, true)) { return; } if (remoteURI == null) { throw new IllegalArgumentException("You must specify a remoteURI"); } localBroker = TransportFactory.connect(localURI); remoteBroker = TransportFactory.connect(remoteURI); LOG.info("Starting a slave connection between " + localBroker + " and " + remoteBroker); localBroker.setTransportListener(new DefaultTransportListener() { public void onCommand(Object command) { } public void onException(IOException error) { if (started.get()) { serviceLocalException(error); } } }); remoteBroker.setTransportListener(new DefaultTransportListener() { public void onCommand(Object o) { Command command = (Command)o; if (started.get()) { serviceRemoteCommand(command); } } public void onException(IOException error) { if (started.get() && remoteBroker.isDisposed()) { serviceRemoteException(error); } } public void transportResumed() { try{ if(!firstConnection){ localBroker = TransportFactory.connect(localURI); localBroker.setTransportListener(new DefaultTransportListener() { public void onCommand(Object command) { } public void onException(IOException error) { if (started.get()) { serviceLocalException(error); } } }); localBroker.start(); restartBridge(); LOG.info("Slave connection between " + localBroker + " and " + remoteBroker + " has been reestablished."); }else{ firstConnection=false; } }catch(IOException e){ LOG.error("MasterConnector failed to send BrokerInfo in transportResumed:", e); }catch(Exception e){ LOG.error("MasterConnector failed to restart localBroker in transportResumed:", e); } } }); try { localBroker.start(); remoteBroker.start(); startBridge(); masterActive.set(true); } catch (Exception e) { masterActive.set(false); if(!stoppedBeforeStart.get()){ LOG.error("Failed to start network bridge: " + e, e); }else{ LOG.info("Slave stopped before connected to the master."); } setFailedToStart(true); } }
public void start() throws Exception { if (!started.compareAndSet(false, true)) { return; } if (remoteURI == null) { throw new IllegalArgumentException("You must specify a remoteURI"); } localBroker = TransportFactory.connect(localURI); remoteBroker = TransportFactory.connect(remoteURI); LOG.info("Starting a slave connection between " + localBroker + " and " + remoteBroker); localBroker.setTransportListener(new DefaultTransportListener() { public void onCommand(Object command) { } public void onException(IOException error) { if (started.get()) { serviceLocalException(error); } } }); remoteBroker.setTransportListener(new DefaultTransportListener() { public void onCommand(Object o) { Command command = (Command)o; if (started.get()) { serviceRemoteCommand(command); } } public void onException(IOException error) { if (started.get()) { serviceRemoteException(error); } } public void transportResumed() { try{ if(!firstConnection){ localBroker = TransportFactory.connect(localURI); localBroker.setTransportListener(new DefaultTransportListener() { public void onCommand(Object command) { } public void onException(IOException error) { if (started.get()) { serviceLocalException(error); } } }); localBroker.start(); restartBridge(); LOG.info("Slave connection between " + localBroker + " and " + remoteBroker + " has been reestablished."); }else{ firstConnection=false; } }catch(IOException e){ LOG.error("MasterConnector failed to send BrokerInfo in transportResumed:", e); }catch(Exception e){ LOG.error("MasterConnector failed to restart localBroker in transportResumed:", e); } } }); try { localBroker.start(); remoteBroker.start(); startBridge(); masterActive.set(true); } catch (Exception e) { masterActive.set(false); if(!stoppedBeforeStart.get()){ LOG.error("Failed to start network bridge: " + e, e); }else{ LOG.info("Slave stopped before connected to the master."); } setFailedToStart(true); } }
diff --git a/src/graindcafe/tribu/TribuSpawner.java b/src/graindcafe/tribu/TribuSpawner.java index ebef449..ad03862 100644 --- a/src/graindcafe/tribu/TribuSpawner.java +++ b/src/graindcafe/tribu/TribuSpawner.java @@ -1,505 +1,506 @@ /******************************************************************************* * Copyright or � or Copr. Quentin Godron (2011) * * [email protected] * * This software is a computer program whose purpose is to create zombie * survival games on Bukkit's server. * * This software is governed by the CeCILL-C license under French law and * abiding by the rules of distribution of free software. You can use, * modify and/ or redistribute the software under the terms of the CeCILL-C * license as circulated by CEA, CNRS and INRIA at the following URL * "http://www.cecill.info". * * As a counterpart to the access to the source code and rights to copy, * modify and redistribute granted by the license, users are provided only * with a limited warranty and the software's author, the holder of the * economic rights, and the successive licensors have only limited * liability. * * In this respect, the user's attention is drawn to the risks associated * with loading, using, modifying and/or developing or reproducing the * software by the user in light of its specific status of free software, * that may mean that it is complicated to manipulate, and that also * therefore means that it is reserved for developers and experienced * professionals having in-depth computer knowledge. Users are therefore * encouraged to load and test the software's suitability as regards their * requirements in conditions enabling the security of their systems and/or * data to be ensured and, more generally, to use and operate it in the * same conditions as regards security. * * The fact that you are presently reading this means that you have had * knowledge of the CeCILL-C license and that you accept its terms. ******************************************************************************/ package graindcafe.tribu; import graindcafe.tribu.Configuration.Constants; import graindcafe.tribu.Configuration.FocusType; import graindcafe.tribu.TribuZombie.CannotSpawnException; import graindcafe.tribu.TribuZombie.CraftTribuZombie; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Stack; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.craftbukkit.v1_6_R2.entity.CraftLivingEntity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; public class TribuSpawner { /** * Is the round finish */ private boolean finished; /** * Health of zombie to spawn */ private float health; /** * number of zombies to spawn */ private int totalToSpawn; /** * Tribu */ private final Tribu plugin; /** * Gonna start */ private boolean starting; /** * spawned zombies */ private int alreadySpawned; /** * planified spawns */ private int pendingSpawn; /** * Referenced zombies */ private final LinkedList<CraftTribuZombie> zombies; private final HashMap<Runnable, Integer> runnerTaskIds; /** * Init the spawner * * @param instance * of Tribu */ public TribuSpawner(final Tribu instance) { plugin = instance; alreadySpawned = 0; pendingSpawn = 0; totalToSpawn = 5; finished = false; starting = true; health = 10; zombies = new LinkedList<CraftTribuZombie>(); runnerTaskIds = new HashMap<Runnable, Integer>(); } /** * Check that all referenced zombies are alive Useful to check if a zombie * has been despawned (too far away, killed but not caught) set finished if * they are all dead */ public void checkZombies() { final Stack<CraftTribuZombie> toDelete = new Stack<CraftTribuZombie>(); for (final CraftTribuZombie e : zombies) if (e == null || e.isDead()) toDelete.push(e); finished = toDelete.isEmpty(); while (!toDelete.isEmpty()) removedZombieCallback(toDelete.pop(), false); } /** * Delete all zombies and prevent the spawner to continue spawning */ public void clearZombies() { for (final CraftTribuZombie zombie : zombies) zombie.remove(); resetTotal(); zombies.clear(); } /** * Despawn a killed zombie * * @param zombie * zombie to unreference * @param drops * drops to clear */ public void despawnZombie(final CraftTribuZombie zombie, final List<ItemStack> drops) { if (zombies.remove(zombie)) { drops.clear(); tryStartNextWave(); } // Else The zombie may have been deleted by "removedZombieCallback" /* * else { * * plugin.LogWarning("Unreferenced zombie despawned"); } */ } /** * Set that it's finish */ public void finishCallback() { finished = true; } // Debug command /** * This is a debug command returning the location of a living zombie It * prints info of this zombie on the console or a severe error * * @return location of a living zombie */ public Location getFirstZombieLocation() { if (alreadySpawned > 0) if (!zombies.isEmpty()) { int i = plugin.getRandom().nextInt(zombies.size()); plugin.LogInfo("Health : " + zombies.get(i).getHealth()); plugin.LogInfo("LastDamage : " + zombies.get(i).getLastDamage()); plugin.LogInfo("isDead : " + zombies.get(i).isDead()); plugin.LogInfo("There is " + zombies.size() + " zombie alive of " + alreadySpawned + "/" + totalToSpawn + " spawned +" + pendingSpawn + " pending spawn. The wave is " + (finished ? "finished" : "in progress")); return zombies.get(i).getLocation(); } else { plugin.getSpawnTimer().getState(); plugin.LogInfo("There is " + zombies.size() + " zombie alive of " + alreadySpawned + "/" + totalToSpawn + " spawned +" + pendingSpawn + " pending spawn. The wave is " + (finished ? "finished" : "in progress")); return null; } else return null; } /** * Get the total quantity of zombie to spawn (Not counting zombies killed) * * @return total to spawn */ public int getMaxSpawn() { return totalToSpawn; } /** * Get the number of zombie already spawned * * @return number of zombie already spawned */ public int getTotal() { return alreadySpawned; } /** * Get the first spawn in a loaded chunk * * @return */ public Location getValidSpawn() { for (final Location curPos : plugin.getLevel().getActiveSpawns()) if (curPos.getWorld().isChunkLoaded( curPos.getWorld().getChunkAt(curPos))) return curPos; plugin.LogInfo(plugin.getLocale("Warning.AllSpawnsCurrentlyUnloaded")); return null; } /** * If the spawner should continue spawning * * @return */ public boolean haveZombieToSpawn() { return alreadySpawned < totalToSpawn; } /** * Check if the living entity is referenced here * * @param ent * @return if the living entity was spawned by this */ public boolean isSpawned(final LivingEntity ent) { return zombies.contains(ent); } /** * The wave is completed if there is no zombie to spawn and zombies spawned * are dead * * @return is wave completed */ public boolean isWaveCompleted() { return !haveZombieToSpawn() && zombies.isEmpty(); } public static Location generatePointBetween(Location loc1, Location loc2, int distanceFromLoc1) { if (distanceFromLoc1 * distanceFromLoc1 > loc1.distanceSquared(loc2)) return loc2; double x = loc1.getX(); Double y = loc1.getY(); double z = loc1.getZ(); Double y1Param; Double x1Param; Double y2Param; Double x2Param; if (x > z) { y1Param = z; x1Param = x; y2Param = loc2.getZ(); x2Param = loc2.getX(); } else { y1Param = x; x1Param = z; y2Param = loc2.getX(); x2Param = loc2.getZ(); } double dY = y2Param - y1Param; double dX = x2Param - x1Param; double a = dY / dX; // double b = a * x1Param - y1Param; double rDx = (dX < 0 ? -1 : 1) * Math.sqrt(distanceFromLoc1 * distanceFromLoc1 / (1 + a * a)); y1Param += a * rDx; x1Param += rDx; if (x > z) { z = y1Param; x = x1Param; } else { x = y1Param; z = x1Param; } y = findSuitableY(loc1.getWorld(), x, y, z); if (y == null) return null; return new Location(loc1.getWorld(), x, y, z); } static Double findSuitableY(Location loc) { return findSuitableY(loc.getWorld(), loc.getX(), loc.getY(), loc.getZ()); } static Double findSuitableY(World w, double x, double y, double z) { double newY = Math.floor(y); double step = 0.5; double sign = -1; boolean failed = false; while (!w.getBlockAt((int) Math.floor(x), (int) Math.floor(y), (int) Math.floor(z)).isEmpty()) { newY = y + (step * sign); sign *= -1; step++; if (step >= 256) { failed = true; break; } } if (failed) return null; return newY; } /** * Kill & unreference a zombie * * @param e * Zombie to despawn * @param removeReward * Reward attackers ? */ public void removedZombieCallback(final CraftTribuZombie e, final boolean removeReward) { if (e != null) { if (removeReward) e.setNoAttacker(); e.remove(); } zombies.remove(e); alreadySpawned--; if (plugin.config().ZombiesFocus == FocusType.NearestPlayer - || plugin.config().ZombiesFocus == FocusType.RandomPlayer) { + || plugin.config().ZombiesFocus == FocusType.RandomPlayer + && e.getTarget() != null) { pendingSpawn++; Runnable runner = new Runnable() { boolean done = false; double traveled = 0; double step = 20 * e.getHandle().getSpeed(); final Location initLoc = e.getLocation().clone(); final CraftLivingEntity target = e.getTarget(); final double distanceToPlayer = 50; public void run() { traveled += step; if (!done && (target == null || target.getLocation() .distanceSquared(initLoc) <= ((distanceToPlayer + traveled) * (distanceToPlayer + traveled)))) { done = true; if (target != null) { Location newLoc = generatePointBetween( target.getLocation(), initLoc, 50); pendingSpawn--; if (newLoc != null) { try { CraftTribuZombie zomb; zomb = (CraftTribuZombie) CraftTribuZombie .spawn(plugin, newLoc); alreadySpawned++; zomb.setTarget(target); zombies.add(zomb); } catch (CannotSpawnException e) { } } } Bukkit.getScheduler().cancelTask( runnerTaskIds.remove(this)); } } }; int taskId = plugin .getServer() .getScheduler() .scheduleSyncRepeatingTask(plugin, runner, 5, Constants.TicksBySecond); runnerTaskIds.put(runner, taskId); } } /** * Prevent spawner to continue spawning but do not set it as finished */ public void resetTotal() { pendingSpawn = 0; alreadySpawned = 0; finished = false; } /** * Set health of zombie to spawn * * @param health * Health */ public void setHealth(final float health) { this.health = health; } /** * Set the number of zombie to spawn * * @param count */ public void setMaxSpawn(final int count) { totalToSpawn = count; } /** * Try to spawn a zombie * * @return if zombies still have to spawn (before spawning it) */ public boolean spawnZombie() { if ((pendingSpawn + alreadySpawned) < totalToSpawn && !finished) { Location pos = plugin.getLevel().getRandomZombieSpawn(); if (pos != null) { if (!pos.getWorld().isChunkLoaded( pos.getWorld().getChunkAt(pos))) { checkZombies(); pos = getValidSpawn(); } if (pos != null) { CraftTribuZombie zombie; try { Double y = findSuitableY(pos); if (y != null) pos.setY(y); zombie = (CraftTribuZombie) CraftTribuZombie.spawn( plugin, pos); zombies.add(zombie); zombie.setHealth(health); alreadySpawned++; } catch (final CannotSpawnException e) { // Impossible to spawn the zombie, maybe because of lack // of // space } } } } else return false; return true; } /** * Set that the spawner has started */ public void startingCallback() { starting = false; } /** * * @return true if the wave has already started */ public boolean hasStarted() { return !starting; } /** * * @return true if the wave didn't start yet */ public boolean isStarting() { return starting; } /** * Try to start the next wave if possible and return if it's starting * * @return */ public boolean tryStartNextWave() { if (zombies.isEmpty() && finished && !starting) { starting = true; plugin.messagePlayers(plugin.getLocale("Broadcast.WaveComplete")); plugin.getWaveStarter().incrementWave(); plugin.getWaveStarter().scheduleWave( Constants.TicksBySecond * plugin.config().WaveStartDelay); } return starting; } public void removeTarget(Player p) { for (CraftTribuZombie z : zombies) { if (z.getTarget().equals(p)) z.setTarget(null); } } }
true
true
public void removedZombieCallback(final CraftTribuZombie e, final boolean removeReward) { if (e != null) { if (removeReward) e.setNoAttacker(); e.remove(); } zombies.remove(e); alreadySpawned--; if (plugin.config().ZombiesFocus == FocusType.NearestPlayer || plugin.config().ZombiesFocus == FocusType.RandomPlayer) { pendingSpawn++; Runnable runner = new Runnable() { boolean done = false; double traveled = 0; double step = 20 * e.getHandle().getSpeed(); final Location initLoc = e.getLocation().clone(); final CraftLivingEntity target = e.getTarget(); final double distanceToPlayer = 50; public void run() { traveled += step; if (!done && (target == null || target.getLocation() .distanceSquared(initLoc) <= ((distanceToPlayer + traveled) * (distanceToPlayer + traveled)))) { done = true; if (target != null) { Location newLoc = generatePointBetween( target.getLocation(), initLoc, 50); pendingSpawn--; if (newLoc != null) { try { CraftTribuZombie zomb; zomb = (CraftTribuZombie) CraftTribuZombie .spawn(plugin, newLoc); alreadySpawned++; zomb.setTarget(target); zombies.add(zomb); } catch (CannotSpawnException e) { } } } Bukkit.getScheduler().cancelTask( runnerTaskIds.remove(this)); } } }; int taskId = plugin .getServer() .getScheduler() .scheduleSyncRepeatingTask(plugin, runner, 5, Constants.TicksBySecond); runnerTaskIds.put(runner, taskId); } }
public void removedZombieCallback(final CraftTribuZombie e, final boolean removeReward) { if (e != null) { if (removeReward) e.setNoAttacker(); e.remove(); } zombies.remove(e); alreadySpawned--; if (plugin.config().ZombiesFocus == FocusType.NearestPlayer || plugin.config().ZombiesFocus == FocusType.RandomPlayer && e.getTarget() != null) { pendingSpawn++; Runnable runner = new Runnable() { boolean done = false; double traveled = 0; double step = 20 * e.getHandle().getSpeed(); final Location initLoc = e.getLocation().clone(); final CraftLivingEntity target = e.getTarget(); final double distanceToPlayer = 50; public void run() { traveled += step; if (!done && (target == null || target.getLocation() .distanceSquared(initLoc) <= ((distanceToPlayer + traveled) * (distanceToPlayer + traveled)))) { done = true; if (target != null) { Location newLoc = generatePointBetween( target.getLocation(), initLoc, 50); pendingSpawn--; if (newLoc != null) { try { CraftTribuZombie zomb; zomb = (CraftTribuZombie) CraftTribuZombie .spawn(plugin, newLoc); alreadySpawned++; zomb.setTarget(target); zombies.add(zomb); } catch (CannotSpawnException e) { } } } Bukkit.getScheduler().cancelTask( runnerTaskIds.remove(this)); } } }; int taskId = plugin .getServer() .getScheduler() .scheduleSyncRepeatingTask(plugin, runner, 5, Constants.TicksBySecond); runnerTaskIds.put(runner, taskId); } }
diff --git a/app/src/processing/app/Editor.java b/app/src/processing/app/Editor.java index 4fc2d13c..774d20f7 100644 --- a/app/src/processing/app/Editor.java +++ b/app/src/processing/app/Editor.java @@ -1,2802 +1,2802 @@ /* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* Part of the Processing project - http://processing.org Copyright (c) 2004-09 Ben Fry and Casey Reas Copyright (c) 2001-04 Massachusetts Institute of Technology This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 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 processing.app; import processing.app.debug.*; import processing.app.syntax.*; import processing.app.tools.*; import processing.core.*; import static processing.app.I18n._; import java.awt.*; import java.awt.datatransfer.*; import java.awt.event.*; import java.awt.print.*; import java.io.*; import java.net.*; import java.util.*; import java.util.zip.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.text.*; import javax.swing.undo.*; import gnu.io.*; /** * Main editor panel for the Processing Development Environment. */ @SuppressWarnings("serial") public class Editor extends JFrame implements RunnerListener { Base base; // otherwise, if the window is resized with the message label // set to blank, it's preferredSize() will be fukered static protected final String EMPTY = " " + " " + " "; /** Command on Mac OS X, Ctrl on Windows and Linux */ static final int SHORTCUT_KEY_MASK = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); /** Command-W on Mac OS X, Ctrl-W on Windows and Linux */ static final KeyStroke WINDOW_CLOSE_KEYSTROKE = KeyStroke.getKeyStroke('W', SHORTCUT_KEY_MASK); /** Command-Option on Mac OS X, Ctrl-Alt on Windows and Linux */ static final int SHORTCUT_ALT_KEY_MASK = ActionEvent.ALT_MASK | Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); /** * true if this file has not yet been given a name by the user */ boolean untitled; PageFormat pageFormat; PrinterJob printerJob; // file, sketch, and tools menus for re-inserting items JMenu fileMenu; JMenu sketchMenu; JMenu toolsMenu; int numTools = 0; EditorToolbar toolbar; // these menus are shared so that they needn't be rebuilt for all windows // each time a sketch is created, renamed, or moved. static JMenu toolbarMenu; static JMenu sketchbookMenu; static JMenu examplesMenu; static JMenu importMenu; // these menus are shared so that the board and serial port selections // are the same for all windows (since the board and serial port that are // actually used are determined by the preferences, which are shared) static JMenu boardsMenu; static JMenu serialMenu; static SerialMenuListener serialMenuListener; static SerialMonitor serialMonitor; EditorHeader header; EditorStatus status; EditorConsole console; JSplitPane splitPane; JPanel consolePanel; JLabel lineNumberComponent; // currently opened program Sketch sketch; EditorLineStatus lineStatus; //JEditorPane editorPane; JEditTextArea textarea; EditorListener listener; // runtime information and window placement Point sketchWindowLocation; //Runner runtime; JMenuItem exportAppItem; JMenuItem saveMenuItem; JMenuItem saveAsMenuItem; boolean running; //boolean presenting; boolean uploading; // undo fellers JMenuItem undoItem, redoItem; protected UndoAction undoAction; protected RedoAction redoAction; UndoManager undo; // used internally, and only briefly CompoundEdit compoundEdit; FindReplace find; Runnable runHandler; Runnable presentHandler; Runnable stopHandler; Runnable exportHandler; Runnable exportAppHandler; public Editor(Base ibase, String path, int[] location) { super("Arduino"); this.base = ibase; Base.setIcon(this); // Install default actions for Run, Present, etc. resetHandlers(); // add listener to handle window close box hit event addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { base.handleClose(Editor.this); } }); // don't close the window when clicked, the app will take care // of that via the handleQuitInternal() methods // http://dev.processing.org/bugs/show_bug.cgi?id=440 setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); // When bringing a window to front, let the Base know addWindowListener(new WindowAdapter() { public void windowActivated(WindowEvent e) { // System.err.println("activate"); // not coming through base.handleActivated(Editor.this); // re-add the sub-menus that are shared by all windows fileMenu.insert(sketchbookMenu, 2); fileMenu.insert(examplesMenu, 3); - //sketchMenu.insert(importMenu, 4); + sketchMenu.insert(importMenu, 4); toolsMenu.insert(boardsMenu, numTools); toolsMenu.insert(serialMenu, numTools + 1); } // added for 1.0.5 // http://dev.processing.org/bugs/show_bug.cgi?id=1260 public void windowDeactivated(WindowEvent e) { // System.err.println("deactivate"); // not coming through fileMenu.remove(sketchbookMenu); fileMenu.remove(examplesMenu); - //sketchMenu.remove(importMenu); + sketchMenu.remove(importMenu); toolsMenu.remove(boardsMenu); toolsMenu.remove(serialMenu); } }); //PdeKeywords keywords = new PdeKeywords(); //sketchbook = new Sketchbook(this); if (serialMonitor == null) { serialMonitor = new SerialMonitor(Preferences.get("serial.port")); serialMonitor.setIconImage(getIconImage()); } buildMenuBar(); // For rev 0120, placing things inside a JPanel Container contentPain = getContentPane(); contentPain.setLayout(new BorderLayout()); JPanel pain = new JPanel(); pain.setLayout(new BorderLayout()); contentPain.add(pain, BorderLayout.CENTER); Box box = Box.createVerticalBox(); Box upper = Box.createVerticalBox(); if (toolbarMenu == null) { toolbarMenu = new JMenu(); base.rebuildToolbarMenu(toolbarMenu); } toolbar = new EditorToolbar(this, toolbarMenu); upper.add(toolbar); header = new EditorHeader(this); upper.add(header); textarea = new JEditTextArea(new PdeTextAreaDefaults()); textarea.setRightClickPopup(new TextAreaPopup()); textarea.setHorizontalOffset(6); // assemble console panel, consisting of status area and the console itself consolePanel = new JPanel(); consolePanel.setLayout(new BorderLayout()); status = new EditorStatus(this); consolePanel.add(status, BorderLayout.NORTH); console = new EditorConsole(this); // windows puts an ugly border on this guy console.setBorder(null); consolePanel.add(console, BorderLayout.CENTER); lineStatus = new EditorLineStatus(textarea); consolePanel.add(lineStatus, BorderLayout.SOUTH); upper.add(textarea); splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, upper, consolePanel); splitPane.setOneTouchExpandable(true); // repaint child panes while resizing splitPane.setContinuousLayout(true); // if window increases in size, give all of increase to // the textarea in the uppper pane splitPane.setResizeWeight(1D); // to fix ugliness.. normally macosx java 1.3 puts an // ugly white border around this object, so turn it off. splitPane.setBorder(null); // the default size on windows is too small and kinda ugly int dividerSize = Preferences.getInteger("editor.divider.size"); if (dividerSize != 0) { splitPane.setDividerSize(dividerSize); } // the following changed from 600, 400 for netbooks // http://code.google.com/p/arduino/issues/detail?id=52 splitPane.setMinimumSize(new Dimension(600, 100)); box.add(splitPane); // hopefully these are no longer needed w/ swing // (har har har.. that was wishful thinking) listener = new EditorListener(this, textarea); pain.add(box); // get shift down/up events so we can show the alt version of toolbar buttons textarea.addKeyListener(toolbar); pain.setTransferHandler(new FileDropHandler()); // System.out.println("t1"); // Finish preparing Editor (formerly found in Base) pack(); // System.out.println("t2"); // Set the window bounds and the divider location before setting it visible setPlacement(location); // Set the minimum size for the editor window setMinimumSize(new Dimension(Preferences.getInteger("editor.window.width.min"), Preferences.getInteger("editor.window.height.min"))); // System.out.println("t3"); // Bring back the general options for the editor applyPreferences(); // System.out.println("t4"); // Open the document that was passed in boolean loaded = handleOpenInternal(path); if (!loaded) sketch = null; // System.out.println("t5"); // All set, now show the window //setVisible(true); } /** * Handles files dragged & dropped from the desktop and into the editor * window. Dragging files into the editor window is the same as using * "Sketch &rarr; Add File" for each file. */ class FileDropHandler extends TransferHandler { public boolean canImport(JComponent dest, DataFlavor[] flavors) { return true; } @SuppressWarnings("unchecked") public boolean importData(JComponent src, Transferable transferable) { int successful = 0; try { DataFlavor uriListFlavor = new DataFlavor("text/uri-list;class=java.lang.String"); if (transferable.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { java.util.List list = (java.util.List) transferable.getTransferData(DataFlavor.javaFileListFlavor); for (int i = 0; i < list.size(); i++) { File file = (File) list.get(i); if (sketch.addFile(file)) { successful++; } } } else if (transferable.isDataFlavorSupported(uriListFlavor)) { // Some platforms (Mac OS X and Linux, when this began) preferred // this method of moving files. String data = (String)transferable.getTransferData(uriListFlavor); String[] pieces = PApplet.splitTokens(data, "\r\n"); for (int i = 0; i < pieces.length; i++) { if (pieces[i].startsWith("#")) continue; String path = null; if (pieces[i].startsWith("file:///")) { path = pieces[i].substring(7); } else if (pieces[i].startsWith("file:/")) { path = pieces[i].substring(5); } if (sketch.addFile(new File(path))) { successful++; } } } } catch (Exception e) { e.printStackTrace(); return false; } if (successful == 0) { statusError(_("No files were added to the sketch.")); } else if (successful == 1) { statusNotice(_("One file added to the sketch.")); } else { statusNotice( I18n.format(_("{0} files added to the sketch."), successful)); } return true; } } protected void setPlacement(int[] location) { setBounds(location[0], location[1], location[2], location[3]); if (location[4] != 0) { splitPane.setDividerLocation(location[4]); } } protected int[] getPlacement() { int[] location = new int[5]; // Get the dimensions of the Frame Rectangle bounds = getBounds(); location[0] = bounds.x; location[1] = bounds.y; location[2] = bounds.width; location[3] = bounds.height; // Get the current placement of the divider location[4] = splitPane.getDividerLocation(); return location; } /** * Hack for #@#)$(* Mac OS X 10.2. * <p/> * This appears to only be required on OS X 10.2, and is not * even being called on later versions of OS X or Windows. */ // public Dimension getMinimumSize() { // //System.out.println("getting minimum size"); // return new Dimension(500, 550); // } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /** * Read and apply new values from the preferences, either because * the app is just starting up, or the user just finished messing * with things in the Preferences window. */ protected void applyPreferences() { // apply the setting for 'use external editor' boolean external = Preferences.getBoolean("editor.external"); textarea.setEditable(!external); saveMenuItem.setEnabled(!external); saveAsMenuItem.setEnabled(!external); TextAreaPainter painter = textarea.getPainter(); if (external) { // disable line highlight and turn off the caret when disabling Color color = Theme.getColor("editor.external.bgcolor"); painter.setBackground(color); painter.setLineHighlightEnabled(false); textarea.setCaretVisible(false); } else { Color color = Theme.getColor("editor.bgcolor"); painter.setBackground(color); boolean highlight = Preferences.getBoolean("editor.linehighlight"); painter.setLineHighlightEnabled(highlight); textarea.setCaretVisible(true); } // apply changes to the font size for the editor //TextAreaPainter painter = textarea.getPainter(); painter.setFont(Preferences.getFont("editor.font")); //Font font = painter.getFont(); //textarea.getPainter().setFont(new Font("Courier", Font.PLAIN, 36)); // in case tab expansion stuff has changed listener.applyPreferences(); // in case moved to a new location // For 0125, changing to async version (to be implemented later) //sketchbook.rebuildMenus(); // For 0126, moved into Base, which will notify all editors. //base.rebuildMenusAsync(); } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . protected void buildMenuBar() { JMenuBar menubar = new JMenuBar(); menubar = new JMenuBar(); menubar.add(buildFileMenu()); menubar.add(buildEditMenu()); menubar.add(buildSketchMenu()); menubar.add(buildToolsMenu()); menubar.add(buildHelpMenu()); setJMenuBar(menubar); } protected JMenu buildFileMenu() { JMenuItem item; fileMenu = new JMenu(_("File")); item = newJMenuItem(_("New"), 'N'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { base.handleNew(); } }); fileMenu.add(item); item = Editor.newJMenuItem(_("Open..."), 'O'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { base.handleOpenPrompt(); } }); fileMenu.add(item); if (sketchbookMenu == null) { sketchbookMenu = new JMenu(_("Sketchbook")); base.rebuildSketchbookMenu(sketchbookMenu); } fileMenu.add(sketchbookMenu); if (examplesMenu == null) { examplesMenu = new JMenu(_("Examples")); base.rebuildExamplesMenu(examplesMenu); } fileMenu.add(examplesMenu); item = Editor.newJMenuItem(_("Close"), 'W'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { base.handleClose(Editor.this); } }); fileMenu.add(item); saveMenuItem = newJMenuItem(_("Save"), 'S'); saveMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleSave(false); } }); fileMenu.add(saveMenuItem); saveAsMenuItem = newJMenuItemShift(_("Save As..."), 'S'); saveAsMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleSaveAs(); } }); fileMenu.add(saveAsMenuItem); item = newJMenuItem(_("Upload"), 'U'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleExport(false); } }); fileMenu.add(item); item = newJMenuItemShift(_("Upload Using Programmer"), 'U'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleExport(true); } }); fileMenu.add(item); fileMenu.addSeparator(); item = newJMenuItemShift(_("Page Setup"), 'P'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handlePageSetup(); } }); fileMenu.add(item); item = newJMenuItem(_("Print"), 'P'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handlePrint(); } }); fileMenu.add(item); // macosx already has its own preferences and quit menu if (!Base.isMacOS()) { fileMenu.addSeparator(); item = newJMenuItem(_("Preferences"), ','); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { base.handlePrefs(); } }); fileMenu.add(item); fileMenu.addSeparator(); item = newJMenuItem(_("Quit"), 'Q'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { base.handleQuit(); } }); fileMenu.add(item); } return fileMenu; } protected JMenu buildSketchMenu() { JMenuItem item; sketchMenu = new JMenu(_("Sketch")); item = newJMenuItem(_("Verify / Compile"), 'R'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleRun(false); } }); sketchMenu.add(item); // item = newJMenuItemShift("Verify / Compile (verbose)", 'R'); // item.addActionListener(new ActionListener() { // public void actionPerformed(ActionEvent e) { // handleRun(true); // } // }); // sketchMenu.add(item); // item = new JMenuItem("Stop"); // item.addActionListener(new ActionListener() { // public void actionPerformed(ActionEvent e) { // handleStop(); // } // }); // sketchMenu.add(item); sketchMenu.addSeparator(); if (importMenu == null) { importMenu = new JMenu(_("Import Library...")); base.rebuildImportMenu(importMenu, this); } sketchMenu.add(importMenu); item = newJMenuItem(_("Show Sketch Folder"), 'K'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.openFolder(sketch.getFolder()); } }); sketchMenu.add(item); item.setEnabled(Base.openFolderAvailable()); item = new JMenuItem(_("Add File...")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { sketch.handleAddFile(); } }); sketchMenu.add(item); return sketchMenu; } protected JMenu buildToolsMenu() { toolsMenu = new JMenu(_("Tools")); JMenu menu = toolsMenu; JMenuItem item; addInternalTools(menu); item = newJMenuItemShift(_("Serial Monitor"), 'M'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleSerial(); } }); menu.add(item); addTools(menu, Base.getToolsFolder()); File sketchbookTools = new File(Base.getSketchbookFolder(), "tools"); addTools(menu, sketchbookTools); menu.addSeparator(); numTools = menu.getItemCount(); // XXX: DAM: these should probably be implemented using the Tools plugin // API, if possible (i.e. if it supports custom actions, etc.) if (boardsMenu == null) { boardsMenu = new JMenu(_("Board")); base.rebuildBoardsMenu(boardsMenu, this); } menu.add(boardsMenu); if (serialMenuListener == null) serialMenuListener = new SerialMenuListener(); if (serialMenu == null) serialMenu = new JMenu(_("Serial Port")); populateSerialMenu(); menu.add(serialMenu); menu.addSeparator(); JMenu programmerMenu = new JMenu(_("Programmer")); base.rebuildProgrammerMenu(programmerMenu); menu.add(programmerMenu); item = new JMenuItem(_("Burn Bootloader")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleBurnBootloader(); } }); menu.add(item); menu.addMenuListener(new MenuListener() { public void menuCanceled(MenuEvent e) {} public void menuDeselected(MenuEvent e) {} public void menuSelected(MenuEvent e) { //System.out.println("Tools menu selected."); populateSerialMenu(); } }); return menu; } protected void addTools(JMenu menu, File sourceFolder) { HashMap<String, JMenuItem> toolItems = new HashMap<String, JMenuItem>(); File[] folders = sourceFolder.listFiles(new FileFilter() { public boolean accept(File folder) { if (folder.isDirectory()) { //System.out.println("checking " + folder); File subfolder = new File(folder, "tool"); return subfolder.exists(); } return false; } }); if (folders == null || folders.length == 0) { return; } for (int i = 0; i < folders.length; i++) { File toolDirectory = new File(folders[i], "tool"); try { // add dir to classpath for .classes //urlList.add(toolDirectory.toURL()); // add .jar files to classpath File[] archives = toolDirectory.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return (name.toLowerCase().endsWith(".jar") || name.toLowerCase().endsWith(".zip")); } }); URL[] urlList = new URL[archives.length]; for (int j = 0; j < urlList.length; j++) { urlList[j] = archives[j].toURI().toURL(); } URLClassLoader loader = new URLClassLoader(urlList); String className = null; for (int j = 0; j < archives.length; j++) { className = findClassInZipFile(folders[i].getName(), archives[j]); if (className != null) break; } /* // Alternatively, could use manifest files with special attributes: // http://java.sun.com/j2se/1.3/docs/guide/jar/jar.html // Example code for loading from a manifest file: // http://forums.sun.com/thread.jspa?messageID=3791501 File infoFile = new File(toolDirectory, "tool.txt"); if (!infoFile.exists()) continue; String[] info = PApplet.loadStrings(infoFile); //Main-Class: org.poo.shoe.AwesomerTool //String className = folders[i].getName(); String className = null; for (int k = 0; k < info.length; k++) { if (info[k].startsWith(";")) continue; String[] pieces = PApplet.splitTokens(info[k], ": "); if (pieces.length == 2) { if (pieces[0].equals("Main-Class")) { className = pieces[1]; } } } */ // If no class name found, just move on. if (className == null) continue; Class<?> toolClass = Class.forName(className, true, loader); final Tool tool = (Tool) toolClass.newInstance(); tool.init(Editor.this); String title = tool.getMenuTitle(); JMenuItem item = new JMenuItem(title); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { SwingUtilities.invokeLater(tool); //new Thread(tool).start(); } }); //menu.add(item); toolItems.put(title, item); } catch (Exception e) { e.printStackTrace(); } } ArrayList<String> toolList = new ArrayList<String>(toolItems.keySet()); if (toolList.size() == 0) return; menu.addSeparator(); Collections.sort(toolList); for (String title : toolList) { menu.add((JMenuItem) toolItems.get(title)); } } protected String findClassInZipFile(String base, File file) { // Class file to search for String classFileName = "/" + base + ".class"; try { ZipFile zipFile = new ZipFile(file); Enumeration<?> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (!entry.isDirectory()) { String name = entry.getName(); //System.out.println("entry: " + name); if (name.endsWith(classFileName)) { //int slash = name.lastIndexOf('/'); //String packageName = (slash == -1) ? "" : name.substring(0, slash); // Remove .class and convert slashes to periods. return name.substring(0, name.length() - 6).replace('/', '.'); } } } } catch (IOException e) { //System.err.println("Ignoring " + filename + " (" + e.getMessage() + ")"); e.printStackTrace(); } return null; } protected JMenuItem createToolMenuItem(String className) { try { Class<?> toolClass = Class.forName(className); final Tool tool = (Tool) toolClass.newInstance(); JMenuItem item = new JMenuItem(tool.getMenuTitle()); tool.init(Editor.this); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { SwingUtilities.invokeLater(tool); } }); return item; } catch (Exception e) { e.printStackTrace(); return null; } } protected JMenu addInternalTools(JMenu menu) { JMenuItem item; item = createToolMenuItem("processing.app.tools.AutoFormat"); int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); item.setAccelerator(KeyStroke.getKeyStroke('T', modifiers)); menu.add(item); //menu.add(createToolMenuItem("processing.app.tools.CreateFont")); //menu.add(createToolMenuItem("processing.app.tools.ColorSelector")); menu.add(createToolMenuItem("processing.app.tools.Archiver")); menu.add(createToolMenuItem("processing.app.tools.FixEncoding")); // // These are temporary entries while Android mode is being worked out. // // The mode will not be in the tools menu, and won't involve a cmd-key // if (!Base.RELEASE) { // item = createToolMenuItem("processing.app.tools.android.AndroidTool"); // item.setAccelerator(KeyStroke.getKeyStroke('D', modifiers)); // menu.add(item); // menu.add(createToolMenuItem("processing.app.tools.android.Reset")); // } return menu; } class SerialMenuListener implements ActionListener { //public SerialMenuListener() { } public void actionPerformed(ActionEvent e) { selectSerialPort(((JCheckBoxMenuItem)e.getSource()).getText()); base.onBoardOrPortChange(); } /* public void actionPerformed(ActionEvent e) { System.out.println(e.getSource()); String name = e.getActionCommand(); PdeBase.properties.put("serial.port", name); System.out.println("set to " + get("serial.port")); //editor.skOpen(path + File.separator + name, name); // need to push "serial.port" into PdeBase.properties } */ } protected void selectSerialPort(String name) { if(serialMenu == null) { System.out.println(_("serialMenu is null")); return; } if (name == null) { System.out.println(_("name is null")); return; } JCheckBoxMenuItem selection = null; for (int i = 0; i < serialMenu.getItemCount(); i++) { JCheckBoxMenuItem item = ((JCheckBoxMenuItem)serialMenu.getItem(i)); if (item == null) { System.out.println(_("name is null")); continue; } item.setState(false); if (name.equals(item.getText())) selection = item; } if (selection != null) selection.setState(true); //System.out.println(item.getLabel()); Preferences.set("serial.port", name); serialMonitor.closeSerialPort(); serialMonitor.setVisible(false); serialMonitor = new SerialMonitor(Preferences.get("serial.port")); //System.out.println("set to " + get("serial.port")); } protected void populateSerialMenu() { // getting list of ports JMenuItem rbMenuItem; //System.out.println("Clearing serial port menu."); serialMenu.removeAll(); boolean empty = true; try { for (Enumeration enumeration = CommPortIdentifier.getPortIdentifiers(); enumeration.hasMoreElements();) { CommPortIdentifier commportidentifier = (CommPortIdentifier)enumeration.nextElement(); //System.out.println("Found communication port: " + commportidentifier); if (commportidentifier.getPortType() == CommPortIdentifier.PORT_SERIAL) { //System.out.println("Adding port to serial port menu: " + commportidentifier); String curr_port = commportidentifier.getName(); rbMenuItem = new JCheckBoxMenuItem(curr_port, curr_port.equals(Preferences.get("serial.port"))); rbMenuItem.addActionListener(serialMenuListener); //serialGroup.add(rbMenuItem); serialMenu.add(rbMenuItem); empty = false; } } if (!empty) { //System.out.println("enabling the serialMenu"); serialMenu.setEnabled(true); } } catch (Exception exception) { System.out.println(_("error retrieving port list")); exception.printStackTrace(); } if (serialMenu.getItemCount() == 0) { serialMenu.setEnabled(false); } //serialMenu.addSeparator(); //serialMenu.add(item); } protected JMenu buildHelpMenu() { // To deal with a Mac OS X 10.5 bug, add an extra space after the name // so that the OS doesn't try to insert its slow help menu. JMenu menu = new JMenu(_("Help")); JMenuItem item; /* // testing internal web server to serve up docs from a zip file item = new JMenuItem("Web Server Test"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //WebServer ws = new WebServer(); SwingUtilities.invokeLater(new Runnable() { public void run() { try { int port = WebServer.launch("/Users/fry/coconut/processing/build/shared/reference.zip"); Base.openURL("http://127.0.0.1:" + port + "/reference/setup_.html"); } catch (IOException e1) { e1.printStackTrace(); } } }); } }); menu.add(item); */ /* item = new JMenuItem("Browser Test"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //Base.openURL("http://processing.org/learning/gettingstarted/"); //JFrame browserFrame = new JFrame("Browser"); BrowserStartup bs = new BrowserStartup("jar:file:/Users/fry/coconut/processing/build/shared/reference.zip!/reference/setup_.html"); bs.initUI(); bs.launch(); } }); menu.add(item); */ item = new JMenuItem(_("Getting Started")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showGettingStarted(); } }); menu.add(item); item = new JMenuItem(_("Environment")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showEnvironment(); } }); menu.add(item); item = new JMenuItem(_("Troubleshooting")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showTroubleshooting(); } }); menu.add(item); item = new JMenuItem(_("Reference")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showReference(); } }); menu.add(item); item = newJMenuItemShift(_("Find in Reference"), 'F'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // if (textarea.isSelectionActive()) { // handleFindReference(); // } handleFindReference(); } }); menu.add(item); item = new JMenuItem(_("Frequently Asked Questions")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.showFAQ(); } }); menu.add(item); item = new JMenuItem(_("Visit Arduino.cc")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.openURL(_("http://arduino.cc/")); } }); menu.add(item); // macosx already has its own about menu if (!Base.isMacOS()) { menu.addSeparator(); item = new JMenuItem(_("About Arduino")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { base.handleAbout(); } }); menu.add(item); } return menu; } protected JMenu buildEditMenu() { JMenu menu = new JMenu(_("Edit")); JMenuItem item; undoItem = newJMenuItem(_("Undo"), 'Z'); undoItem.addActionListener(undoAction = new UndoAction()); menu.add(undoItem); if (!Base.isMacOS()) { redoItem = newJMenuItem(_("Redo"), 'Y'); } else { redoItem = newJMenuItemShift(_("Redo"), 'Z'); } redoItem.addActionListener(redoAction = new RedoAction()); menu.add(redoItem); menu.addSeparator(); // TODO "cut" and "copy" should really only be enabled // if some text is currently selected item = newJMenuItem(_("Cut"), 'X'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleCut(); } }); menu.add(item); item = newJMenuItem(_("Copy"), 'C'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.copy(); } }); menu.add(item); item = newJMenuItemShift(_("Copy for Forum"), 'C'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // SwingUtilities.invokeLater(new Runnable() { // public void run() { new DiscourseFormat(Editor.this, false).show(); // } // }); } }); menu.add(item); item = newJMenuItemAlt(_("Copy as HTML"), 'C'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // SwingUtilities.invokeLater(new Runnable() { // public void run() { new DiscourseFormat(Editor.this, true).show(); // } // }); } }); menu.add(item); item = newJMenuItem(_("Paste"), 'V'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.paste(); sketch.setModified(true); } }); menu.add(item); item = newJMenuItem(_("Select All"), 'A'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textarea.selectAll(); } }); menu.add(item); menu.addSeparator(); item = newJMenuItem(_("Comment/Uncomment"), '/'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleCommentUncomment(); } }); menu.add(item); item = newJMenuItem(_("Increase Indent"), ']'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleIndentOutdent(true); } }); menu.add(item); item = newJMenuItem(_("Decrease Indent"), '['); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleIndentOutdent(false); } }); menu.add(item); menu.addSeparator(); item = newJMenuItem(_("Find..."), 'F'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (find == null) { find = new FindReplace(Editor.this); } //new FindReplace(Editor.this).show(); find.setVisible(true); //find.setVisible(true); } }); menu.add(item); // TODO find next should only be enabled after a // search has actually taken place item = newJMenuItem(_("Find Next"), 'G'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (find != null) { find.findNext(); } } }); menu.add(item); item = newJMenuItemShift(_("Find Previous"), 'G'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (find != null) { find.findPrevious(); } } }); menu.add(item); item = newJMenuItem(_("Use Selection For Find"), 'E'); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (find == null) { find = new FindReplace(Editor.this); } find.setFindText( getSelectedText() ); } }); menu.add(item); return menu; } /** * A software engineer, somewhere, needs to have his abstraction * taken away. In some countries they jail or beat people for writing * the sort of API that would require a five line helper function * just to set the command key for a menu item. */ static public JMenuItem newJMenuItem(String title, int what) { JMenuItem menuItem = new JMenuItem(title); int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); menuItem.setAccelerator(KeyStroke.getKeyStroke(what, modifiers)); return menuItem; } /** * Like newJMenuItem() but adds shift as a modifier for the key command. */ static public JMenuItem newJMenuItemShift(String title, int what) { JMenuItem menuItem = new JMenuItem(title); int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); modifiers |= ActionEvent.SHIFT_MASK; menuItem.setAccelerator(KeyStroke.getKeyStroke(what, modifiers)); return menuItem; } /** * Same as newJMenuItem(), but adds the ALT (on Linux and Windows) * or OPTION (on Mac OS X) key as a modifier. */ static public JMenuItem newJMenuItemAlt(String title, int what) { JMenuItem menuItem = new JMenuItem(title); //int modifiers = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); //menuItem.setAccelerator(KeyStroke.getKeyStroke(what, modifiers)); menuItem.setAccelerator(KeyStroke.getKeyStroke(what, SHORTCUT_ALT_KEY_MASK)); return menuItem; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class UndoAction extends AbstractAction { public UndoAction() { super("Undo"); this.setEnabled(false); } public void actionPerformed(ActionEvent e) { try { undo.undo(); } catch (CannotUndoException ex) { //System.out.println("Unable to undo: " + ex); //ex.printStackTrace(); } updateUndoState(); redoAction.updateRedoState(); } protected void updateUndoState() { if (undo.canUndo()) { this.setEnabled(true); undoItem.setEnabled(true); undoItem.setText(undo.getUndoPresentationName()); putValue(Action.NAME, undo.getUndoPresentationName()); if (sketch != null) { sketch.setModified(true); // 0107 } } else { this.setEnabled(false); undoItem.setEnabled(false); undoItem.setText(_("Undo")); putValue(Action.NAME, "Undo"); if (sketch != null) { sketch.setModified(false); // 0107 } } } } class RedoAction extends AbstractAction { public RedoAction() { super("Redo"); this.setEnabled(false); } public void actionPerformed(ActionEvent e) { try { undo.redo(); } catch (CannotRedoException ex) { //System.out.println("Unable to redo: " + ex); //ex.printStackTrace(); } updateRedoState(); undoAction.updateUndoState(); } protected void updateRedoState() { if (undo.canRedo()) { redoItem.setEnabled(true); redoItem.setText(undo.getRedoPresentationName()); putValue(Action.NAME, undo.getRedoPresentationName()); } else { this.setEnabled(false); redoItem.setEnabled(false); redoItem.setText(_("Redo")); putValue(Action.NAME, "Redo"); } } } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . // these will be done in a more generic way soon, more like: // setHandler("action name", Runnable); // but for the time being, working out the kinks of how many things to // abstract from the editor in this fashion. public void setHandlers(Runnable runHandler, Runnable presentHandler, Runnable stopHandler, Runnable exportHandler, Runnable exportAppHandler) { this.runHandler = runHandler; this.presentHandler = presentHandler; this.stopHandler = stopHandler; this.exportHandler = exportHandler; this.exportAppHandler = exportAppHandler; } public void resetHandlers() { runHandler = new DefaultRunHandler(); presentHandler = new DefaultPresentHandler(); stopHandler = new DefaultStopHandler(); exportHandler = new DefaultExportHandler(); exportAppHandler = new DefaultExportAppHandler(); } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /** * Gets the current sketch object. */ public Sketch getSketch() { return sketch; } /** * Get the JEditTextArea object for use (not recommended). This should only * be used in obscure cases that really need to hack the internals of the * JEditTextArea. Most tools should only interface via the get/set functions * found in this class. This will maintain compatibility with future releases, * which will not use JEditTextArea. */ public JEditTextArea getTextArea() { return textarea; } /** * Get the contents of the current buffer. Used by the Sketch class. */ public String getText() { return textarea.getText(); } /** * Get a range of text from the current buffer. */ public String getText(int start, int stop) { return textarea.getText(start, stop - start); } /** * Replace the entire contents of the front-most tab. */ public void setText(String what) { startCompoundEdit(); textarea.setText(what); stopCompoundEdit(); } public void insertText(String what) { startCompoundEdit(); int caret = getCaretOffset(); setSelection(caret, caret); textarea.setSelectedText(what); stopCompoundEdit(); } /** * Called to update the text but not switch to a different set of code * (which would affect the undo manager). */ // public void setText2(String what, int start, int stop) { // beginCompoundEdit(); // textarea.setText(what); // endCompoundEdit(); // // // make sure that a tool isn't asking for a bad location // start = Math.max(0, Math.min(start, textarea.getDocumentLength())); // stop = Math.max(0, Math.min(start, textarea.getDocumentLength())); // textarea.select(start, stop); // // textarea.requestFocus(); // get the caret blinking // } public String getSelectedText() { return textarea.getSelectedText(); } public void setSelectedText(String what) { textarea.setSelectedText(what); } public void setSelection(int start, int stop) { // make sure that a tool isn't asking for a bad location start = PApplet.constrain(start, 0, textarea.getDocumentLength()); stop = PApplet.constrain(stop, 0, textarea.getDocumentLength()); textarea.select(start, stop); } /** * Get the position (character offset) of the caret. With text selected, * this will be the last character actually selected, no matter the direction * of the selection. That is, if the user clicks and drags to select lines * 7 up to 4, then the caret position will be somewhere on line four. */ public int getCaretOffset() { return textarea.getCaretPosition(); } /** * True if some text is currently selected. */ public boolean isSelectionActive() { return textarea.isSelectionActive(); } /** * Get the beginning point of the current selection. */ public int getSelectionStart() { return textarea.getSelectionStart(); } /** * Get the end point of the current selection. */ public int getSelectionStop() { return textarea.getSelectionStop(); } /** * Get text for a specified line. */ public String getLineText(int line) { return textarea.getLineText(line); } /** * Replace the text on a specified line. */ public void setLineText(int line, String what) { startCompoundEdit(); textarea.select(getLineStartOffset(line), getLineStopOffset(line)); textarea.setSelectedText(what); stopCompoundEdit(); } /** * Get character offset for the start of a given line of text. */ public int getLineStartOffset(int line) { return textarea.getLineStartOffset(line); } /** * Get character offset for end of a given line of text. */ public int getLineStopOffset(int line) { return textarea.getLineStopOffset(line); } /** * Get the number of lines in the currently displayed buffer. */ public int getLineCount() { return textarea.getLineCount(); } /** * Use before a manipulating text to group editing operations together as a * single undo. Use stopCompoundEdit() once finished. */ public void startCompoundEdit() { compoundEdit = new CompoundEdit(); } /** * Use with startCompoundEdit() to group edit operations in a single undo. */ public void stopCompoundEdit() { compoundEdit.end(); undo.addEdit(compoundEdit); undoAction.updateUndoState(); redoAction.updateRedoState(); compoundEdit = null; } public int getScrollPosition() { return textarea.getScrollPosition(); } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /** * Switch between tabs, this swaps out the Document object * that's currently being manipulated. */ protected void setCode(SketchCode code) { SyntaxDocument document = (SyntaxDocument) code.getDocument(); if (document == null) { // this document not yet inited document = new SyntaxDocument(); code.setDocument(document); // turn on syntax highlighting document.setTokenMarker(new PdeKeywords()); // insert the program text into the document object try { document.insertString(0, code.getProgram(), null); } catch (BadLocationException bl) { bl.printStackTrace(); } // set up this guy's own undo manager // code.undo = new UndoManager(); // connect the undo listener to the editor document.addUndoableEditListener(new UndoableEditListener() { public void undoableEditHappened(UndoableEditEvent e) { if (compoundEdit != null) { compoundEdit.addEdit(e.getEdit()); } else if (undo != null) { undo.addEdit(e.getEdit()); undoAction.updateUndoState(); redoAction.updateRedoState(); } } }); } // update the document object that's in use textarea.setDocument(document, code.getSelectionStart(), code.getSelectionStop(), code.getScrollPosition()); textarea.requestFocus(); // get the caret blinking this.undo = code.getUndo(); undoAction.updateUndoState(); redoAction.updateRedoState(); } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /** * Implements Edit &rarr; Cut. */ public void handleCut() { textarea.cut(); sketch.setModified(true); } /** * Implements Edit &rarr; Copy. */ public void handleCopy() { textarea.copy(); } protected void handleDiscourseCopy() { new DiscourseFormat(Editor.this, false).show(); } protected void handleHTMLCopy() { new DiscourseFormat(Editor.this, true).show(); } /** * Implements Edit &rarr; Paste. */ public void handlePaste() { textarea.paste(); sketch.setModified(true); } /** * Implements Edit &rarr; Select All. */ public void handleSelectAll() { textarea.selectAll(); } protected void handleCommentUncomment() { startCompoundEdit(); int startLine = textarea.getSelectionStartLine(); int stopLine = textarea.getSelectionStopLine(); int lastLineStart = textarea.getLineStartOffset(stopLine); int selectionStop = textarea.getSelectionStop(); // If the selection ends at the beginning of the last line, // then don't (un)comment that line. if (selectionStop == lastLineStart) { // Though if there's no selection, don't do that if (textarea.isSelectionActive()) { stopLine--; } } // If the text is empty, ignore the user. // Also ensure that all lines are commented (not just the first) // when determining whether to comment or uncomment. int length = textarea.getDocumentLength(); boolean commented = true; for (int i = startLine; commented && (i <= stopLine); i++) { int pos = textarea.getLineStartOffset(i); if (pos + 2 > length) { commented = false; } else { // Check the first two characters to see if it's already a comment. String begin = textarea.getText(pos, 2); //System.out.println("begin is '" + begin + "'"); commented = begin.equals("//"); } } for (int line = startLine; line <= stopLine; line++) { int location = textarea.getLineStartOffset(line); if (commented) { // remove a comment textarea.select(location, location+2); if (textarea.getSelectedText().equals("//")) { textarea.setSelectedText(""); } } else { // add a comment textarea.select(location, location); textarea.setSelectedText("//"); } } // Subtract one from the end, otherwise selects past the current line. // (Which causes subsequent calls to keep expanding the selection) textarea.select(textarea.getLineStartOffset(startLine), textarea.getLineStopOffset(stopLine) - 1); stopCompoundEdit(); } protected void handleIndentOutdent(boolean indent) { int tabSize = Preferences.getInteger("editor.tabs.size"); String tabString = Editor.EMPTY.substring(0, tabSize); startCompoundEdit(); int startLine = textarea.getSelectionStartLine(); int stopLine = textarea.getSelectionStopLine(); // If the selection ends at the beginning of the last line, // then don't (un)comment that line. int lastLineStart = textarea.getLineStartOffset(stopLine); int selectionStop = textarea.getSelectionStop(); if (selectionStop == lastLineStart) { // Though if there's no selection, don't do that if (textarea.isSelectionActive()) { stopLine--; } } for (int line = startLine; line <= stopLine; line++) { int location = textarea.getLineStartOffset(line); if (indent) { textarea.select(location, location); textarea.setSelectedText(tabString); } else { // outdent textarea.select(location, location + tabSize); // Don't eat code if it's not indented if (textarea.getSelectedText().equals(tabString)) { textarea.setSelectedText(""); } } } // Subtract one from the end, otherwise selects past the current line. // (Which causes subsequent calls to keep expanding the selection) textarea.select(textarea.getLineStartOffset(startLine), textarea.getLineStopOffset(stopLine) - 1); stopCompoundEdit(); } protected String getCurrentKeyword() { String text = ""; if (textarea.getSelectedText() != null) text = textarea.getSelectedText().trim(); try { int current = textarea.getCaretPosition(); int startOffset = 0; int endIndex = current; String tmp = textarea.getDocument().getText(current, 1); // TODO probably a regexp that matches Arduino lang special chars // already exists. String regexp = "[\\s\\n();\\\\.!='\\[\\]{}]"; while (!tmp.matches(regexp)) { endIndex++; tmp = textarea.getDocument().getText(endIndex, 1); } // For some reason document index start at 2. // if( current - start < 2 ) return; tmp = ""; while (!tmp.matches(regexp)) { startOffset++; if (current - startOffset < 0) { tmp = textarea.getDocument().getText(0, 1); break; } else tmp = textarea.getDocument().getText(current - startOffset, 1); } startOffset--; int length = endIndex - current + startOffset; text = textarea.getDocument().getText(current - startOffset, length); } catch (BadLocationException bl) { bl.printStackTrace(); } finally { return text; } } protected void handleFindReference() { String text = getCurrentKeyword(); String referenceFile = PdeKeywords.getReference(text); if (referenceFile == null) { statusNotice(I18n.format(_("No reference available for \"{0}\""), text)); } else { Base.showReference(I18n.format(_("{0}.html"), referenceFile)); } } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /** * Implements Sketch &rarr; Run. * @param verbose Set true to run with verbose output. */ public void handleRun(final boolean verbose) { internalCloseRunner(); running = true; toolbar.activate(EditorToolbar.RUN); status.progress(_("Compiling sketch...")); // do this to advance/clear the terminal window / dos prompt / etc for (int i = 0; i < 10; i++) System.out.println(); // clear the console on each run, unless the user doesn't want to if (Preferences.getBoolean("console.auto_clear")) { console.clear(); } // Cannot use invokeLater() here, otherwise it gets // placed on the event thread and causes a hang--bad idea all around. new Thread(verbose ? presentHandler : runHandler).start(); } // DAM: in Arduino, this is compile class DefaultRunHandler implements Runnable { public void run() { try { sketch.prepare(); sketch.build(false); statusNotice(_("Done compiling.")); } catch (Exception e) { status.unprogress(); statusError(e); } status.unprogress(); toolbar.deactivate(EditorToolbar.RUN); } } // DAM: in Arduino, this is compile (with verbose output) class DefaultPresentHandler implements Runnable { public void run() { try { sketch.prepare(); sketch.build(true); statusNotice(_("Done compiling.")); } catch (Exception e) { status.unprogress(); statusError(e); } status.unprogress(); toolbar.deactivate(EditorToolbar.RUN); } } class DefaultStopHandler implements Runnable { public void run() { try { // DAM: we should try to kill the compilation or upload process here. } catch (Exception e) { statusError(e); } } } /** * Set the location of the sketch run window. Used by Runner to update the * Editor about window drag events while the sketch is running. */ public void setSketchLocation(Point p) { sketchWindowLocation = p; } /** * Get the last location of the sketch's run window. Used by Runner to make * the window show up in the same location as when it was last closed. */ public Point getSketchLocation() { return sketchWindowLocation; } /** * Implements Sketch &rarr; Stop, or pressing Stop on the toolbar. */ public void handleStop() { // called by menu or buttons // toolbar.activate(EditorToolbar.STOP); internalCloseRunner(); toolbar.deactivate(EditorToolbar.RUN); // toolbar.deactivate(EditorToolbar.STOP); // focus the PDE again after quitting presentation mode [toxi 030903] toFront(); } /** * Deactivate the Run button. This is called by Runner to notify that the * sketch has stopped running, usually in response to an error (or maybe * the sketch completing and exiting?) Tools should not call this function. * To initiate a "stop" action, call handleStop() instead. */ public void internalRunnerClosed() { running = false; toolbar.deactivate(EditorToolbar.RUN); } /** * Handle internal shutdown of the runner. */ public void internalCloseRunner() { running = false; if (stopHandler != null) try { stopHandler.run(); } catch (Exception e) { } sketch.cleanup(); } /** * Check if the sketch is modified and ask user to save changes. * @return false if canceling the close/quit operation */ protected boolean checkModified() { if (!sketch.isModified()) return true; // As of Processing 1.0.10, this always happens immediately. // http://dev.processing.org/bugs/show_bug.cgi?id=1456 String prompt = I18n.format(_("Save changes to \"{0}\"? "), sketch.getName()); if (!Base.isMacOS()) { int result = JOptionPane.showConfirmDialog(this, prompt, _("Close"), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (result == JOptionPane.YES_OPTION) { return handleSave(true); } else if (result == JOptionPane.NO_OPTION) { return true; // ok to continue } else if (result == JOptionPane.CANCEL_OPTION) { return false; } else { throw new IllegalStateException(); } } else { // This code is disabled unless Java 1.5 is being used on Mac OS X // because of a Java bug that prevents the initial value of the // dialog from being set properly (at least on my MacBook Pro). // The bug causes the "Don't Save" option to be the highlighted, // blinking, default. This sucks. But I'll tell you what doesn't // suck--workarounds for the Mac and Apple's snobby attitude about it! // I think it's nifty that they treat their developers like dirt. // Pane formatting adapted from the quaqua guide // http://www.randelshofer.ch/quaqua/guide/joptionpane.html JOptionPane pane = new JOptionPane(_("<html> " + "<head> <style type=\"text/css\">"+ "b { font: 13pt \"Lucida Grande\" }"+ "p { font: 11pt \"Lucida Grande\"; margin-top: 8px }"+ "</style> </head>" + "<b>Do you want to save changes to this sketch<BR>" + " before closing?</b>" + "<p>If you don't save, your changes will be lost."), JOptionPane.QUESTION_MESSAGE); String[] options = new String[] { _("Save"), _("Cancel"), _("Don't Save") }; pane.setOptions(options); // highlight the safest option ala apple hig pane.setInitialValue(options[0]); // on macosx, setting the destructive property places this option // away from the others at the lefthand side pane.putClientProperty("Quaqua.OptionPane.destructiveOption", new Integer(2)); JDialog dialog = pane.createDialog(this, null); dialog.setVisible(true); Object result = pane.getValue(); if (result == options[0]) { // save (and close/quit) return handleSave(true); } else if (result == options[2]) { // don't save (still close/quit) return true; } else { // cancel? return false; } } } /** * Open a sketch from a particular path, but don't check to save changes. * Used by Sketch.saveAs() to re-open a sketch after the "Save As" */ protected void handleOpenUnchecked(String path, int codeIndex, int selStart, int selStop, int scrollPos) { internalCloseRunner(); handleOpenInternal(path); // Replacing a document that may be untitled. If this is an actual // untitled document, then editor.untitled will be set by Base. untitled = false; sketch.setCurrentCode(codeIndex); textarea.select(selStart, selStop); textarea.setScrollPosition(scrollPos); } /** * Second stage of open, occurs after having checked to see if the * modifications (if any) to the previous sketch need to be saved. */ protected boolean handleOpenInternal(String path) { // check to make sure that this .pde file is // in a folder of the same name File file = new File(path); String fileName = file.getName(); File parent = file.getParentFile(); String parentName = parent.getName(); String pdeName = parentName + ".pde"; File altPdeFile = new File(parent, pdeName); String inoName = parentName + ".ino"; File altInoFile = new File(parent, pdeName); if (pdeName.equals(fileName) || inoName.equals(fileName)) { // no beef with this guy } else if (altPdeFile.exists()) { // user selected a .java from the same sketch, but open the .pde instead path = altPdeFile.getAbsolutePath(); } else if (altInoFile.exists()) { path = altInoFile.getAbsolutePath(); } else if (!path.endsWith(".ino") && !path.endsWith(".pde")) { Base.showWarning(_("Bad file selected"), _("Processing can only open its own sketches\n" + "and other files ending in .ino or .pde"), null); return false; } else { String properParent = fileName.substring(0, fileName.length() - 4); Object[] options = { _("OK"), _("Cancel") }; String prompt = I18n.format( _("The file \"{0}\" needs to be inside\n" + "a sketch folder named \"{1}\".\n" + "Create this folder, move the file, and continue?"), fileName, properParent ); int result = JOptionPane.showOptionDialog(this, prompt, _("Moving"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (result == JOptionPane.YES_OPTION) { // create properly named folder File properFolder = new File(file.getParent(), properParent); if (properFolder.exists()) { Base.showWarning(_("Error"), I18n.format( _("A folder named \"{0}\" already exists. " + "Can't open sketch."), properParent ), null); return false; } if (!properFolder.mkdirs()) { //throw new IOException("Couldn't create sketch folder"); Base.showWarning(_("Error"), _("Could not create the sketch folder."), null); return false; } // copy the sketch inside File properPdeFile = new File(properFolder, file.getName()); File origPdeFile = new File(path); try { Base.copyFile(origPdeFile, properPdeFile); } catch (IOException e) { Base.showWarning(_("Error"), _("Could not copy to a proper location."), e); return false; } // remove the original file, so user doesn't get confused origPdeFile.delete(); // update with the new path path = properPdeFile.getAbsolutePath(); } else if (result == JOptionPane.NO_OPTION) { return false; } } try { sketch = new Sketch(this, path); } catch (IOException e) { Base.showWarning(_("Error"), _("Could not create the sketch."), e); return false; } header.rebuild(); // Set the title of the window to "sketch_070752a - Processing 0126" setTitle( I18n.format( _("{0} | Arduino {1}"), sketch.getName(), Base.VERSION_NAME ) ); // Disable untitled setting from previous document, if any untitled = false; // Store information on who's open and running // (in case there's a crash or something that can't be recovered) base.storeSketches(); Preferences.save(); // opening was successful return true; // } catch (Exception e) { // e.printStackTrace(); // statusError(e); // return false; // } } /** * Actually handle the save command. If 'immediately' is set to false, * this will happen in another thread so that the message area * will update and the save button will stay highlighted while the * save is happening. If 'immediately' is true, then it will happen * immediately. This is used during a quit, because invokeLater() * won't run properly while a quit is happening. This fixes * <A HREF="http://dev.processing.org/bugs/show_bug.cgi?id=276">Bug 276</A>. */ public boolean handleSave(boolean immediately) { //stopRunner(); handleStop(); // 0136 if (untitled) { return handleSaveAs(); // need to get the name, user might also cancel here } else if (immediately) { return handleSave2(); } else { SwingUtilities.invokeLater(new Runnable() { public void run() { handleSave2(); } }); } return true; } protected boolean handleSave2() { toolbar.activate(EditorToolbar.SAVE); statusNotice(_("Saving...")); boolean saved = false; try { saved = sketch.save(); if (saved) statusNotice(_("Done Saving.")); else statusEmpty(); // rebuild sketch menu in case a save-as was forced // Disabling this for 0125, instead rebuild the menu inside // the Save As method of the Sketch object, since that's the // only one who knows whether something was renamed. //sketchbook.rebuildMenus(); //sketchbook.rebuildMenusAsync(); } catch (Exception e) { // show the error as a message in the window statusError(e); // zero out the current action, // so that checkModified2 will just do nothing //checkModifiedMode = 0; // this is used when another operation calls a save } //toolbar.clear(); toolbar.deactivate(EditorToolbar.SAVE); return saved; } public boolean handleSaveAs() { //stopRunner(); // formerly from 0135 handleStop(); toolbar.activate(EditorToolbar.SAVE); //SwingUtilities.invokeLater(new Runnable() { //public void run() { statusNotice(_("Saving...")); try { if (sketch.saveAs()) { statusNotice(_("Done Saving.")); // Disabling this for 0125, instead rebuild the menu inside // the Save As method of the Sketch object, since that's the // only one who knows whether something was renamed. //sketchbook.rebuildMenusAsync(); } else { statusNotice(_("Save Canceled.")); return false; } } catch (Exception e) { // show the error as a message in the window statusError(e); } finally { // make sure the toolbar button deactivates toolbar.deactivate(EditorToolbar.SAVE); } return true; } public boolean serialPrompt() { int count = serialMenu.getItemCount(); Object[] names = new Object[count]; for (int i = 0; i < count; i++) { names[i] = ((JCheckBoxMenuItem)serialMenu.getItem(i)).getText(); } String result = (String) JOptionPane.showInputDialog(this, I18n.format( _("Serial port {0} not found.\n" + "Retry the upload with another serial port?"), Preferences.get("serial.port") ), "Serial port not found", JOptionPane.PLAIN_MESSAGE, null, names, 0); if (result == null) return false; selectSerialPort(result); base.onBoardOrPortChange(); return true; } /** * Called by Sketch &rarr; Export. * Handles calling the export() function on sketch, and * queues all the gui status stuff that comes along with it. * <p/> * Made synchronized to (hopefully) avoid problems of people * hitting export twice, quickly, and horking things up. */ /** * Handles calling the export() function on sketch, and * queues all the gui status stuff that comes along with it. * * Made synchronized to (hopefully) avoid problems of people * hitting export twice, quickly, and horking things up. */ synchronized public void handleExport(final boolean usingProgrammer) { //if (!handleExportCheckModified()) return; toolbar.activate(EditorToolbar.EXPORT); console.clear(); status.progress(_("Uploading to I/O Board...")); new Thread(usingProgrammer ? exportAppHandler : exportHandler).start(); } // DAM: in Arduino, this is upload class DefaultExportHandler implements Runnable { public void run() { try { serialMonitor.closeSerialPort(); serialMonitor.setVisible(false); uploading = true; boolean success = sketch.exportApplet(false); if (success) { statusNotice(_("Done uploading.")); } else { // error message will already be visible } } catch (SerialNotFoundException e) { populateSerialMenu(); if (serialMenu.getItemCount() == 0) statusError(e); else if (serialPrompt()) run(); else statusNotice(_("Upload canceled.")); } catch (RunnerException e) { //statusError("Error during upload."); //e.printStackTrace(); status.unprogress(); statusError(e); } catch (Exception e) { e.printStackTrace(); } status.unprogress(); uploading = false; //toolbar.clear(); toolbar.deactivate(EditorToolbar.EXPORT); } } // DAM: in Arduino, this is upload (with verbose output) class DefaultExportAppHandler implements Runnable { public void run() { try { serialMonitor.closeSerialPort(); serialMonitor.setVisible(false); uploading = true; boolean success = sketch.exportApplet(true); if (success) { statusNotice(_("Done uploading.")); } else { // error message will already be visible } } catch (SerialNotFoundException e) { populateSerialMenu(); if (serialMenu.getItemCount() == 0) statusError(e); else if (serialPrompt()) run(); else statusNotice(_("Upload canceled.")); } catch (RunnerException e) { //statusError("Error during upload."); //e.printStackTrace(); status.unprogress(); statusError(e); } catch (Exception e) { e.printStackTrace(); } status.unprogress(); uploading = false; //toolbar.clear(); toolbar.deactivate(EditorToolbar.EXPORT); } } /** * Checks to see if the sketch has been modified, and if so, * asks the user to save the sketch or cancel the export. * This prevents issues where an incomplete version of the sketch * would be exported, and is a fix for * <A HREF="http://dev.processing.org/bugs/show_bug.cgi?id=157">Bug 157</A> */ protected boolean handleExportCheckModified() { if (!sketch.isModified()) return true; Object[] options = { _("OK"), _("Cancel") }; int result = JOptionPane.showOptionDialog(this, _("Save changes before export?"), _("Save"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (result == JOptionPane.OK_OPTION) { handleSave(true); } else { // why it's not CANCEL_OPTION is beyond me (at least on the mac) // but f-- it.. let's get this shite done.. //} else if (result == JOptionPane.CANCEL_OPTION) { statusNotice(_("Export canceled, changes must first be saved.")); //toolbar.clear(); return false; } return true; } public void handleSerial() { if (uploading) return; try { serialMonitor.openSerialPort(); serialMonitor.setVisible(true); } catch (SerialException e) { statusError(e); } } protected void handleBurnBootloader() { console.clear(); statusNotice(_("Burning bootloader to I/O Board (this may take a minute)...")); SwingUtilities.invokeLater(new Runnable() { public void run() { try { Uploader uploader = new AvrdudeUploader(); if (uploader.burnBootloader()) { statusNotice(_("Done burning bootloader.")); } else { statusError(_("Error while burning bootloader.")); // error message will already be visible } } catch (RunnerException e) { statusError(_("Error while burning bootloader.")); e.printStackTrace(); //statusError(e); } catch (Exception e) { statusError(_("Error while burning bootloader.")); e.printStackTrace(); } }}); } /** * Handler for File &rarr; Page Setup. */ public void handlePageSetup() { //printerJob = null; if (printerJob == null) { printerJob = PrinterJob.getPrinterJob(); } if (pageFormat == null) { pageFormat = printerJob.defaultPage(); } pageFormat = printerJob.pageDialog(pageFormat); //System.out.println("page format is " + pageFormat); } /** * Handler for File &rarr; Print. */ public void handlePrint() { statusNotice(_("Printing...")); //printerJob = null; if (printerJob == null) { printerJob = PrinterJob.getPrinterJob(); } if (pageFormat != null) { //System.out.println("setting page format " + pageFormat); printerJob.setPrintable(textarea.getPainter(), pageFormat); } else { printerJob.setPrintable(textarea.getPainter()); } // set the name of the job to the code name printerJob.setJobName(sketch.getCurrentCode().getPrettyName()); if (printerJob.printDialog()) { try { printerJob.print(); statusNotice(_("Done printing.")); } catch (PrinterException pe) { statusError(_("Error while printing.")); pe.printStackTrace(); } } else { statusNotice(_("Printing canceled.")); } //printerJob = null; // clear this out? } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /** * Show an error int the status bar. */ public void statusError(String what) { status.error(what); //new Exception("deactivating RUN").printStackTrace(); toolbar.deactivate(EditorToolbar.RUN); } /** * Show an exception in the editor status bar. */ public void statusError(Exception e) { e.printStackTrace(); // if (e == null) { // System.err.println("Editor.statusError() was passed a null exception."); // return; // } if (e instanceof RunnerException) { RunnerException re = (RunnerException) e; if (re.hasCodeIndex()) { sketch.setCurrentCode(re.getCodeIndex()); } if (re.hasCodeLine()) { int line = re.getCodeLine(); // subtract one from the end so that the \n ain't included if (line >= textarea.getLineCount()) { // The error is at the end of this current chunk of code, // so the last line needs to be selected. line = textarea.getLineCount() - 1; if (textarea.getLineText(line).length() == 0) { // The last line may be zero length, meaning nothing to select. // If so, back up one more line. line--; } } if (line < 0 || line >= textarea.getLineCount()) { System.err.println(I18n.format(_("Bad error line: {0}"), line)); } else { textarea.select(textarea.getLineStartOffset(line), textarea.getLineStopOffset(line) - 1); } } } // Since this will catch all Exception types, spend some time figuring // out which kind and try to give a better error message to the user. String mess = e.getMessage(); if (mess != null) { String javaLang = "java.lang."; if (mess.indexOf(javaLang) == 0) { mess = mess.substring(javaLang.length()); } String rxString = "RuntimeException: "; if (mess.indexOf(rxString) == 0) { mess = mess.substring(rxString.length()); } statusError(mess); } // e.printStackTrace(); } /** * Show a notice message in the editor status bar. */ public void statusNotice(String msg) { status.notice(msg); } /** * Clear the status area. */ public void statusEmpty() { statusNotice(EMPTY); } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . protected void onBoardOrPortChange() { Map<String, String> boardPreferences = Base.getBoardPreferences(); lineStatus.setBoardName(boardPreferences.get("name")); lineStatus.setSerialPort(Preferences.get("serial.port")); lineStatus.repaint(); } /** * Returns the edit popup menu. */ class TextAreaPopup extends JPopupMenu { //private String currentDir = System.getProperty("user.dir"); private String referenceFile = null; private JMenuItem cutItem; private JMenuItem copyItem; private JMenuItem discourseItem; private JMenuItem referenceItem; private JMenuItem openURLItem; private JSeparator openURLItemSeparator; private String clickedURL; public TextAreaPopup() { openURLItem = new JMenuItem(_("Open URL")); openURLItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Base.openURL(clickedURL); } }); add(openURLItem); openURLItemSeparator = new JSeparator(); add(openURLItemSeparator); cutItem = new JMenuItem(_("Cut")); cutItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleCut(); } }); add(cutItem); copyItem = new JMenuItem(_("Copy")); copyItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleCopy(); } }); add(copyItem); discourseItem = new JMenuItem(_("Copy for Forum")); discourseItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleDiscourseCopy(); } }); add(discourseItem); discourseItem = new JMenuItem(_("Copy as HTML")); discourseItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleHTMLCopy(); } }); add(discourseItem); JMenuItem item = new JMenuItem(_("Paste")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handlePaste(); } }); add(item); item = new JMenuItem(_("Select All")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleSelectAll(); } }); add(item); addSeparator(); item = new JMenuItem(_("Comment/Uncomment")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleCommentUncomment(); } }); add(item); item = new JMenuItem(_("Increase Indent")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleIndentOutdent(true); } }); add(item); item = new JMenuItem(_("Decrease Indent")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleIndentOutdent(false); } }); add(item); addSeparator(); referenceItem = new JMenuItem(_("Find in Reference")); referenceItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { handleFindReference(); } }); add(referenceItem); } // if no text is selected, disable copy and cut menu items public void show(Component component, int x, int y) { int lineNo = textarea.getLineOfOffset(textarea.xyToOffset(x, y)); int offset = textarea.xToOffset(lineNo, x); String line = textarea.getLineText(lineNo); clickedURL = textarea.checkClickedURL(line, offset); if (clickedURL != null) { openURLItem.setVisible(true); openURLItemSeparator.setVisible(true); } else { openURLItem.setVisible(false); openURLItemSeparator.setVisible(false); } if (textarea.isSelectionActive()) { cutItem.setEnabled(true); copyItem.setEnabled(true); discourseItem.setEnabled(true); } else { cutItem.setEnabled(false); copyItem.setEnabled(false); discourseItem.setEnabled(false); } referenceFile = PdeKeywords.getReference(getCurrentKeyword()); referenceItem.setEnabled(referenceFile != null); super.show(component, x, y); } } }
false
true
public Editor(Base ibase, String path, int[] location) { super("Arduino"); this.base = ibase; Base.setIcon(this); // Install default actions for Run, Present, etc. resetHandlers(); // add listener to handle window close box hit event addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { base.handleClose(Editor.this); } }); // don't close the window when clicked, the app will take care // of that via the handleQuitInternal() methods // http://dev.processing.org/bugs/show_bug.cgi?id=440 setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); // When bringing a window to front, let the Base know addWindowListener(new WindowAdapter() { public void windowActivated(WindowEvent e) { // System.err.println("activate"); // not coming through base.handleActivated(Editor.this); // re-add the sub-menus that are shared by all windows fileMenu.insert(sketchbookMenu, 2); fileMenu.insert(examplesMenu, 3); //sketchMenu.insert(importMenu, 4); toolsMenu.insert(boardsMenu, numTools); toolsMenu.insert(serialMenu, numTools + 1); } // added for 1.0.5 // http://dev.processing.org/bugs/show_bug.cgi?id=1260 public void windowDeactivated(WindowEvent e) { // System.err.println("deactivate"); // not coming through fileMenu.remove(sketchbookMenu); fileMenu.remove(examplesMenu); //sketchMenu.remove(importMenu); toolsMenu.remove(boardsMenu); toolsMenu.remove(serialMenu); } }); //PdeKeywords keywords = new PdeKeywords(); //sketchbook = new Sketchbook(this); if (serialMonitor == null) { serialMonitor = new SerialMonitor(Preferences.get("serial.port")); serialMonitor.setIconImage(getIconImage()); } buildMenuBar(); // For rev 0120, placing things inside a JPanel Container contentPain = getContentPane(); contentPain.setLayout(new BorderLayout()); JPanel pain = new JPanel(); pain.setLayout(new BorderLayout()); contentPain.add(pain, BorderLayout.CENTER); Box box = Box.createVerticalBox(); Box upper = Box.createVerticalBox(); if (toolbarMenu == null) { toolbarMenu = new JMenu(); base.rebuildToolbarMenu(toolbarMenu); } toolbar = new EditorToolbar(this, toolbarMenu); upper.add(toolbar); header = new EditorHeader(this); upper.add(header); textarea = new JEditTextArea(new PdeTextAreaDefaults()); textarea.setRightClickPopup(new TextAreaPopup()); textarea.setHorizontalOffset(6); // assemble console panel, consisting of status area and the console itself consolePanel = new JPanel(); consolePanel.setLayout(new BorderLayout()); status = new EditorStatus(this); consolePanel.add(status, BorderLayout.NORTH); console = new EditorConsole(this); // windows puts an ugly border on this guy console.setBorder(null); consolePanel.add(console, BorderLayout.CENTER); lineStatus = new EditorLineStatus(textarea); consolePanel.add(lineStatus, BorderLayout.SOUTH); upper.add(textarea); splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, upper, consolePanel); splitPane.setOneTouchExpandable(true); // repaint child panes while resizing splitPane.setContinuousLayout(true); // if window increases in size, give all of increase to // the textarea in the uppper pane splitPane.setResizeWeight(1D); // to fix ugliness.. normally macosx java 1.3 puts an // ugly white border around this object, so turn it off. splitPane.setBorder(null); // the default size on windows is too small and kinda ugly int dividerSize = Preferences.getInteger("editor.divider.size"); if (dividerSize != 0) { splitPane.setDividerSize(dividerSize); } // the following changed from 600, 400 for netbooks // http://code.google.com/p/arduino/issues/detail?id=52 splitPane.setMinimumSize(new Dimension(600, 100)); box.add(splitPane); // hopefully these are no longer needed w/ swing // (har har har.. that was wishful thinking) listener = new EditorListener(this, textarea); pain.add(box); // get shift down/up events so we can show the alt version of toolbar buttons textarea.addKeyListener(toolbar); pain.setTransferHandler(new FileDropHandler()); // System.out.println("t1"); // Finish preparing Editor (formerly found in Base) pack(); // System.out.println("t2"); // Set the window bounds and the divider location before setting it visible setPlacement(location); // Set the minimum size for the editor window setMinimumSize(new Dimension(Preferences.getInteger("editor.window.width.min"), Preferences.getInteger("editor.window.height.min"))); // System.out.println("t3"); // Bring back the general options for the editor applyPreferences(); // System.out.println("t4"); // Open the document that was passed in boolean loaded = handleOpenInternal(path); if (!loaded) sketch = null; // System.out.println("t5"); // All set, now show the window //setVisible(true); }
public Editor(Base ibase, String path, int[] location) { super("Arduino"); this.base = ibase; Base.setIcon(this); // Install default actions for Run, Present, etc. resetHandlers(); // add listener to handle window close box hit event addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { base.handleClose(Editor.this); } }); // don't close the window when clicked, the app will take care // of that via the handleQuitInternal() methods // http://dev.processing.org/bugs/show_bug.cgi?id=440 setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); // When bringing a window to front, let the Base know addWindowListener(new WindowAdapter() { public void windowActivated(WindowEvent e) { // System.err.println("activate"); // not coming through base.handleActivated(Editor.this); // re-add the sub-menus that are shared by all windows fileMenu.insert(sketchbookMenu, 2); fileMenu.insert(examplesMenu, 3); sketchMenu.insert(importMenu, 4); toolsMenu.insert(boardsMenu, numTools); toolsMenu.insert(serialMenu, numTools + 1); } // added for 1.0.5 // http://dev.processing.org/bugs/show_bug.cgi?id=1260 public void windowDeactivated(WindowEvent e) { // System.err.println("deactivate"); // not coming through fileMenu.remove(sketchbookMenu); fileMenu.remove(examplesMenu); sketchMenu.remove(importMenu); toolsMenu.remove(boardsMenu); toolsMenu.remove(serialMenu); } }); //PdeKeywords keywords = new PdeKeywords(); //sketchbook = new Sketchbook(this); if (serialMonitor == null) { serialMonitor = new SerialMonitor(Preferences.get("serial.port")); serialMonitor.setIconImage(getIconImage()); } buildMenuBar(); // For rev 0120, placing things inside a JPanel Container contentPain = getContentPane(); contentPain.setLayout(new BorderLayout()); JPanel pain = new JPanel(); pain.setLayout(new BorderLayout()); contentPain.add(pain, BorderLayout.CENTER); Box box = Box.createVerticalBox(); Box upper = Box.createVerticalBox(); if (toolbarMenu == null) { toolbarMenu = new JMenu(); base.rebuildToolbarMenu(toolbarMenu); } toolbar = new EditorToolbar(this, toolbarMenu); upper.add(toolbar); header = new EditorHeader(this); upper.add(header); textarea = new JEditTextArea(new PdeTextAreaDefaults()); textarea.setRightClickPopup(new TextAreaPopup()); textarea.setHorizontalOffset(6); // assemble console panel, consisting of status area and the console itself consolePanel = new JPanel(); consolePanel.setLayout(new BorderLayout()); status = new EditorStatus(this); consolePanel.add(status, BorderLayout.NORTH); console = new EditorConsole(this); // windows puts an ugly border on this guy console.setBorder(null); consolePanel.add(console, BorderLayout.CENTER); lineStatus = new EditorLineStatus(textarea); consolePanel.add(lineStatus, BorderLayout.SOUTH); upper.add(textarea); splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, upper, consolePanel); splitPane.setOneTouchExpandable(true); // repaint child panes while resizing splitPane.setContinuousLayout(true); // if window increases in size, give all of increase to // the textarea in the uppper pane splitPane.setResizeWeight(1D); // to fix ugliness.. normally macosx java 1.3 puts an // ugly white border around this object, so turn it off. splitPane.setBorder(null); // the default size on windows is too small and kinda ugly int dividerSize = Preferences.getInteger("editor.divider.size"); if (dividerSize != 0) { splitPane.setDividerSize(dividerSize); } // the following changed from 600, 400 for netbooks // http://code.google.com/p/arduino/issues/detail?id=52 splitPane.setMinimumSize(new Dimension(600, 100)); box.add(splitPane); // hopefully these are no longer needed w/ swing // (har har har.. that was wishful thinking) listener = new EditorListener(this, textarea); pain.add(box); // get shift down/up events so we can show the alt version of toolbar buttons textarea.addKeyListener(toolbar); pain.setTransferHandler(new FileDropHandler()); // System.out.println("t1"); // Finish preparing Editor (formerly found in Base) pack(); // System.out.println("t2"); // Set the window bounds and the divider location before setting it visible setPlacement(location); // Set the minimum size for the editor window setMinimumSize(new Dimension(Preferences.getInteger("editor.window.width.min"), Preferences.getInteger("editor.window.height.min"))); // System.out.println("t3"); // Bring back the general options for the editor applyPreferences(); // System.out.println("t4"); // Open the document that was passed in boolean loaded = handleOpenInternal(path); if (!loaded) sketch = null; // System.out.println("t5"); // All set, now show the window //setVisible(true); }
diff --git a/com/mraof/minestuck/inventory/ContainerMachine.java b/com/mraof/minestuck/inventory/ContainerMachine.java index dbee0fec..f36acd76 100644 --- a/com/mraof/minestuck/inventory/ContainerMachine.java +++ b/com/mraof/minestuck/inventory/ContainerMachine.java @@ -1,226 +1,226 @@ package com.mraof.minestuck.inventory; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.ICrafting; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import com.mraof.minestuck.Minestuck; import com.mraof.minestuck.tileentity.TileEntityMachine; public class ContainerMachine extends Container { private static final int cruxtruderInputX = 79; private static final int cruxtruderInputY = 57; private static final int cruxtruderOutputX = 79; private static final int cruxtruderOutputY = 19; private static final int designexInput1X = 62; private static final int designexInput1Y = 26; private static final int designexInput2X = 62; private static final int designexInput2Y = 50; private static final int designexCardsX = 26; private static final int designexCardsY = 50; private static final int designexOutputX = 134; private static final int designexOutputY = 37; private static final int latheCardX = 44; private static final int latheCardY = 20; private static final int latheDowelX = 44; private static final int latheDowelY = 50; private static final int latheOutputX = 122; private static final int latheOutputY = 33; private static final int alchemiterInputX = 27; private static final int alchemiterInputY = 20; private static final int alchemiterOutputX = 135; private static final int alchemiterOutputY = 20; public TileEntityMachine tileEntity; private int metadata; private boolean operator = true; public ContainerMachine(InventoryPlayer inventoryPlayer, TileEntityMachine te) { tileEntity = te; metadata = te.getMetadata(); te.owner = inventoryPlayer.player; //the Slot constructor takes the IInventory and the slot number in that it binds to //and the x-y coordinates it resides on-screen switch (metadata) { case (0): addSlotToContainer(new SlotInput(tileEntity,1,cruxtruderInputX,cruxtruderInputY,Minestuck.rawCruxite.itemID)); addSlotToContainer(new SlotOutput(tileEntity,0,cruxtruderOutputX,cruxtruderOutputY)); break; case (1): addSlotToContainer(new Slot(tileEntity,1,designexInput1X,designexInput1Y)); addSlotToContainer(new Slot(tileEntity,2,designexInput2X,designexInput2Y)); addSlotToContainer(new SlotInput(tileEntity,3,designexCardsX,designexCardsY,Minestuck.blankCard.itemID)); addSlotToContainer(new SlotOutput(tileEntity,0,designexOutputX,designexOutputY)); break; case (2): addSlotToContainer(new SlotInput(tileEntity,1,latheCardX,latheCardY,Minestuck.punchedCard.itemID)); addSlotToContainer(new SlotInput(tileEntity,2,latheDowelX,latheDowelY,Minestuck.cruxiteDowel.itemID)); addSlotToContainer(new SlotOutput(tileEntity,0,latheOutputX,latheOutputY)); break; case (3): addSlotToContainer(new SlotDualInput(tileEntity,1,alchemiterInputX,alchemiterInputY,Minestuck.cruxiteDowelCarved.itemID,Minestuck.cruxiteDowel.itemID)); addSlotToContainer(new SlotOutput(tileEntity,0,alchemiterOutputX,alchemiterOutputY)); //break; } // for (int i = 0; i < 3; i++) { // for (int j = 0; j < 3; j++) { // addSlotToContainer(new Slot(tileEntity, j + i * 3, 62 + j * 18, 17 + i * 18)); // } // } //commonly used vanilla code that adds the player's inventory bindPlayerInventory(inventoryPlayer); } @Override public boolean canInteractWith(EntityPlayer player) { return tileEntity.isUseableByPlayer(player); } protected void bindPlayerInventory(InventoryPlayer inventoryPlayer) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 9; j++) { addSlotToContainer(new Slot(inventoryPlayer, j + i * 9 + 9, 8 + j * 18, 84 + i * 18)); } } for (int i = 0; i < 9; i++) { addSlotToContainer(new Slot(inventoryPlayer, i, 8 + i * 18, 142)); } } @Override public ItemStack transferStackInSlot(EntityPlayer player, int slotNumber) { ItemStack itemstack = null; Slot slot = (Slot)this.inventorySlots.get(slotNumber); int allSlots = this.inventorySlots.size(); int invSlots = tileEntity.getSizeInventory(); if (slot != null && slot.getHasStack()) { ItemStack itemstackOrig = slot.getStack(); itemstack = itemstackOrig.copy(); boolean result = false; //System.out.println("[MINESTUCK] Shifing slot "+slotNumber); switch (metadata) { case (0): if (slotNumber <= 1) { //if it's a machine slot result = mergeItemStack(itemstackOrig,2,allSlots,false); } else if (slotNumber > 1) { //if it's an inventory slot with valid contents //System.out.println("[MINESTUCK] item ID of " + itemstackOrig.itemID + ". Expected " + Minestuck.rawCruxite.itemID); if (itemstackOrig.itemID == Minestuck.rawCruxite.itemID) { //System.out.println("[MINESTUCK] Transferring..."); result = mergeItemStack(itemstackOrig,0,1,false); } } break; case (1): if (slotNumber <= 3) { //if it's a machine slot result = mergeItemStack(itemstackOrig,4,allSlots,false); } else if (slotNumber > 3) { //if it's an inventory slot with valid contents if (itemstackOrig.itemID == Minestuck.blankCard.itemID) { result = mergeItemStack(itemstackOrig,2,3,false); } else { result = mergeItemStack(itemstackOrig,0,2,false); } } break; case (2): if (slotNumber <= 2) { //if it's a machine slot result = mergeItemStack(itemstackOrig,3,allSlots,false); } else if (slotNumber > 2) { //if it's an inventory slot with valid contents if (itemstackOrig.itemID == Minestuck.punchedCard.itemID) { result = mergeItemStack(itemstackOrig,0,1,false); } else if (itemstackOrig.itemID == Minestuck.cruxiteDowel.itemID) { result = mergeItemStack(itemstackOrig,1,2,false); } } break; case (3): if (slotNumber <= 1) { //if it's a machine slot result = mergeItemStack(itemstackOrig,2,allSlots,false); } else if (slotNumber > 1) { //if it's an inventory slot with valid contents - if (itemstackOrig.itemID == Minestuck.cruxiteDowelCarved.itemID) { + if (itemstackOrig.itemID == Minestuck.cruxiteDowelCarved.itemID || itemstackOrig.itemID == Minestuck.cruxiteDowel.itemID) { result = mergeItemStack(itemstackOrig,0,1,false); } } break; } if (!result) { return null; } if (itemstackOrig.stackSize == 0) { slot.putStack((ItemStack)null); } else { slot.onSlotChanged(); } } return itemstack; } public void addCraftingToCrafters(ICrafting par1ICrafting) { super.addCraftingToCrafters(par1ICrafting); // System.out.printf("[MINESTUCK] addCraftingToCrafters running, the metadata is %d\n", this.metadata); switch(this.metadata) { case 1: // System.out.printf("[MINESTUCK] Mode is %b \n", this.tileEntity.mode); par1ICrafting.sendProgressBarUpdate(this, 0, this.tileEntity.mode ? 0 : 1); } } public void detectAndSendChanges() { super.detectAndSendChanges(); for (int i = 0; i < this.crafters.size(); ++i) { ICrafting icrafting = (ICrafting)this.crafters.get(i); switch(this.metadata) { case 1: if (this.operator != (this.tileEntity.mode)) { icrafting.sendProgressBarUpdate(this, 0, this.tileEntity.mode ? 0 : 1); this.operator = this.tileEntity.mode; } } } } @Override public void updateProgressBar(int par1, int par2) { switch(this.metadata) { case 1: // System.out.println("Mode on Client is now " + par2); tileEntity.mode = par2 == 0; } } }
true
true
public ItemStack transferStackInSlot(EntityPlayer player, int slotNumber) { ItemStack itemstack = null; Slot slot = (Slot)this.inventorySlots.get(slotNumber); int allSlots = this.inventorySlots.size(); int invSlots = tileEntity.getSizeInventory(); if (slot != null && slot.getHasStack()) { ItemStack itemstackOrig = slot.getStack(); itemstack = itemstackOrig.copy(); boolean result = false; //System.out.println("[MINESTUCK] Shifing slot "+slotNumber); switch (metadata) { case (0): if (slotNumber <= 1) { //if it's a machine slot result = mergeItemStack(itemstackOrig,2,allSlots,false); } else if (slotNumber > 1) { //if it's an inventory slot with valid contents //System.out.println("[MINESTUCK] item ID of " + itemstackOrig.itemID + ". Expected " + Minestuck.rawCruxite.itemID); if (itemstackOrig.itemID == Minestuck.rawCruxite.itemID) { //System.out.println("[MINESTUCK] Transferring..."); result = mergeItemStack(itemstackOrig,0,1,false); } } break; case (1): if (slotNumber <= 3) { //if it's a machine slot result = mergeItemStack(itemstackOrig,4,allSlots,false); } else if (slotNumber > 3) { //if it's an inventory slot with valid contents if (itemstackOrig.itemID == Minestuck.blankCard.itemID) { result = mergeItemStack(itemstackOrig,2,3,false); } else { result = mergeItemStack(itemstackOrig,0,2,false); } } break; case (2): if (slotNumber <= 2) { //if it's a machine slot result = mergeItemStack(itemstackOrig,3,allSlots,false); } else if (slotNumber > 2) { //if it's an inventory slot with valid contents if (itemstackOrig.itemID == Minestuck.punchedCard.itemID) { result = mergeItemStack(itemstackOrig,0,1,false); } else if (itemstackOrig.itemID == Minestuck.cruxiteDowel.itemID) { result = mergeItemStack(itemstackOrig,1,2,false); } } break; case (3): if (slotNumber <= 1) { //if it's a machine slot result = mergeItemStack(itemstackOrig,2,allSlots,false); } else if (slotNumber > 1) { //if it's an inventory slot with valid contents if (itemstackOrig.itemID == Minestuck.cruxiteDowelCarved.itemID) { result = mergeItemStack(itemstackOrig,0,1,false); } } break; } if (!result) { return null; } if (itemstackOrig.stackSize == 0) { slot.putStack((ItemStack)null); } else { slot.onSlotChanged(); } } return itemstack; }
public ItemStack transferStackInSlot(EntityPlayer player, int slotNumber) { ItemStack itemstack = null; Slot slot = (Slot)this.inventorySlots.get(slotNumber); int allSlots = this.inventorySlots.size(); int invSlots = tileEntity.getSizeInventory(); if (slot != null && slot.getHasStack()) { ItemStack itemstackOrig = slot.getStack(); itemstack = itemstackOrig.copy(); boolean result = false; //System.out.println("[MINESTUCK] Shifing slot "+slotNumber); switch (metadata) { case (0): if (slotNumber <= 1) { //if it's a machine slot result = mergeItemStack(itemstackOrig,2,allSlots,false); } else if (slotNumber > 1) { //if it's an inventory slot with valid contents //System.out.println("[MINESTUCK] item ID of " + itemstackOrig.itemID + ". Expected " + Minestuck.rawCruxite.itemID); if (itemstackOrig.itemID == Minestuck.rawCruxite.itemID) { //System.out.println("[MINESTUCK] Transferring..."); result = mergeItemStack(itemstackOrig,0,1,false); } } break; case (1): if (slotNumber <= 3) { //if it's a machine slot result = mergeItemStack(itemstackOrig,4,allSlots,false); } else if (slotNumber > 3) { //if it's an inventory slot with valid contents if (itemstackOrig.itemID == Minestuck.blankCard.itemID) { result = mergeItemStack(itemstackOrig,2,3,false); } else { result = mergeItemStack(itemstackOrig,0,2,false); } } break; case (2): if (slotNumber <= 2) { //if it's a machine slot result = mergeItemStack(itemstackOrig,3,allSlots,false); } else if (slotNumber > 2) { //if it's an inventory slot with valid contents if (itemstackOrig.itemID == Minestuck.punchedCard.itemID) { result = mergeItemStack(itemstackOrig,0,1,false); } else if (itemstackOrig.itemID == Minestuck.cruxiteDowel.itemID) { result = mergeItemStack(itemstackOrig,1,2,false); } } break; case (3): if (slotNumber <= 1) { //if it's a machine slot result = mergeItemStack(itemstackOrig,2,allSlots,false); } else if (slotNumber > 1) { //if it's an inventory slot with valid contents if (itemstackOrig.itemID == Minestuck.cruxiteDowelCarved.itemID || itemstackOrig.itemID == Minestuck.cruxiteDowel.itemID) { result = mergeItemStack(itemstackOrig,0,1,false); } } break; } if (!result) { return null; } if (itemstackOrig.stackSize == 0) { slot.putStack((ItemStack)null); } else { slot.onSlotChanged(); } } return itemstack; }
diff --git a/test/src/test/thread/Helper.java b/test/src/test/thread/Helper.java index 10dbdf12..e6732334 100644 --- a/test/src/test/thread/Helper.java +++ b/test/src/test/thread/Helper.java @@ -1,22 +1,25 @@ package test.thread; import java.util.HashMap; import java.util.Map; public class Helper { private static Map<String, Map<Long, Long>> m_maps = new HashMap<String, Map<Long, Long>>(); - public synchronized static Map<Long, Long> getMap(String className) { - Map<Long, Long> result = m_maps.get(className); - if (result == null) { - result = new HashMap(); - m_maps.put(className, result); + public static Map<Long, Long> getMap(String className) { + synchronized(m_maps) { + Map<Long, Long> result = m_maps.get(className); + if (result == null) { + result = new HashMap(); + m_maps.put(className, result); + } + return result; } +// System.out.println("Putting class:" + className + " result:" + result); - return result; } public static void reset() { m_maps = new HashMap<String, Map<Long, Long>>(); } }
false
true
public synchronized static Map<Long, Long> getMap(String className) { Map<Long, Long> result = m_maps.get(className); if (result == null) { result = new HashMap(); m_maps.put(className, result); } return result; }
public static Map<Long, Long> getMap(String className) { synchronized(m_maps) { Map<Long, Long> result = m_maps.get(className); if (result == null) { result = new HashMap(); m_maps.put(className, result); } return result; } // System.out.println("Putting class:" + className + " result:" + result); }
diff --git a/src/com/orange/groupbuy/parser/TaobaoKillParser.java b/src/com/orange/groupbuy/parser/TaobaoKillParser.java index e966a9a..20a282f 100644 --- a/src/com/orange/groupbuy/parser/TaobaoKillParser.java +++ b/src/com/orange/groupbuy/parser/TaobaoKillParser.java @@ -1,315 +1,315 @@ package com.orange.groupbuy.parser; import java.util.Date; import java.util.concurrent.ConcurrentHashMap; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.jdom.Element; import org.jsoup.Jsoup; import com.mongodb.DBObject; import com.orange.common.solr.SolrClient; import com.orange.common.utils.DateUtil; import com.orange.common.utils.StringUtil; import com.orange.groupbuy.addressparser.CommonAddressParser; import com.orange.groupbuy.constant.DBConstants; import com.orange.groupbuy.dao.Product; import com.orange.groupbuy.manager.ProductManager; import com.taobao.api.ApiException; import com.taobao.api.DefaultTaobaoClient; import com.taobao.api.TaobaoClient; import com.taobao.api.request.ItemsSearchRequest; import com.taobao.api.request.SellercatsListGetRequest; import com.taobao.api.request.ShopGetRequest; import com.taobao.api.request.UserGetRequest; import com.taobao.api.response.ItemsSearchResponse; import com.taobao.api.response.SellercatsListGetResponse; import com.taobao.api.response.ShopGetResponse; import com.taobao.api.response.UserGetResponse; public class TaobaoKillParser extends CommonGroupBuyParser { final static String url = "http://gw.api.taobao.com/router/rest"; final static String TAOBAO_MIAOSHA_APPKEY = "12426200"; final static String TAOBAO_MIAOSHA_SECRET = "a673eb7d8a117ea5f24ce60d42fdf972"; final static String TAOBAO_ZHEKOU_APPKEY = "12428257"; final static String TAOBAO_ZHEKOU_SECRET = "7f2ce34d3e564b1cf257d07ba751faae"; final String basicWapSite = "http://a.m.taobao.com/i"; final String basicWebSite = "http://item.taobao.com/item.htm?id="; final String SITE_NAME_TAOBAO = "http://www.taobao.com"; final String SITE_URL = "http://www.taobao.com"; TaobaoClient client; //= new DefaultTaobaoClient(url, appkey, secret); static final ConcurrentHashMap<String, JSONObject> taobaoShopMap = new ConcurrentHashMap<String, JSONObject>(); public static TaobaoClient getTaobaoMiaoshaConfig(){ return new DefaultTaobaoClient(url, TAOBAO_MIAOSHA_APPKEY, TAOBAO_MIAOSHA_SECRET); } public static TaobaoClient getTaobaoZhekouConfig(){ return new DefaultTaobaoClient(url, TAOBAO_ZHEKOU_APPKEY, TAOBAO_ZHEKOU_SECRET); } public TaobaoKillParser(TaobaoClient client){ this.client = client; } @Override public int convertCategory(String category) { return 0; } @Override public boolean disableAddressParsing() { return true; } @Override public String generateWapLoc(String webURL, String imageURL) { return null; } @Override public boolean parseElement(Element root, CommonAddressParser addressParser) { return false; } public static String TAOBAO_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; public static Date parseTaobaoDate(String dateString){ return DateUtil.dateFromStringByFormat(dateString, TAOBAO_DATE_FORMAT, DateUtil.CHINA_TIMEZONE); } public boolean userHasShop(String userNick) { UserGetRequest req = new UserGetRequest(); req.setFields("has_shop"); req.setNick(userNick); UserGetResponse response; try { response = client.execute(req , null); org.jsoup.nodes.Document doc = Jsoup.parse(response.getBody()); String content = doc.text(); JSONObject object = JSONObject.fromObject(content); object = object.getJSONObject("user_get_response"); log.debug("get taobao user = "+object.toString()); if (object != null && object.containsKey("user")){ JSONObject userInfo = object.getJSONObject("user"); boolean hasShop = userInfo.getBoolean("has_shop"); return hasShop; } } catch (ApiException e) { log.error("userHasShop but catch exception = "+e.toString(), e); } return false; } public JSONObject getTaobaoShop(String shopNick){ if (shopNick == null || shopNick.trim().length() == 0){ log.warn("getTaobaoShop but shop nickname is null or empty"); return null; } JSONObject shopInfo = null; if (taobaoShopMap.containsKey(shopNick)){ shopInfo= taobaoShopMap.get(shopNick); } else{ if (userHasShop(shopNick) == false){ log.warn("user " + shopNick + " found but has no shop"); return null; } try { log.info("getTaobaoShop, nick="+shopNick); ShopGetRequest req=new ShopGetRequest(); req.setNick(shopNick); req.setFields("sid,cid,title,nick,created,modified"); ShopGetResponse response = client.execute(req); org.jsoup.nodes.Document doc = Jsoup.parse(response.getBody()); String content = doc.text(); JSONObject object = JSONObject.fromObject(content); object = object.getJSONObject("shop_get_response"); if (object != null && object.containsKey("shop")){ shopInfo = object.getJSONObject("shop"); } if (shopInfo != null){ taobaoShopMap.put(shopNick, shopInfo); } } catch (ApiException e) { log.error("getTaobaoShopWapUrl but catch exception = "+e.toString(), e); } } return shopInfo; } public String getTaobaoShopURL(JSONObject shopObj){ if (shopObj == null) return null; else return "http://shop".concat(shopObj.getString("sid")).concat(".taobao.com"); } public String getTaobaoShopWAPURL(JSONObject shopObj){ if (shopObj == null) return null; else return "http://shop".concat(shopObj.getString("sid")).concat(".m.taobao.com"); } public String getTaobaoShopTitle(JSONObject shopObj){ if (shopObj == null) return null; else return shopObj.getString("title"); } @Override public boolean parse(DBObject task){ String query = (String)task.get(DBConstants.F_TAOBAO_QUERY); int category = ((Double)task.get(DBConstants.F_TAOBAO_CATEGORY)).intValue(); log.info("Start parsing taobao products site, query = "+query+", category = "+category); ItemsSearchRequest req = new ItemsSearchRequest(); req.setFields("num_iid,title,nick,pic_url,cid,price,type,list_time,delist_time,post_fee,score,volume"); req.setQ(query); req.setOrderBy("popularity:desc"); req.setPageSize(200L); try { log.info("[SEND] taobao request, req = "+req.toString()); ItemsSearchResponse response = client.execute(req); // delete the html tag org.jsoup.nodes.Document doc = Jsoup.parse(response.getBody()); String content = doc.text(); log.debug("[RECV] taobao response = "+content); -// content = content.replaceAll("<\\\\/span>", ""); + content = content.replaceAll("<\\\\/span>", ""); // add product site JSONObject object = JSONObject.fromObject(content); object = object.getJSONObject("items_search_response"); if (object == null || !object.containsKey("item_search")){ log.info("search taobao product but no result found"); return true; } object = object.getJSONObject("item_search"); if (object == null || !object.containsKey("items")){ log.info("search taobao product but no result found"); return true; } object = object.getJSONObject("items"); if (object == null || !object.containsKey("item")){ log.info("search taobao product but no result found"); return true; } JSONArray taobaoItems = object.getJSONArray("item"); for (int i=0; i<taobaoItems.size(); i++) { JSONObject taobaoItem = (JSONObject) taobaoItems.get(i); Object id = taobaoItem.get("num_iid"); String image = taobaoItem.getString("pic_url"); String title = taobaoItem.getString("title"); // set Web & WAP URL String wapURL = basicWapSite.concat(""+id).concat(".htm"); String webURL = basicWebSite.concat(""+id); // set start date & end date String startDateString = taobaoItem.getString("list_time"); String endDateString = taobaoItem.getString("delist_time"); Date startDate = parseTaobaoDate(startDateString); Date endDate = parseTaobaoDate(endDateString); // set price & bought info Double price = taobaoItem.getDouble("price"); Double value = taobaoItem.getDouble("price"); int bought = taobaoItem.getInt("volume"); Product product = null; product = ProductManager.findProduct(mongoClient, webURL, DBConstants.C_NATIONWIDE); if (product == null){ // set shop information here to reduce some traffic on invoking taobao shop API String nick = taobaoItem.getString("nick"); JSONObject shopObject = getTaobaoShop(nick); String siteName = getTaobaoShopTitle(shopObject); String siteURL = getTaobaoShopWAPURL(shopObject); if (StringUtil.isEmpty(siteName) || StringUtil.isEmpty(siteURL)){ log.info("fail to create taobao product due to site name/URL empty, nick = "+nick); continue; } boolean result = true; product = new Product(); result = product.setMandantoryFields(DBConstants.C_NATIONWIDE, webURL, image, title, startDate, endDate, price, value, bought, siteId, siteName, siteURL); product.setWapLoc(wapURL); product.setCategory(category); product.setProductType(DBConstants.C_PRODUCT_TYPE_TAOBAO); if (!result){ log.info("fail to create taobao product on setMandantoryFields, product = "+product.toString()); continue; } log.info("Create taobao product = " + product.toString()); result = ProductManager.createProduct(mongoClient, product); if (!result){ log.info("fail to create taobao product on final creation, product = "+product.toString()); continue; } ProductManager.createSolrIndex(product, true); } else{ // update product if it's changed boolean hasChange = false; if (price != product.getPrice()){ product.setPrice(price); product.setValue(value); hasChange = true; } if (bought != product.getBought()){ product.setBought(bought); product.calcAndSetTopScore(bought, startDate); hasChange = true; } if (hasChange){ log.debug("product "+product.getTitle()+" change, update DB"); ProductManager.save(mongoClient, product); } else{ log.debug("product "+product.getTitle()+" found, no change"); } } } SolrClient.commit(); } catch (ApiException e) { log.error("execute taobao kill parser, but catch taobao API exception = " + e.toString(), e); } catch (Exception e) { log.error("execute taobao kill parser, but catch exception = " + e.toString(), e); } log.info("Finish parsing all taobao products site, query = "+query+", category = "+category); return true; } }
true
true
public boolean parse(DBObject task){ String query = (String)task.get(DBConstants.F_TAOBAO_QUERY); int category = ((Double)task.get(DBConstants.F_TAOBAO_CATEGORY)).intValue(); log.info("Start parsing taobao products site, query = "+query+", category = "+category); ItemsSearchRequest req = new ItemsSearchRequest(); req.setFields("num_iid,title,nick,pic_url,cid,price,type,list_time,delist_time,post_fee,score,volume"); req.setQ(query); req.setOrderBy("popularity:desc"); req.setPageSize(200L); try { log.info("[SEND] taobao request, req = "+req.toString()); ItemsSearchResponse response = client.execute(req); // delete the html tag org.jsoup.nodes.Document doc = Jsoup.parse(response.getBody()); String content = doc.text(); log.debug("[RECV] taobao response = "+content); // content = content.replaceAll("<\\\\/span>", ""); // add product site JSONObject object = JSONObject.fromObject(content); object = object.getJSONObject("items_search_response"); if (object == null || !object.containsKey("item_search")){ log.info("search taobao product but no result found"); return true; } object = object.getJSONObject("item_search"); if (object == null || !object.containsKey("items")){ log.info("search taobao product but no result found"); return true; } object = object.getJSONObject("items"); if (object == null || !object.containsKey("item")){ log.info("search taobao product but no result found"); return true; } JSONArray taobaoItems = object.getJSONArray("item"); for (int i=0; i<taobaoItems.size(); i++) { JSONObject taobaoItem = (JSONObject) taobaoItems.get(i); Object id = taobaoItem.get("num_iid"); String image = taobaoItem.getString("pic_url"); String title = taobaoItem.getString("title"); // set Web & WAP URL String wapURL = basicWapSite.concat(""+id).concat(".htm"); String webURL = basicWebSite.concat(""+id); // set start date & end date String startDateString = taobaoItem.getString("list_time"); String endDateString = taobaoItem.getString("delist_time"); Date startDate = parseTaobaoDate(startDateString); Date endDate = parseTaobaoDate(endDateString); // set price & bought info Double price = taobaoItem.getDouble("price"); Double value = taobaoItem.getDouble("price"); int bought = taobaoItem.getInt("volume"); Product product = null; product = ProductManager.findProduct(mongoClient, webURL, DBConstants.C_NATIONWIDE); if (product == null){ // set shop information here to reduce some traffic on invoking taobao shop API String nick = taobaoItem.getString("nick"); JSONObject shopObject = getTaobaoShop(nick); String siteName = getTaobaoShopTitle(shopObject); String siteURL = getTaobaoShopWAPURL(shopObject); if (StringUtil.isEmpty(siteName) || StringUtil.isEmpty(siteURL)){ log.info("fail to create taobao product due to site name/URL empty, nick = "+nick); continue; } boolean result = true; product = new Product(); result = product.setMandantoryFields(DBConstants.C_NATIONWIDE, webURL, image, title, startDate, endDate, price, value, bought, siteId, siteName, siteURL); product.setWapLoc(wapURL); product.setCategory(category); product.setProductType(DBConstants.C_PRODUCT_TYPE_TAOBAO); if (!result){ log.info("fail to create taobao product on setMandantoryFields, product = "+product.toString()); continue; } log.info("Create taobao product = " + product.toString()); result = ProductManager.createProduct(mongoClient, product); if (!result){ log.info("fail to create taobao product on final creation, product = "+product.toString()); continue; } ProductManager.createSolrIndex(product, true); } else{ // update product if it's changed boolean hasChange = false; if (price != product.getPrice()){ product.setPrice(price); product.setValue(value); hasChange = true; } if (bought != product.getBought()){ product.setBought(bought); product.calcAndSetTopScore(bought, startDate); hasChange = true; } if (hasChange){ log.debug("product "+product.getTitle()+" change, update DB"); ProductManager.save(mongoClient, product); } else{ log.debug("product "+product.getTitle()+" found, no change"); } } } SolrClient.commit(); } catch (ApiException e) { log.error("execute taobao kill parser, but catch taobao API exception = " + e.toString(), e); } catch (Exception e) { log.error("execute taobao kill parser, but catch exception = " + e.toString(), e); } log.info("Finish parsing all taobao products site, query = "+query+", category = "+category); return true; }
public boolean parse(DBObject task){ String query = (String)task.get(DBConstants.F_TAOBAO_QUERY); int category = ((Double)task.get(DBConstants.F_TAOBAO_CATEGORY)).intValue(); log.info("Start parsing taobao products site, query = "+query+", category = "+category); ItemsSearchRequest req = new ItemsSearchRequest(); req.setFields("num_iid,title,nick,pic_url,cid,price,type,list_time,delist_time,post_fee,score,volume"); req.setQ(query); req.setOrderBy("popularity:desc"); req.setPageSize(200L); try { log.info("[SEND] taobao request, req = "+req.toString()); ItemsSearchResponse response = client.execute(req); // delete the html tag org.jsoup.nodes.Document doc = Jsoup.parse(response.getBody()); String content = doc.text(); log.debug("[RECV] taobao response = "+content); content = content.replaceAll("<\\\\/span>", ""); // add product site JSONObject object = JSONObject.fromObject(content); object = object.getJSONObject("items_search_response"); if (object == null || !object.containsKey("item_search")){ log.info("search taobao product but no result found"); return true; } object = object.getJSONObject("item_search"); if (object == null || !object.containsKey("items")){ log.info("search taobao product but no result found"); return true; } object = object.getJSONObject("items"); if (object == null || !object.containsKey("item")){ log.info("search taobao product but no result found"); return true; } JSONArray taobaoItems = object.getJSONArray("item"); for (int i=0; i<taobaoItems.size(); i++) { JSONObject taobaoItem = (JSONObject) taobaoItems.get(i); Object id = taobaoItem.get("num_iid"); String image = taobaoItem.getString("pic_url"); String title = taobaoItem.getString("title"); // set Web & WAP URL String wapURL = basicWapSite.concat(""+id).concat(".htm"); String webURL = basicWebSite.concat(""+id); // set start date & end date String startDateString = taobaoItem.getString("list_time"); String endDateString = taobaoItem.getString("delist_time"); Date startDate = parseTaobaoDate(startDateString); Date endDate = parseTaobaoDate(endDateString); // set price & bought info Double price = taobaoItem.getDouble("price"); Double value = taobaoItem.getDouble("price"); int bought = taobaoItem.getInt("volume"); Product product = null; product = ProductManager.findProduct(mongoClient, webURL, DBConstants.C_NATIONWIDE); if (product == null){ // set shop information here to reduce some traffic on invoking taobao shop API String nick = taobaoItem.getString("nick"); JSONObject shopObject = getTaobaoShop(nick); String siteName = getTaobaoShopTitle(shopObject); String siteURL = getTaobaoShopWAPURL(shopObject); if (StringUtil.isEmpty(siteName) || StringUtil.isEmpty(siteURL)){ log.info("fail to create taobao product due to site name/URL empty, nick = "+nick); continue; } boolean result = true; product = new Product(); result = product.setMandantoryFields(DBConstants.C_NATIONWIDE, webURL, image, title, startDate, endDate, price, value, bought, siteId, siteName, siteURL); product.setWapLoc(wapURL); product.setCategory(category); product.setProductType(DBConstants.C_PRODUCT_TYPE_TAOBAO); if (!result){ log.info("fail to create taobao product on setMandantoryFields, product = "+product.toString()); continue; } log.info("Create taobao product = " + product.toString()); result = ProductManager.createProduct(mongoClient, product); if (!result){ log.info("fail to create taobao product on final creation, product = "+product.toString()); continue; } ProductManager.createSolrIndex(product, true); } else{ // update product if it's changed boolean hasChange = false; if (price != product.getPrice()){ product.setPrice(price); product.setValue(value); hasChange = true; } if (bought != product.getBought()){ product.setBought(bought); product.calcAndSetTopScore(bought, startDate); hasChange = true; } if (hasChange){ log.debug("product "+product.getTitle()+" change, update DB"); ProductManager.save(mongoClient, product); } else{ log.debug("product "+product.getTitle()+" found, no change"); } } } SolrClient.commit(); } catch (ApiException e) { log.error("execute taobao kill parser, but catch taobao API exception = " + e.toString(), e); } catch (Exception e) { log.error("execute taobao kill parser, but catch exception = " + e.toString(), e); } log.info("Finish parsing all taobao products site, query = "+query+", category = "+category); return true; }
diff --git a/src/main/java/org/basex/core/Lock.java b/src/main/java/org/basex/core/Lock.java index c0835b17e..7f7756f66 100644 --- a/src/main/java/org/basex/core/Lock.java +++ b/src/main/java/org/basex/core/Lock.java @@ -1,154 +1,156 @@ package org.basex.core; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.basex.util.Util; /** * Management of executing read/write processes. Multiple readers, single * writers (readers/writer lock). * * @author BaseX Team 2005-11, ISC License * @author Andreas Weiler */ public final class Lock { /** Flag for skipping all locking tests. */ private static final boolean SKIP = false; /** List of waiting processes for writers or reading groups. */ private final List<Resource> list = Collections.synchronizedList(new ArrayList<Resource>()); /** Server Context. */ private final Context ctx; /** States of locking. */ private static enum State { /** Idle state. */ IDLE, /** Read state. */ READ, /** Write state. */ WRITE } /** State of the lock. */ private State state = State.IDLE; /** Number of active readers. */ private int activeR; /** * Default constructor. * @param c context */ public Lock(final Context c) { ctx = c; } /** * Modifications before executing a command. * @param w writing flag */ public void register(final boolean w) { if(SKIP) return; if(w) { - if(state == State.IDLE) { - state = State.WRITE; - return; + synchronized(this) { + if(state == State.IDLE) { + state = State.WRITE; + return; + } } // exclusive lock final Resource lx = new Resource(false); synchronized(lx) { list.add(lx); while(lx.locked) { try { lx.wait(); } catch(final InterruptedException ex) { Util.stack(ex); } } state = State.WRITE; } } else { synchronized(this) { final int p = Math.max(ctx.prop.num(Prop.PARALLEL), 1); if(state != State.WRITE && list.size() == 0 && activeR < p) { state = State.READ; ++activeR; return; } } // shared lock final Resource ls = new Resource(true); synchronized(ls) { list.add(ls); while(ls.locked) { try { ls.wait(); } catch(final InterruptedException ex) { Util.stack(ex); } } state = State.READ; synchronized(this) { ++activeR; } } } } /** * Modifications after executing a command. * @param w writing flag */ public synchronized void unregister(final boolean w) { if(SKIP) return; if(!w) --activeR; if(list.size() > 0) { if(list.get(0).reader) { notifyReaders(); } else { notifyNext(); } } else { state = State.IDLE; } } /** * Notifies all waiting readers. */ private void notifyReaders() { final int p = Math.max(ctx.prop.num(Prop.PARALLEL), 1); int c = activeR; do { notifyNext(); } while(++c < p && list.size() > 0 && list.get(0).reader); } /** * Notifies the next process. */ private void notifyNext() { final Resource l = list.remove(0); synchronized(l) { l.locked = false; l.notifyAll(); } } /** Inner class for a locking object. */ private static class Resource { /** Reader flag. */ final boolean reader; /** Flag if lock can start. */ boolean locked = true; /** * Standard constructor. * @param r reader flag */ Resource(final boolean r) { reader = r; } } }
true
true
public void register(final boolean w) { if(SKIP) return; if(w) { if(state == State.IDLE) { state = State.WRITE; return; } // exclusive lock final Resource lx = new Resource(false); synchronized(lx) { list.add(lx); while(lx.locked) { try { lx.wait(); } catch(final InterruptedException ex) { Util.stack(ex); } } state = State.WRITE; } } else { synchronized(this) { final int p = Math.max(ctx.prop.num(Prop.PARALLEL), 1); if(state != State.WRITE && list.size() == 0 && activeR < p) { state = State.READ; ++activeR; return; } } // shared lock final Resource ls = new Resource(true); synchronized(ls) { list.add(ls); while(ls.locked) { try { ls.wait(); } catch(final InterruptedException ex) { Util.stack(ex); } } state = State.READ; synchronized(this) { ++activeR; } } } }
public void register(final boolean w) { if(SKIP) return; if(w) { synchronized(this) { if(state == State.IDLE) { state = State.WRITE; return; } } // exclusive lock final Resource lx = new Resource(false); synchronized(lx) { list.add(lx); while(lx.locked) { try { lx.wait(); } catch(final InterruptedException ex) { Util.stack(ex); } } state = State.WRITE; } } else { synchronized(this) { final int p = Math.max(ctx.prop.num(Prop.PARALLEL), 1); if(state != State.WRITE && list.size() == 0 && activeR < p) { state = State.READ; ++activeR; return; } } // shared lock final Resource ls = new Resource(true); synchronized(ls) { list.add(ls); while(ls.locked) { try { ls.wait(); } catch(final InterruptedException ex) { Util.stack(ex); } } state = State.READ; synchronized(this) { ++activeR; } } } }
diff --git a/test/com/eteks/sweethome3d/junit/BackgroundImageWizardTest.java b/test/com/eteks/sweethome3d/junit/BackgroundImageWizardTest.java index 4ed0fb55..562650ed 100644 --- a/test/com/eteks/sweethome3d/junit/BackgroundImageWizardTest.java +++ b/test/com/eteks/sweethome3d/junit/BackgroundImageWizardTest.java @@ -1,228 +1,228 @@ /* * BackgroundImageWizardTest.java 22 sept. 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.junit; import java.awt.KeyboardFocusManager; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.net.URL; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JSpinner; import junit.extensions.abbot.ComponentTestFixture; import abbot.finder.AWTHierarchy; import abbot.finder.ComponentSearchException; import abbot.tester.JComponentTester; import com.eteks.sweethome3d.io.DefaultUserPreferences; import com.eteks.sweethome3d.model.BackgroundImage; import com.eteks.sweethome3d.model.Content; import com.eteks.sweethome3d.model.Home; import com.eteks.sweethome3d.model.LengthUnit; import com.eteks.sweethome3d.model.RecorderException; import com.eteks.sweethome3d.model.UserPreferences; import com.eteks.sweethome3d.swing.BackgroundImageWizardStepsPanel; import com.eteks.sweethome3d.swing.HomePane; import com.eteks.sweethome3d.swing.SwingViewFactory; import com.eteks.sweethome3d.swing.WizardPane; import com.eteks.sweethome3d.tools.URLContent; import com.eteks.sweethome3d.viewcontroller.BackgroundImageWizardController; import com.eteks.sweethome3d.viewcontroller.ContentManager; import com.eteks.sweethome3d.viewcontroller.HomeController; import com.eteks.sweethome3d.viewcontroller.HomeView; import com.eteks.sweethome3d.viewcontroller.View; import com.eteks.sweethome3d.viewcontroller.ViewFactory; /** * Tests background image wizard. * @author Emmanuel Puybaret */ public class BackgroundImageWizardTest extends ComponentTestFixture { public void testBackgroundImageWizard() throws ComponentSearchException, InterruptedException, NoSuchFieldException, IllegalAccessException, InvocationTargetException { final UserPreferences preferences = new DefaultUserPreferences(); // Ensure we use centimeter unit preferences.setUnit(LengthUnit.CENTIMETER); final URL testedImageName = BackgroundImageWizardTest.class.getResource("resources/test.png"); // Create a dummy content manager final ContentManager contentManager = new ContentManager() { public Content getContent(String contentName) throws RecorderException { try { // Let's consider contentName is a URL return new URLContent(new URL(contentName)); } catch (IOException ex) { fail(); return null; } } public String getPresentationName(String contentName, ContentType contentType) { return "test"; } public boolean isAcceptable(String contentName, ContentType contentType) { return true; } public String showOpenDialog(View parentView, String dialogTitle, ContentType contentType) { // Return tested model name URL return testedImageName.toString(); } public String showSaveDialog(View parentView, String dialogTitle, ContentType contentType, String name) { return null; } }; Home home = new Home(); ViewFactory viewFactory = new SwingViewFactory(); final HomeController controller = new HomeController(home, preferences, viewFactory, contentManager); final JComponent homeView = (JComponent)controller.getView(); // 1. Create a frame that displays a home view JFrame frame = new JFrame("Background Image Wizard Test"); frame.add(homeView); frame.pack(); // Show home plan frame showWindow(frame); JComponentTester tester = new JComponentTester(); tester.waitForIdle(); // Check home background image is empty assertEquals("Home background image isn't empty", null, home.getBackgroundImage()); // 2. Open wizard to import a background image runAction(controller, HomeView.ActionType.IMPORT_BACKGROUND_IMAGE, tester); // Wait for import furniture view to be shown tester.waitForFrameShowing(new AWTHierarchy(), preferences.getLocalizedString( BackgroundImageWizardController.class, "wizard.title")); // Check dialog box is displayed JDialog wizardDialog = (JDialog)TestUtilities.findComponent(frame, JDialog.class); assertTrue("Wizard view dialog not showing", wizardDialog.isShowing()); // Retrieve ImportedFurnitureWizardStepsPanel components BackgroundImageWizardStepsPanel panel = (BackgroundImageWizardStepsPanel)TestUtilities.findComponent( wizardDialog, BackgroundImageWizardStepsPanel.class); JButton imageChoiceOrChangeButton = (JButton)TestUtilities.getField(panel, "imageChoiceOrChangeButton"); JSpinner scaleDistanceSpinner = (JSpinner)TestUtilities.getField(panel, "scaleDistanceSpinner"); JSpinner xOriginSpinner = (JSpinner)TestUtilities.getField(panel, "xOriginSpinner"); JSpinner yOriginSpinner = (JSpinner)TestUtilities.getField(panel, "yOriginSpinner"); // Check current step is image assertStepShowing(panel, true, false, false); // 3. Choose tested image String imageChoiceOrChangeButtonText = imageChoiceOrChangeButton.getText(); tester.click(imageChoiceOrChangeButton); - // Wait 100 s to let time to Java to load the image + // Wait 100 ms to let time to Java to load the image Thread.sleep(100); // Check choice button text changed assertFalse("Choice button text didn't change", imageChoiceOrChangeButtonText.equals(imageChoiceOrChangeButton.getText())); // Click on next button WizardPane view = (WizardPane)TestUtilities.findComponent(wizardDialog, WizardPane.class); // Retrieve wizard view next button final JButton nextFinishOptionButton = (JButton)TestUtilities.getField(view, "nextFinishOptionButton"); assertTrue("Next button isn't enabled", nextFinishOptionButton.isEnabled()); tester.click(nextFinishOptionButton); // Check current step is scale assertStepShowing(panel, false, true, false); // 4. Check scale distance spinner value is empty assertEquals("Scale distance spinner isn't empty", null, scaleDistanceSpinner.getValue()); assertFalse("Next button is enabled", nextFinishOptionButton.isEnabled()); // Check scale spinner field has focus tester.waitForIdle(); assertSame("Scale spinner doesn't have focus", ((JSpinner.DefaultEditor)scaleDistanceSpinner.getEditor()).getTextField(), KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner()); // Enter as scale tester.actionKeyString("100"); // Check next button is enabled assertTrue("Next button isn't enabled", nextFinishOptionButton.isEnabled()); tester.click(nextFinishOptionButton); // Check current step is origin assertStepShowing(panel, false, false, true); // 5. Check origin x and y spinners value is 0 assertEquals("Wrong origin x spinner value", new Float(0), xOriginSpinner.getValue()); assertEquals("Wrong origin y spinner value", new Float(0), yOriginSpinner.getValue()); assertTrue("Next button isn't enabled", nextFinishOptionButton.isEnabled()); tester.waitForIdle(); assertSame("Origin x spinner doesn't have focus", ((JSpinner.DefaultEditor)xOriginSpinner.getEditor()).getTextField(), KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner()); // Change origin tester.actionKeyString("10"); assertEquals("Wrong origin x spinner value", 10f, xOriginSpinner.getValue()); tester.click(nextFinishOptionButton); // Check home has a background image BackgroundImage backgroundImage = home.getBackgroundImage(); assertTrue("No background image in home", backgroundImage != null); assertEquals("Background image wrong scale", 100f, backgroundImage.getScaleDistance()); assertEquals("Background image wrong x origin", 10f, backgroundImage.getXOrigin()); assertEquals("Background image wrong y origin", 0f, backgroundImage.getYOrigin()); // 6. Undo background image choice in home runAction(controller, HomeView.ActionType.UNDO, tester); // Check home background image is empty assertEquals("Home background image isn't empty", null, home.getBackgroundImage()); // Redo runAction(controller, HomeView.ActionType.REDO, tester); // Check home background image is back assertSame("No background image in home", backgroundImage, home.getBackgroundImage()); // 7. Delete background image runAction(controller, HomeView.ActionType.DELETE_BACKGROUND_IMAGE, tester); // Check home background image is empty assertEquals("Home background image isn't empty", null, home.getBackgroundImage()); } /** * Asserts if each <code>panel</code> step preview component is showing or not. */ private void assertStepShowing(BackgroundImageWizardStepsPanel panel, boolean imageStepShwing, boolean scaleStepShowing, boolean originStepShowing) throws NoSuchFieldException, IllegalAccessException { assertEquals("Wrong image step visibility", imageStepShwing, ((JComponent)TestUtilities.getField(panel, "imageChoicePreviewComponent")).isShowing()); assertEquals("Wrong scale step visibility", scaleStepShowing, ((JComponent)TestUtilities.getField(panel, "scalePreviewComponent")).isShowing()); assertEquals("Wrong origin step visibility", originStepShowing, ((JComponent)TestUtilities.getField(panel, "originPreviewComponent")).isShowing()); } /** * Runs <code>actionPerformed</code> method matching <code>actionType</code> * in <code>controller</code> view. */ private void runAction(final HomeController controller, final HomePane.ActionType actionType, JComponentTester tester) { tester.invokeAndWait(new Runnable() { public void run() { ((JComponent)controller.getView()).getActionMap().get(actionType).actionPerformed(null); } }); } }
true
true
public void testBackgroundImageWizard() throws ComponentSearchException, InterruptedException, NoSuchFieldException, IllegalAccessException, InvocationTargetException { final UserPreferences preferences = new DefaultUserPreferences(); // Ensure we use centimeter unit preferences.setUnit(LengthUnit.CENTIMETER); final URL testedImageName = BackgroundImageWizardTest.class.getResource("resources/test.png"); // Create a dummy content manager final ContentManager contentManager = new ContentManager() { public Content getContent(String contentName) throws RecorderException { try { // Let's consider contentName is a URL return new URLContent(new URL(contentName)); } catch (IOException ex) { fail(); return null; } } public String getPresentationName(String contentName, ContentType contentType) { return "test"; } public boolean isAcceptable(String contentName, ContentType contentType) { return true; } public String showOpenDialog(View parentView, String dialogTitle, ContentType contentType) { // Return tested model name URL return testedImageName.toString(); } public String showSaveDialog(View parentView, String dialogTitle, ContentType contentType, String name) { return null; } }; Home home = new Home(); ViewFactory viewFactory = new SwingViewFactory(); final HomeController controller = new HomeController(home, preferences, viewFactory, contentManager); final JComponent homeView = (JComponent)controller.getView(); // 1. Create a frame that displays a home view JFrame frame = new JFrame("Background Image Wizard Test"); frame.add(homeView); frame.pack(); // Show home plan frame showWindow(frame); JComponentTester tester = new JComponentTester(); tester.waitForIdle(); // Check home background image is empty assertEquals("Home background image isn't empty", null, home.getBackgroundImage()); // 2. Open wizard to import a background image runAction(controller, HomeView.ActionType.IMPORT_BACKGROUND_IMAGE, tester); // Wait for import furniture view to be shown tester.waitForFrameShowing(new AWTHierarchy(), preferences.getLocalizedString( BackgroundImageWizardController.class, "wizard.title")); // Check dialog box is displayed JDialog wizardDialog = (JDialog)TestUtilities.findComponent(frame, JDialog.class); assertTrue("Wizard view dialog not showing", wizardDialog.isShowing()); // Retrieve ImportedFurnitureWizardStepsPanel components BackgroundImageWizardStepsPanel panel = (BackgroundImageWizardStepsPanel)TestUtilities.findComponent( wizardDialog, BackgroundImageWizardStepsPanel.class); JButton imageChoiceOrChangeButton = (JButton)TestUtilities.getField(panel, "imageChoiceOrChangeButton"); JSpinner scaleDistanceSpinner = (JSpinner)TestUtilities.getField(panel, "scaleDistanceSpinner"); JSpinner xOriginSpinner = (JSpinner)TestUtilities.getField(panel, "xOriginSpinner"); JSpinner yOriginSpinner = (JSpinner)TestUtilities.getField(panel, "yOriginSpinner"); // Check current step is image assertStepShowing(panel, true, false, false); // 3. Choose tested image String imageChoiceOrChangeButtonText = imageChoiceOrChangeButton.getText(); tester.click(imageChoiceOrChangeButton); // Wait 100 s to let time to Java to load the image Thread.sleep(100); // Check choice button text changed assertFalse("Choice button text didn't change", imageChoiceOrChangeButtonText.equals(imageChoiceOrChangeButton.getText())); // Click on next button WizardPane view = (WizardPane)TestUtilities.findComponent(wizardDialog, WizardPane.class); // Retrieve wizard view next button final JButton nextFinishOptionButton = (JButton)TestUtilities.getField(view, "nextFinishOptionButton"); assertTrue("Next button isn't enabled", nextFinishOptionButton.isEnabled()); tester.click(nextFinishOptionButton); // Check current step is scale assertStepShowing(panel, false, true, false); // 4. Check scale distance spinner value is empty assertEquals("Scale distance spinner isn't empty", null, scaleDistanceSpinner.getValue()); assertFalse("Next button is enabled", nextFinishOptionButton.isEnabled()); // Check scale spinner field has focus tester.waitForIdle(); assertSame("Scale spinner doesn't have focus", ((JSpinner.DefaultEditor)scaleDistanceSpinner.getEditor()).getTextField(), KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner()); // Enter as scale tester.actionKeyString("100"); // Check next button is enabled assertTrue("Next button isn't enabled", nextFinishOptionButton.isEnabled()); tester.click(nextFinishOptionButton); // Check current step is origin assertStepShowing(panel, false, false, true); // 5. Check origin x and y spinners value is 0 assertEquals("Wrong origin x spinner value", new Float(0), xOriginSpinner.getValue()); assertEquals("Wrong origin y spinner value", new Float(0), yOriginSpinner.getValue()); assertTrue("Next button isn't enabled", nextFinishOptionButton.isEnabled()); tester.waitForIdle(); assertSame("Origin x spinner doesn't have focus", ((JSpinner.DefaultEditor)xOriginSpinner.getEditor()).getTextField(), KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner()); // Change origin tester.actionKeyString("10"); assertEquals("Wrong origin x spinner value", 10f, xOriginSpinner.getValue()); tester.click(nextFinishOptionButton); // Check home has a background image BackgroundImage backgroundImage = home.getBackgroundImage(); assertTrue("No background image in home", backgroundImage != null); assertEquals("Background image wrong scale", 100f, backgroundImage.getScaleDistance()); assertEquals("Background image wrong x origin", 10f, backgroundImage.getXOrigin()); assertEquals("Background image wrong y origin", 0f, backgroundImage.getYOrigin()); // 6. Undo background image choice in home runAction(controller, HomeView.ActionType.UNDO, tester); // Check home background image is empty assertEquals("Home background image isn't empty", null, home.getBackgroundImage()); // Redo runAction(controller, HomeView.ActionType.REDO, tester); // Check home background image is back assertSame("No background image in home", backgroundImage, home.getBackgroundImage()); // 7. Delete background image runAction(controller, HomeView.ActionType.DELETE_BACKGROUND_IMAGE, tester); // Check home background image is empty assertEquals("Home background image isn't empty", null, home.getBackgroundImage()); }
public void testBackgroundImageWizard() throws ComponentSearchException, InterruptedException, NoSuchFieldException, IllegalAccessException, InvocationTargetException { final UserPreferences preferences = new DefaultUserPreferences(); // Ensure we use centimeter unit preferences.setUnit(LengthUnit.CENTIMETER); final URL testedImageName = BackgroundImageWizardTest.class.getResource("resources/test.png"); // Create a dummy content manager final ContentManager contentManager = new ContentManager() { public Content getContent(String contentName) throws RecorderException { try { // Let's consider contentName is a URL return new URLContent(new URL(contentName)); } catch (IOException ex) { fail(); return null; } } public String getPresentationName(String contentName, ContentType contentType) { return "test"; } public boolean isAcceptable(String contentName, ContentType contentType) { return true; } public String showOpenDialog(View parentView, String dialogTitle, ContentType contentType) { // Return tested model name URL return testedImageName.toString(); } public String showSaveDialog(View parentView, String dialogTitle, ContentType contentType, String name) { return null; } }; Home home = new Home(); ViewFactory viewFactory = new SwingViewFactory(); final HomeController controller = new HomeController(home, preferences, viewFactory, contentManager); final JComponent homeView = (JComponent)controller.getView(); // 1. Create a frame that displays a home view JFrame frame = new JFrame("Background Image Wizard Test"); frame.add(homeView); frame.pack(); // Show home plan frame showWindow(frame); JComponentTester tester = new JComponentTester(); tester.waitForIdle(); // Check home background image is empty assertEquals("Home background image isn't empty", null, home.getBackgroundImage()); // 2. Open wizard to import a background image runAction(controller, HomeView.ActionType.IMPORT_BACKGROUND_IMAGE, tester); // Wait for import furniture view to be shown tester.waitForFrameShowing(new AWTHierarchy(), preferences.getLocalizedString( BackgroundImageWizardController.class, "wizard.title")); // Check dialog box is displayed JDialog wizardDialog = (JDialog)TestUtilities.findComponent(frame, JDialog.class); assertTrue("Wizard view dialog not showing", wizardDialog.isShowing()); // Retrieve ImportedFurnitureWizardStepsPanel components BackgroundImageWizardStepsPanel panel = (BackgroundImageWizardStepsPanel)TestUtilities.findComponent( wizardDialog, BackgroundImageWizardStepsPanel.class); JButton imageChoiceOrChangeButton = (JButton)TestUtilities.getField(panel, "imageChoiceOrChangeButton"); JSpinner scaleDistanceSpinner = (JSpinner)TestUtilities.getField(panel, "scaleDistanceSpinner"); JSpinner xOriginSpinner = (JSpinner)TestUtilities.getField(panel, "xOriginSpinner"); JSpinner yOriginSpinner = (JSpinner)TestUtilities.getField(panel, "yOriginSpinner"); // Check current step is image assertStepShowing(panel, true, false, false); // 3. Choose tested image String imageChoiceOrChangeButtonText = imageChoiceOrChangeButton.getText(); tester.click(imageChoiceOrChangeButton); // Wait 100 ms to let time to Java to load the image Thread.sleep(100); // Check choice button text changed assertFalse("Choice button text didn't change", imageChoiceOrChangeButtonText.equals(imageChoiceOrChangeButton.getText())); // Click on next button WizardPane view = (WizardPane)TestUtilities.findComponent(wizardDialog, WizardPane.class); // Retrieve wizard view next button final JButton nextFinishOptionButton = (JButton)TestUtilities.getField(view, "nextFinishOptionButton"); assertTrue("Next button isn't enabled", nextFinishOptionButton.isEnabled()); tester.click(nextFinishOptionButton); // Check current step is scale assertStepShowing(panel, false, true, false); // 4. Check scale distance spinner value is empty assertEquals("Scale distance spinner isn't empty", null, scaleDistanceSpinner.getValue()); assertFalse("Next button is enabled", nextFinishOptionButton.isEnabled()); // Check scale spinner field has focus tester.waitForIdle(); assertSame("Scale spinner doesn't have focus", ((JSpinner.DefaultEditor)scaleDistanceSpinner.getEditor()).getTextField(), KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner()); // Enter as scale tester.actionKeyString("100"); // Check next button is enabled assertTrue("Next button isn't enabled", nextFinishOptionButton.isEnabled()); tester.click(nextFinishOptionButton); // Check current step is origin assertStepShowing(panel, false, false, true); // 5. Check origin x and y spinners value is 0 assertEquals("Wrong origin x spinner value", new Float(0), xOriginSpinner.getValue()); assertEquals("Wrong origin y spinner value", new Float(0), yOriginSpinner.getValue()); assertTrue("Next button isn't enabled", nextFinishOptionButton.isEnabled()); tester.waitForIdle(); assertSame("Origin x spinner doesn't have focus", ((JSpinner.DefaultEditor)xOriginSpinner.getEditor()).getTextField(), KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner()); // Change origin tester.actionKeyString("10"); assertEquals("Wrong origin x spinner value", 10f, xOriginSpinner.getValue()); tester.click(nextFinishOptionButton); // Check home has a background image BackgroundImage backgroundImage = home.getBackgroundImage(); assertTrue("No background image in home", backgroundImage != null); assertEquals("Background image wrong scale", 100f, backgroundImage.getScaleDistance()); assertEquals("Background image wrong x origin", 10f, backgroundImage.getXOrigin()); assertEquals("Background image wrong y origin", 0f, backgroundImage.getYOrigin()); // 6. Undo background image choice in home runAction(controller, HomeView.ActionType.UNDO, tester); // Check home background image is empty assertEquals("Home background image isn't empty", null, home.getBackgroundImage()); // Redo runAction(controller, HomeView.ActionType.REDO, tester); // Check home background image is back assertSame("No background image in home", backgroundImage, home.getBackgroundImage()); // 7. Delete background image runAction(controller, HomeView.ActionType.DELETE_BACKGROUND_IMAGE, tester); // Check home background image is empty assertEquals("Home background image isn't empty", null, home.getBackgroundImage()); }
diff --git a/source/java/org/encuestame/web/beans/survey/tweetpoll/CreateTweetPollBean.java b/source/java/org/encuestame/web/beans/survey/tweetpoll/CreateTweetPollBean.java index ee8246647..a967bb28c 100644 --- a/source/java/org/encuestame/web/beans/survey/tweetpoll/CreateTweetPollBean.java +++ b/source/java/org/encuestame/web/beans/survey/tweetpoll/CreateTweetPollBean.java @@ -1,251 +1,252 @@ /* ************************************************************************************ * Copyright (C) 2001-2010 encuestame: system online surveys Copyright (C) 2010 * encuestame Development Team. * Licensed under the Apache Software License version 2.0 * 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.encuestame.web.beans.survey.tweetpoll; import java.util.ArrayList; import java.util.Date; import org.encuestame.core.exception.EnMeExpcetion; import org.encuestame.core.persistence.pojo.SecUsers; import org.encuestame.core.service.ISurveyService; import org.encuestame.web.beans.MasterBean; import org.encuestame.web.beans.survey.UnitAnswersBean; import org.encuestame.web.beans.survey.UnitQuestionBean; import twitter4j.Status; /** * Create Tweet Poll. * @author Picado, Juan [email protected] * @since Feb 13, 2010 11:36:48 PM * @version $Id$ */ public class CreateTweetPollBean extends MasterBean { /** {@link UnitTweetPoll}. **/ private UnitTweetPoll unitTweetPoll = new UnitTweetPoll(); /** {@link UnitAnswersBean}. **/ private UnitAnswersBean answersBean = new UnitAnswersBean(); /** {@link UnitQuestionBean}. **/ private UnitQuestionBean questionBean = new UnitQuestionBean(); /** Resume Tweet. **/ private String resumeTweet; /** Count Tweet. **/ private Integer countTweet; /** * Constructor. */ public CreateTweetPollBean() { } /** * Save Question. */ public void saveQuestion(){ try{ log.info("Question Name "+questionBean.getQuestionName()); this.questionBean.setUserId(getUsernameByName().getSecUser().getUid()); getUnitTweetPoll().setQuestionBean(questionBean); addInfoMessage("Question Saved.", ""); setResumeTweet(this.questionBean.getQuestionName()); //TODO: refresh url }catch (Exception e) { addErrorMessage("Error save question", ""); log.error(e); e.printStackTrace(); } } /** * Create Short Sumilate Url. * @param answer answer */ public void createShortSimulateUrl(final UnitAnswersBean answer){ try{ final ISurveyService survey = getServicemanager().getApplicationServices().getSecurityService().getSurveyService(); log.info("survey service "+survey); final String url = survey.getTwitterService().getTinyUrl("http://www.google.es"); log.info("tiny url "+url); StringBuffer answerString = new StringBuffer(getResumeTweet()); answerString.append(" "); answerString.append(answer.getAnswers()); answerString.append(" "); answerString.append(url); log.info("answerString "+answerString); setResumeTweet(answerString.toString()); } catch (Exception e) { log.error(e); e.printStackTrace(); addErrorMessage("Error to create Short Simulate Url", ""); } } /** * Add answer to question. **/ public void addAnswer(){ try{ if(getUnitTweetPoll().getQuestionBean() !=null){ getUnitTweetPoll().getQuestionBean().getListAnswers().add(getAnswersBean()); createShortSimulateUrl(getAnswersBean()); setAnswersBean(new UnitAnswersBean()); addInfoMessage("Answer Added", ""); } else{ addWarningMessage("You need create question first.", ""); } }catch (Exception e) { addErrorMessage("error to add answer", ""); log.error(e); e.printStackTrace(); } } /** * Delete All Answers. */ public void deleteAllAnswers(){ try{ getUnitTweetPoll().getQuestionBean().setListAnswers(new ArrayList<UnitAnswersBean>()); addInfoMessage("Answer Cleared.", ""); }catch (Exception e) { addErrorMessage("error to add answer", ""); log.error(e); } } /** * Create Tweet Poll. */ public void createTweetPoll(){ final ISurveyService survey = getServicemanager().getApplicationServices().getSecurityService().getSurveyService(); try{ //save question survey.createQuestion(getUnitTweetPoll().getQuestionBean()); //save create tweet poll getUnitTweetPoll().setUserId(getUsernameByName().getSecUser().getUid()); //TODO: we need implement schedule tweetPoll. getUnitTweetPoll().setScheduleDate(new Date()); getUnitTweetPoll().setCloseNotification(false); getUnitTweetPoll().setAllowLiveResults(false); getUnitTweetPoll().setSchedule(false); + getUnitTweetPoll().setPublishPoll(false); getUnitTweetPoll().setResultNotification(false); survey.createTweetPoll(getUnitTweetPoll()); if(getUnitTweetPoll().getPublishPoll()){ final String tweet = survey.generateTweetPollText(getUnitTweetPoll()); final SecUsers sessionUser = getUsernameByName().getSecUser(); final Status status = survey.publicTweetPoll(tweet, sessionUser.getTwitterAccount(), sessionUser.getTwitterPassword()); final Long tweetId = status.getId(); if(tweetId != null){ getUnitTweetPoll().setTweetId(tweetId); getUnitTweetPoll().setPublicationDateTweet(status.getCreatedAt()); survey.saveTweetId(getUnitTweetPoll()); log.info("tweeted :"+tweetId); } } addInfoMessage("tweet poll message", ""); log.debug("tweet poll created"); }catch (EnMeExpcetion e) { addErrorMessage("error "+e, ""); log.error(e); e.printStackTrace(); } } /** * @return the unitTweetPoll */ public UnitTweetPoll getUnitTweetPoll() { return unitTweetPoll; } /** * @param unitTweetPoll the unitTweetPoll to set */ public void setUnitTweetPoll(final UnitTweetPoll unitTweetPoll) { this.unitTweetPoll = unitTweetPoll; } /** * @return the answersBean */ public UnitAnswersBean getAnswersBean() { return answersBean; } /** * @param answersBean the answersBean to set */ public void setAnswersBean(final UnitAnswersBean answersBean) { this.answersBean = answersBean; } /** * @return the questionBean */ public UnitQuestionBean getQuestionBean() { return questionBean; } /** * @param questionBean the questionBean to set */ public void setQuestionBean(final UnitQuestionBean questionBean) { this.questionBean = questionBean; } /** * @return the resumeTweet */ public String getResumeTweet() { return resumeTweet; } /** * @param resumeTweet the resumeTweet to set */ public void setResumeTweet(final String resumeTweet) { this.updateCount(resumeTweet); this.resumeTweet = resumeTweet; } /** * Update Count. * @param resumeTweet */ private void updateCount(final String resumeTweet){ final Integer tweetLenght = resumeTweet.length(); setCountTweet(getCountTweet() - tweetLenght); } /** * @return the countTweet */ public Integer getCountTweet() { return countTweet; } /** * @param countTweet the countTweet to set */ public void setCountTweet(Integer countTweet) { this.countTweet = countTweet; } }
true
true
public void createTweetPoll(){ final ISurveyService survey = getServicemanager().getApplicationServices().getSecurityService().getSurveyService(); try{ //save question survey.createQuestion(getUnitTweetPoll().getQuestionBean()); //save create tweet poll getUnitTweetPoll().setUserId(getUsernameByName().getSecUser().getUid()); //TODO: we need implement schedule tweetPoll. getUnitTweetPoll().setScheduleDate(new Date()); getUnitTweetPoll().setCloseNotification(false); getUnitTweetPoll().setAllowLiveResults(false); getUnitTweetPoll().setSchedule(false); getUnitTweetPoll().setResultNotification(false); survey.createTweetPoll(getUnitTweetPoll()); if(getUnitTweetPoll().getPublishPoll()){ final String tweet = survey.generateTweetPollText(getUnitTweetPoll()); final SecUsers sessionUser = getUsernameByName().getSecUser(); final Status status = survey.publicTweetPoll(tweet, sessionUser.getTwitterAccount(), sessionUser.getTwitterPassword()); final Long tweetId = status.getId(); if(tweetId != null){ getUnitTweetPoll().setTweetId(tweetId); getUnitTweetPoll().setPublicationDateTweet(status.getCreatedAt()); survey.saveTweetId(getUnitTweetPoll()); log.info("tweeted :"+tweetId); } } addInfoMessage("tweet poll message", ""); log.debug("tweet poll created"); }catch (EnMeExpcetion e) { addErrorMessage("error "+e, ""); log.error(e); e.printStackTrace(); } }
public void createTweetPoll(){ final ISurveyService survey = getServicemanager().getApplicationServices().getSecurityService().getSurveyService(); try{ //save question survey.createQuestion(getUnitTweetPoll().getQuestionBean()); //save create tweet poll getUnitTweetPoll().setUserId(getUsernameByName().getSecUser().getUid()); //TODO: we need implement schedule tweetPoll. getUnitTweetPoll().setScheduleDate(new Date()); getUnitTweetPoll().setCloseNotification(false); getUnitTweetPoll().setAllowLiveResults(false); getUnitTweetPoll().setSchedule(false); getUnitTweetPoll().setPublishPoll(false); getUnitTweetPoll().setResultNotification(false); survey.createTweetPoll(getUnitTweetPoll()); if(getUnitTweetPoll().getPublishPoll()){ final String tweet = survey.generateTweetPollText(getUnitTweetPoll()); final SecUsers sessionUser = getUsernameByName().getSecUser(); final Status status = survey.publicTweetPoll(tweet, sessionUser.getTwitterAccount(), sessionUser.getTwitterPassword()); final Long tweetId = status.getId(); if(tweetId != null){ getUnitTweetPoll().setTweetId(tweetId); getUnitTweetPoll().setPublicationDateTweet(status.getCreatedAt()); survey.saveTweetId(getUnitTweetPoll()); log.info("tweeted :"+tweetId); } } addInfoMessage("tweet poll message", ""); log.debug("tweet poll created"); }catch (EnMeExpcetion e) { addErrorMessage("error "+e, ""); log.error(e); e.printStackTrace(); } }
diff --git a/annis-gui/src/main/java/annis/gui/AboutWindow.java b/annis-gui/src/main/java/annis/gui/AboutWindow.java index 7c87123e9..381c9f47c 100644 --- a/annis-gui/src/main/java/annis/gui/AboutWindow.java +++ b/annis-gui/src/main/java/annis/gui/AboutWindow.java @@ -1,145 +1,145 @@ /* * Copyright 2011 Corpuslinguistic working group Humboldt University Berlin. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package annis.gui; import com.vaadin.server.ExternalResource; import com.vaadin.server.ThemeResource; import com.vaadin.server.VaadinService; import com.vaadin.server.VaadinSession; import com.vaadin.ui.*; import com.vaadin.ui.Button.ClickEvent; import java.io.File; import java.io.FileFilter; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.apache.commons.io.filefilter.WildcardFileFilter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author thomas */ public class AboutWindow extends Window { private static final Logger log = LoggerFactory.getLogger(AboutWindow.class); private VerticalLayout layout; public AboutWindow() { setSizeFull(); layout = new VerticalLayout(); setContent(layout); layout.setSizeFull(); HorizontalLayout hLayout = new HorizontalLayout(); Embedded logoAnnis = new Embedded(); logoAnnis.setSource(new ThemeResource("annis-logo-128.png")); logoAnnis.setType(Embedded.TYPE_IMAGE); hLayout.addComponent(logoAnnis); Embedded logoSfb = new Embedded(); logoSfb.setSource(new ThemeResource("sfb-logo.jpg")); logoSfb.setType(Embedded.TYPE_IMAGE); hLayout.addComponent(logoSfb); Link lnkFork = new Link(); lnkFork.setResource(new ExternalResource("https://github.com/korpling/ANNIS")); lnkFork.setIcon(new ExternalResource("https://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png")); lnkFork.setTargetName("_blank"); hLayout.addComponent(lnkFork); hLayout.setComponentAlignment(logoAnnis, Alignment.MIDDLE_LEFT); hLayout.setComponentAlignment(logoSfb, Alignment.MIDDLE_RIGHT); hLayout.setComponentAlignment(lnkFork, Alignment.TOP_RIGHT); layout.addComponent(hLayout); layout.addComponent(new Label("ANNIS is a project of the " + "<a href=\"http://www.sfb632.uni-potsdam.de/\">SFB632</a>.", Label.CONTENT_XHTML)); layout.addComponent(new Label("Homepage: " + "<a href=\"http://www.sfb632.uni-potsdam.de/d1/annis/\">" + "http://www.sfb632.uni-potsdam.de/d1/annis/</a>.", Label.CONTENT_XHTML)); layout.addComponent(new Label("Version: " + VaadinSession.getCurrent().getAttribute("annis-version"))); TextArea txtThirdParty = new TextArea(); txtThirdParty.setSizeFull(); StringBuilder sb = new StringBuilder(); - sb.append("The ANNIS team want's to thank these third party software that " + sb.append("The ANNIS team wants to thank these third party software that " + "made the ANNIS GUI possible:\n"); File thirdPartyFolder = new File(VaadinService.getCurrent().getBaseDirectory(), "THIRD-PARTY"); if(thirdPartyFolder.isDirectory()) { for(File c : thirdPartyFolder.listFiles((FileFilter) new WildcardFileFilter("*.txt"))) { if(c.isFile()) { try { sb.append(FileUtils.readFileToString(c)).append("\n"); } catch (IOException ex) { log.error("Could not read file", ex); } } } } txtThirdParty.setValue(sb.toString()); txtThirdParty.setReadOnly(true); txtThirdParty.addStyleName("license"); txtThirdParty.setWordwrap(false); layout.addComponent(txtThirdParty); Button btOK = new Button("OK"); final AboutWindow finalThis = this; btOK.addClickListener(new OkClickListener(finalThis)); layout.addComponent(btOK); layout.setComponentAlignment(hLayout, Alignment.MIDDLE_CENTER); layout.setComponentAlignment(btOK, Alignment.MIDDLE_CENTER); layout.setExpandRatio(txtThirdParty, 1.0f); } private static class OkClickListener implements Button.ClickListener { private final AboutWindow finalThis; public OkClickListener(AboutWindow finalThis) { this.finalThis = finalThis; } @Override public void buttonClick(ClickEvent event) { UI.getCurrent().removeWindow(finalThis); } } }
true
true
public AboutWindow() { setSizeFull(); layout = new VerticalLayout(); setContent(layout); layout.setSizeFull(); HorizontalLayout hLayout = new HorizontalLayout(); Embedded logoAnnis = new Embedded(); logoAnnis.setSource(new ThemeResource("annis-logo-128.png")); logoAnnis.setType(Embedded.TYPE_IMAGE); hLayout.addComponent(logoAnnis); Embedded logoSfb = new Embedded(); logoSfb.setSource(new ThemeResource("sfb-logo.jpg")); logoSfb.setType(Embedded.TYPE_IMAGE); hLayout.addComponent(logoSfb); Link lnkFork = new Link(); lnkFork.setResource(new ExternalResource("https://github.com/korpling/ANNIS")); lnkFork.setIcon(new ExternalResource("https://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png")); lnkFork.setTargetName("_blank"); hLayout.addComponent(lnkFork); hLayout.setComponentAlignment(logoAnnis, Alignment.MIDDLE_LEFT); hLayout.setComponentAlignment(logoSfb, Alignment.MIDDLE_RIGHT); hLayout.setComponentAlignment(lnkFork, Alignment.TOP_RIGHT); layout.addComponent(hLayout); layout.addComponent(new Label("ANNIS is a project of the " + "<a href=\"http://www.sfb632.uni-potsdam.de/\">SFB632</a>.", Label.CONTENT_XHTML)); layout.addComponent(new Label("Homepage: " + "<a href=\"http://www.sfb632.uni-potsdam.de/d1/annis/\">" + "http://www.sfb632.uni-potsdam.de/d1/annis/</a>.", Label.CONTENT_XHTML)); layout.addComponent(new Label("Version: " + VaadinSession.getCurrent().getAttribute("annis-version"))); TextArea txtThirdParty = new TextArea(); txtThirdParty.setSizeFull(); StringBuilder sb = new StringBuilder(); sb.append("The ANNIS team want's to thank these third party software that " + "made the ANNIS GUI possible:\n"); File thirdPartyFolder = new File(VaadinService.getCurrent().getBaseDirectory(), "THIRD-PARTY"); if(thirdPartyFolder.isDirectory()) { for(File c : thirdPartyFolder.listFiles((FileFilter) new WildcardFileFilter("*.txt"))) { if(c.isFile()) { try { sb.append(FileUtils.readFileToString(c)).append("\n"); } catch (IOException ex) { log.error("Could not read file", ex); } } } } txtThirdParty.setValue(sb.toString()); txtThirdParty.setReadOnly(true); txtThirdParty.addStyleName("license"); txtThirdParty.setWordwrap(false); layout.addComponent(txtThirdParty); Button btOK = new Button("OK"); final AboutWindow finalThis = this; btOK.addClickListener(new OkClickListener(finalThis)); layout.addComponent(btOK); layout.setComponentAlignment(hLayout, Alignment.MIDDLE_CENTER); layout.setComponentAlignment(btOK, Alignment.MIDDLE_CENTER); layout.setExpandRatio(txtThirdParty, 1.0f); }
public AboutWindow() { setSizeFull(); layout = new VerticalLayout(); setContent(layout); layout.setSizeFull(); HorizontalLayout hLayout = new HorizontalLayout(); Embedded logoAnnis = new Embedded(); logoAnnis.setSource(new ThemeResource("annis-logo-128.png")); logoAnnis.setType(Embedded.TYPE_IMAGE); hLayout.addComponent(logoAnnis); Embedded logoSfb = new Embedded(); logoSfb.setSource(new ThemeResource("sfb-logo.jpg")); logoSfb.setType(Embedded.TYPE_IMAGE); hLayout.addComponent(logoSfb); Link lnkFork = new Link(); lnkFork.setResource(new ExternalResource("https://github.com/korpling/ANNIS")); lnkFork.setIcon(new ExternalResource("https://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png")); lnkFork.setTargetName("_blank"); hLayout.addComponent(lnkFork); hLayout.setComponentAlignment(logoAnnis, Alignment.MIDDLE_LEFT); hLayout.setComponentAlignment(logoSfb, Alignment.MIDDLE_RIGHT); hLayout.setComponentAlignment(lnkFork, Alignment.TOP_RIGHT); layout.addComponent(hLayout); layout.addComponent(new Label("ANNIS is a project of the " + "<a href=\"http://www.sfb632.uni-potsdam.de/\">SFB632</a>.", Label.CONTENT_XHTML)); layout.addComponent(new Label("Homepage: " + "<a href=\"http://www.sfb632.uni-potsdam.de/d1/annis/\">" + "http://www.sfb632.uni-potsdam.de/d1/annis/</a>.", Label.CONTENT_XHTML)); layout.addComponent(new Label("Version: " + VaadinSession.getCurrent().getAttribute("annis-version"))); TextArea txtThirdParty = new TextArea(); txtThirdParty.setSizeFull(); StringBuilder sb = new StringBuilder(); sb.append("The ANNIS team wants to thank these third party software that " + "made the ANNIS GUI possible:\n"); File thirdPartyFolder = new File(VaadinService.getCurrent().getBaseDirectory(), "THIRD-PARTY"); if(thirdPartyFolder.isDirectory()) { for(File c : thirdPartyFolder.listFiles((FileFilter) new WildcardFileFilter("*.txt"))) { if(c.isFile()) { try { sb.append(FileUtils.readFileToString(c)).append("\n"); } catch (IOException ex) { log.error("Could not read file", ex); } } } } txtThirdParty.setValue(sb.toString()); txtThirdParty.setReadOnly(true); txtThirdParty.addStyleName("license"); txtThirdParty.setWordwrap(false); layout.addComponent(txtThirdParty); Button btOK = new Button("OK"); final AboutWindow finalThis = this; btOK.addClickListener(new OkClickListener(finalThis)); layout.addComponent(btOK); layout.setComponentAlignment(hLayout, Alignment.MIDDLE_CENTER); layout.setComponentAlignment(btOK, Alignment.MIDDLE_CENTER); layout.setExpandRatio(txtThirdParty, 1.0f); }
diff --git a/threads/LotteryScheduler.java b/threads/LotteryScheduler.java index 9c70819..60cbf04 100755 --- a/threads/LotteryScheduler.java +++ b/threads/LotteryScheduler.java @@ -1,211 +1,211 @@ package nachos.threads; import nachos.machine.*; import java.util.Random; import java.util.TreeSet; import java.util.HashSet; import java.util.Iterator; /** * A scheduler that chooses threads using a lottery. * * <p> * A lottery scheduler associates a number of tickets with each thread. When a * thread needs to be dequeued, a random lottery is held, among all the tickets * of all the threads waiting to be dequeued. The thread that holds the winning * ticket is chosen. * * <p> * Note that a lottery scheduler must be able to handle a lot of tickets * (sometimes billions), so it is not acceptable to maintain state for every * ticket. * * <p> * A lottery scheduler must partially solve the priority inversion problem; in * particular, tickets must be transferred through locks, and through joins. * Unlike a priority scheduler, these tickets add (as opposed to just taking * the maximum). */ public class LotteryScheduler extends PriorityScheduler { public static final int priorityMinimum = 1; public static final int priorityMaximum = Integer.MAX_VALUE; /** * Allocate a new lottery scheduler. */ public LotteryScheduler() { } //DONE!!!! protected ThreadState getThreadState(KThread thread) { if (thread.schedulingState == null) thread.schedulingState = new LotteryThreadState(thread); return (ThreadState) thread.schedulingState; } /** * Allocate a new lottery thread queue. * * @param transferPriority <tt>true</tt> if this queue should * transfer tickets from waiting threads * to the owning thread. * @return a new lottery thread queue. */ public ThreadQueue newThreadQueue(boolean transferPriority) { return new LotteryQueue(transferPriority); } protected class LotteryQueue extends PriorityQueue { //In terms of picking the next thread linear in the number of threads on the queue is fine LotteryQueue(boolean transferPriority) { super(transferPriority); } public void updateEntry(ThreadState ts, int newEffectivePriority) { int oldPriority = ts.getEffectivePriority(); ts.effectivePriority = newEffectivePriority; //propagate int difference = newEffectivePriority-oldPriority; if(difference != 0) ts.propagate(difference); } //DONE!!!!! protected ThreadState pickNextThread() { //Set up an Iterator and go through it Random randomGenerator = new Random(); int ticketCount = 0; Iterator<ThreadState> itr = this.waitQueue.iterator(); while(itr.hasNext()) { ticketCount += itr.next().getEffectivePriority(); } if(ticketCount > 0) { int num = randomGenerator.nextInt(ticketCount); itr = this.waitQueue.iterator(); ThreadState temp; while(itr.hasNext()) { temp = itr.next(); num -= temp.effectivePriority; if(num <= 0){ return temp; } } } return null; } } protected class LotteryThreadState extends ThreadState { public LotteryThreadState(KThread thread) { super(thread); } //DONE!!!! public void setPriority(int newPriority) { this.priority = newPriority; this.updateEffectivePriority(); } //DONE!!!! public void propagate(int difference) { if(pqWant != null) { if(pqWant.transferPriority == true) { if(pqWant.holder != null) pqWant.updateEntry(pqWant.holder, pqWant.holder.effectivePriority+difference); } } } //DONE!!!! public void updateEffectivePriority() { //Calculate new effectivePriority checking possible donations from threads that are waiting for me int sumPriority = this.priority; for (PriorityQueue pq: this.pqHave) if (pq.transferPriority == true) { Iterator<ThreadState> itr = pq.waitQueue.iterator(); while(itr.hasNext()) sumPriority += itr.next().getEffectivePriority(); } //If there is a change in priority, update and propagate to other owners if (sumPriority != this.effectivePriority) { int difference = sumPriority - this.effectivePriority; this.effectivePriority = sumPriority; this.propagate(difference); } } //DONE!!!! public void waitForAccess(PriorityQueue pq) { this.pqWant = pq; //this.time = Machine.timer().getTime(); this.time = TickTimer++; pq.waitQueue.add(this); //Propagate this ThreadState's effectivePriority to holder of pq if (pq.transferPriority == true) { if(pq.holder != null) pq.updateEntry(pq.holder, pq.holder.effectivePriority+this.effectivePriority); } } //Added a line to acquire in PriorityScheduler //updateEffectivePriority() at the very end of acquire } public static void selfTest() { LotteryScheduler ls = new LotteryScheduler(); LotteryQueue[] pq = new LotteryQueue[5]; KThread[] t = new KThread[5]; ThreadState lts[] = new LotteryThreadState[5]; for (int i=0; i < 5; i++) pq[i] = ls.new LotteryQueue(true); for (int i=0; i < 5; i++) { t[i] = new KThread(); t[i].setName("thread" + i); lts[i] = ls.getThreadState(t[i]); } Machine.interrupt().disable(); System.out.println("===========LotteryScheduler Test============"); System.out.println("priority defaults to " + lts[0].priority); pq[0].acquire(t[0]); System.out.println("pq[0].acquire(t[0])"); System.out.println("lock holder effective priority is " + pq[0].holder.effectivePriority); lts[0].setPriority(5); System.out.println("lts[0].setPriority(5)"); System.out.println("lock holder effective priority is " + lts[0].effectivePriority); pq[0].waitForAccess(t[1]); System.out.println("pq[0].waitForAccess(t[1])"); System.out.println("lock holder effective priority is " + lts[0].effectivePriority); KThread temp = pq[0].pickNextThread().thread; System.out.println("pq[0].pickNextThread()"); System.out.println("nextThread == null is: " + (temp == null)); pq[0].waitForAccess(t[2]); System.out.println("pq[0].waitForAccess(t[2])"); System.out.println("lock holder effective priority is " + lts[0].effectivePriority); lts[1].setPriority(3); System.out.println("lts[1].setPriority(3)"); System.out.println("lts[1] priority is " + lts[1].priority); System.out.println("lts[1] effective priority is " + lts[1].effectivePriority); System.out.println("lock holder effective priority is " + lts[0].effectivePriority); lts[2].setPriority(6); - System.out.println("lts[1].setPriority(2)"); - System.out.println("lts[1] priority is " + lts[1].priority); - System.out.println("lts[1] effective priority is " + lts[1].effectivePriority); + System.out.println("lts[2].setPriority(6)"); + System.out.println("lts[2] priority is " + lts[2].priority); + System.out.println("lts[2] effective priority is " + lts[2].effectivePriority); System.out.println("lock holder effective priority is " + lts[0].effectivePriority); temp = pq[0].nextThread(); System.out.println("pq[0].nextThread()"); System.out.println("nextThread == null is: " + (temp == null)); ThreadState temp2 = pq[0].pickNextThread(); System.out.println("pq[0].pickNextThread()"); System.out.println("pickNextThread == null is: " + (temp2 == null)); temp = pq[0].nextThread(); System.out.println("pq[0].nextThread()"); System.out.println("nextThread == null is: " + (temp == null)); Machine.interrupt().enable(); } }
true
true
public static void selfTest() { LotteryScheduler ls = new LotteryScheduler(); LotteryQueue[] pq = new LotteryQueue[5]; KThread[] t = new KThread[5]; ThreadState lts[] = new LotteryThreadState[5]; for (int i=0; i < 5; i++) pq[i] = ls.new LotteryQueue(true); for (int i=0; i < 5; i++) { t[i] = new KThread(); t[i].setName("thread" + i); lts[i] = ls.getThreadState(t[i]); } Machine.interrupt().disable(); System.out.println("===========LotteryScheduler Test============"); System.out.println("priority defaults to " + lts[0].priority); pq[0].acquire(t[0]); System.out.println("pq[0].acquire(t[0])"); System.out.println("lock holder effective priority is " + pq[0].holder.effectivePriority); lts[0].setPriority(5); System.out.println("lts[0].setPriority(5)"); System.out.println("lock holder effective priority is " + lts[0].effectivePriority); pq[0].waitForAccess(t[1]); System.out.println("pq[0].waitForAccess(t[1])"); System.out.println("lock holder effective priority is " + lts[0].effectivePriority); KThread temp = pq[0].pickNextThread().thread; System.out.println("pq[0].pickNextThread()"); System.out.println("nextThread == null is: " + (temp == null)); pq[0].waitForAccess(t[2]); System.out.println("pq[0].waitForAccess(t[2])"); System.out.println("lock holder effective priority is " + lts[0].effectivePriority); lts[1].setPriority(3); System.out.println("lts[1].setPriority(3)"); System.out.println("lts[1] priority is " + lts[1].priority); System.out.println("lts[1] effective priority is " + lts[1].effectivePriority); System.out.println("lock holder effective priority is " + lts[0].effectivePriority); lts[2].setPriority(6); System.out.println("lts[1].setPriority(2)"); System.out.println("lts[1] priority is " + lts[1].priority); System.out.println("lts[1] effective priority is " + lts[1].effectivePriority); System.out.println("lock holder effective priority is " + lts[0].effectivePriority); temp = pq[0].nextThread(); System.out.println("pq[0].nextThread()"); System.out.println("nextThread == null is: " + (temp == null)); ThreadState temp2 = pq[0].pickNextThread(); System.out.println("pq[0].pickNextThread()"); System.out.println("pickNextThread == null is: " + (temp2 == null)); temp = pq[0].nextThread(); System.out.println("pq[0].nextThread()"); System.out.println("nextThread == null is: " + (temp == null)); Machine.interrupt().enable(); }
public static void selfTest() { LotteryScheduler ls = new LotteryScheduler(); LotteryQueue[] pq = new LotteryQueue[5]; KThread[] t = new KThread[5]; ThreadState lts[] = new LotteryThreadState[5]; for (int i=0; i < 5; i++) pq[i] = ls.new LotteryQueue(true); for (int i=0; i < 5; i++) { t[i] = new KThread(); t[i].setName("thread" + i); lts[i] = ls.getThreadState(t[i]); } Machine.interrupt().disable(); System.out.println("===========LotteryScheduler Test============"); System.out.println("priority defaults to " + lts[0].priority); pq[0].acquire(t[0]); System.out.println("pq[0].acquire(t[0])"); System.out.println("lock holder effective priority is " + pq[0].holder.effectivePriority); lts[0].setPriority(5); System.out.println("lts[0].setPriority(5)"); System.out.println("lock holder effective priority is " + lts[0].effectivePriority); pq[0].waitForAccess(t[1]); System.out.println("pq[0].waitForAccess(t[1])"); System.out.println("lock holder effective priority is " + lts[0].effectivePriority); KThread temp = pq[0].pickNextThread().thread; System.out.println("pq[0].pickNextThread()"); System.out.println("nextThread == null is: " + (temp == null)); pq[0].waitForAccess(t[2]); System.out.println("pq[0].waitForAccess(t[2])"); System.out.println("lock holder effective priority is " + lts[0].effectivePriority); lts[1].setPriority(3); System.out.println("lts[1].setPriority(3)"); System.out.println("lts[1] priority is " + lts[1].priority); System.out.println("lts[1] effective priority is " + lts[1].effectivePriority); System.out.println("lock holder effective priority is " + lts[0].effectivePriority); lts[2].setPriority(6); System.out.println("lts[2].setPriority(6)"); System.out.println("lts[2] priority is " + lts[2].priority); System.out.println("lts[2] effective priority is " + lts[2].effectivePriority); System.out.println("lock holder effective priority is " + lts[0].effectivePriority); temp = pq[0].nextThread(); System.out.println("pq[0].nextThread()"); System.out.println("nextThread == null is: " + (temp == null)); ThreadState temp2 = pq[0].pickNextThread(); System.out.println("pq[0].pickNextThread()"); System.out.println("pickNextThread == null is: " + (temp2 == null)); temp = pq[0].nextThread(); System.out.println("pq[0].nextThread()"); System.out.println("nextThread == null is: " + (temp == null)); Machine.interrupt().enable(); }
diff --git a/core/Parser.java b/core/Parser.java index b19c3a6..e7d5f03 100755 --- a/core/Parser.java +++ b/core/Parser.java @@ -1,1597 +1,1597 @@ /* * Parser.java * * Parses a MIPS64 source code and fills the symbol table and the memory. * * (c) 2006 mancausoft, Vanni * * This file is part of the EduMIPS64 project, and is released under the GNU * General Public License. * * 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 */ /** Parses a MIPS64 source code and fills the symbol table and the memory. * @author mancausoft, Vanni */ package edumips64.core; import edumips64.Main; import edumips64.utils.*; import edumips64.core.is.*; import java.util.regex.*; import java.io.*; import java.util.*; import java.lang.reflect.Array; public class Parser { private enum AliasRegister {zero,at,v0,v1,a0,a1,a2,a3,t0,t1,t2,t3,t4,t5,t6,t7,s0,s1,s2,s3,s4,s5,s6,s7,t8,t9,k0,k1,gp,sp,fp,ra}; private static final String deprecateInstruction[] = {"BNEZ","BEQZ", "HALT", "DADDUI"}; private class VoidJump { public Instruction instr; public String label; int row; int column; int instrCount; String line; boolean isBranch = false; } ParserMultiWarningException warning; ParserMultiException error; boolean isFirstOutOfMemory; String path; int numError; int numWarning; /** Instance of Parser */ private static Parser instance = null; /** 0 null, 1 .data, 2 .text or .code */ private int status; /** File to be parsed */ private BufferedReader in; int memoryCount; String filename; private SymbolTable symTab; /** Singleton pattern constructor */ private Parser () { symTab = SymbolTable.getInstance(); } /** Singleton Pattern implementation * @return get the Singleton instance of the Parser */ public static Parser getInstance() { if(instance==null) instance = new Parser(); return instance; } private String fileToString(BufferedReader in) throws IOException { String ret = ""; int charRead =0; String line; while ((line = in.readLine())!=null) { String tmp = cleanFormat(line); if (tmp!=null) ret += tmp + "\n"; }while (charRead == 1024); return ret; } /** * */ private void checkLoop(String data, Stack<String> included ) throws IOException, ParserMultiException { int i = 0; do { i = data.indexOf("#include ",i); if (i != -1) { int end = data.indexOf("\n", i); if (end == -1) { end = data.length(); } int a = included.search(data.substring(i+9, end ).trim()); if ( a!= -1) { error = new ParserMultiException (); error.add("INCLUDE_LOOP",0,0,"#include "+ data.substring(i+9, end ).trim() ); throw error; } String filename = data.substring(i+9, end).trim(); if (!(new File(filename)).isAbsolute()) filename = path + filename; String filetmp = fileToString(new BufferedReader(new InputStreamReader(new FileInputStream(filename),"ISO-8859-1"))); checkLoop(filetmp ,included); i ++; } }while(i!=-1); } /** Process the #include (Syntax #include file.ext ) */ private String preprocessor() throws IOException, ParserMultiException { String filetmp = ""; filetmp = fileToString(in); int i=0; //check loop Stack<String> included = new Stack<String>(); included.push(this.filename); checkLoop(filetmp, included); // include do { i = filetmp.indexOf("#include ",i); if (i != -1) { int end = filetmp.indexOf("\n", i); if (end == -1) { end = filetmp.length(); } edumips64.Main.logger.debug("Open by #include: " + filetmp.substring(i+9, end).trim()); String filename = filetmp.substring(i+9, end).trim(); if (!(new File(filename)).isAbsolute()) filename = path + filename; filetmp = filetmp.substring(0,i) + fileToString (new BufferedReader(new InputStreamReader(new FileInputStream(filename) ,"ISO-8859-1"))) + filetmp.substring(end); } }while(i!=-1); return filetmp; } /** Loading from File * @param filename A String with the system-dependent file name * @throws FileNotFoundException if the file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading * @throws SecurityException if a security manager exists and its checkRead method denies read access to the file. */ public void parse(String filename) throws FileNotFoundException, SecurityException, IOException,ParserMultiException { in = new BufferedReader(new InputStreamReader(new FileInputStream(filename),"ISO-8859-1")); this.filename = filename; int oldindex = 0; int index = 0; while ((index = filename.indexOf(File.separator,index)) != -1 ) { oldindex = index; index ++; } path = filename.substring(0,oldindex+1); String code = preprocessor(); parse(code.toCharArray()); } /** Loading from buffer * @param buffer An Array of char with the MIPS code * */ public void parse(char[] buffer) throws IOException,ParserMultiException { in = new BufferedReader(new CharArrayReader(buffer)); doParsing(); } /** commit the parsing (public or private?) */ private void doParsing () throws IOException,ParserMultiException { boolean isFirstOutOfInstructionMemory = false; isFirstOutOfMemory = true; boolean halt = false; int row = 0; int nline=0; numError = 0; numWarning =0; int instrCount = -4; // Hack fituso by Andrea String line; error = new ParserMultiException(); warning = new ParserMultiWarningException(); LinkedList<VoidJump> voidJump = new LinkedList<VoidJump>(); Memory mem = Memory.getInstance(); memoryCount=0; String lastLabel =""; while ((line = in.readLine())!=null) //read all file { row++; for(int i=0; i<line.length(); i++) { if(line.charAt(i)==';') //comments break; if(line.charAt(i)==' ' || line.charAt(i)=='\t') continue; int tab = line.indexOf('\t',i); int space = line.indexOf(' ',i); if (tab == -1) tab=line.length(); if (space == -1) space=line.length(); int end = Math.min(tab,space)-1; String instr = line.substring(i,end+1); String parameters = null; try { if (line.charAt(i)=='.') { edumips64.Main.logger.debug("Processing " + instr); if(instr.compareToIgnoreCase(".DATA")==0) { status = 1; } else if (instr.compareToIgnoreCase(".TEXT")==0 || instr.compareToIgnoreCase(".CODE")==0 ) { status = 2; } else { String name = instr.substring(1); // The name, without the dot. if(status != 1) { numError++; error.add(name.toUpperCase() + "INCODE", row, i + 1, line); i = line.length(); continue; } try { if(!((instr.compareToIgnoreCase(".ASCII") == 0) || instr.compareToIgnoreCase(".ASCIIZ") == 0)) { // We don't want strings to be uppercase, do we? parameters = cleanFormat(line.substring(end+2)); parameters = parameters.toUpperCase(); parameters = parameters.split(";")[0]; Main.logger.debug("parameters: " + parameters); } else parameters = line.substring(end + 2); parameters = parameters.split(";")[0].trim(); Main.logger.debug("parameters: " + parameters); } catch (StringIndexOutOfBoundsException e) { numWarning++; warning.add("VALUE_MISS", row, i+1, line); error.addWarning("VALUE_MISS", row, i+1, line); memoryCount++; i = line.length(); continue; } if (instr==null) { numWarning++; warning.add("VALUE_MISS", row, i+1, line); error.addWarning("VALUE_MISS", row, i+1, line); memoryCount++; i = line.length(); continue; } MemoryElement tmpMem = null; tmpMem = mem.getCell(memoryCount * 8); Main.logger.debug("line: "+line); String[] comment = (line.substring(i)).split(";",2); if (Array.getLength(comment) == 2) { Main.logger.debug("found comments: "+comment[1]); tmpMem.setComment(comment[1]); } tmpMem.setCode(comment[0]); if(instr.compareToIgnoreCase(".ASCII") == 0 || instr.compareToIgnoreCase(".ASCIIZ") == 0) { edumips64.Main.logger.debug(".ascii(z): parameters = " + parameters); boolean auto_terminate = false; if(instr.compareToIgnoreCase(".ASCIIZ") == 0) auto_terminate = true; try { List<String> pList = splitStringParameters(parameters, auto_terminate); for(String current_string : pList) { edumips64.Main.logger.debug("Current string: [" + current_string + "]"); edumips64.Main.logger.debug(".ascii(z): requested new memory cell (" + memoryCount + ")"); tmpMem = mem.getCell(memoryCount * 8); memoryCount++; int posInWord = 0; // TODO: Controllo sui parametri (es. virgolette?) int num = current_string.length(); boolean escape = false; boolean placeholder = false; int escaped = 0; // to avoid escape sequences to count as two bytes for(int tmpi = 0; tmpi < num; tmpi++) { if((tmpi - escaped) % 8 == 0 && (tmpi - escaped) != 0 && !escape) { edumips64.Main.logger.debug(".ascii(z): requested new memory cell (" + memoryCount + ")"); tmpMem = mem.getCell(memoryCount * 8); memoryCount++; posInWord = 0; } char c = current_string.charAt(tmpi); int to_write = (int)c; edumips64.Main.logger.debug("Char: " + c + " (" + to_write + ") [" + Integer.toHexString(to_write) + "]"); if(escape) { switch(c) { case '0': to_write = 0; break; case 'n': to_write = 10; break; case 't': to_write = 9; break; case '\\': to_write = 92; break; case '"': to_write = 34; break; default: throw new StringFormatException(); } edumips64.Main.logger.debug("(escaped to [" + Integer.toHexString(to_write) + "])"); escape = false; c = 0; // to avoid re-entering the escape if branch. } if(placeholder) { if(c != '%' && c != 's' && c != 'd' && c != 'i') { edumips64.Main.logger.debug("Invalid placeholder: %" + c); // Invalid placeholder throw new StringFormatException(); } placeholder = false; } if(c == '%' && !placeholder) { edumips64.Main.logger.debug("Expecting on next step a valid placeholder..."); placeholder = true; } if(c == '\\') { escape = true; escaped++; continue; } tmpMem.writeByte(to_write, posInWord++); } } } catch(StringFormatException ex) { edumips64.Main.logger.debug("Badly formed string list"); numError++; // TODO: more descriptive error message error.add("INVALIDVALUE",row,0,line); } end = line.length(); } else if(instr.compareToIgnoreCase(".SPACE") == 0) { int posInWord=0; //position of byte to write into a doubleword memoryCount++; try { if(isHexNumber(parameters)) parameters = Converter.hexToLong(parameters); if(isNumber(parameters)) { int num = Integer.parseInt(parameters); for(int tmpi = 0; tmpi < num; tmpi++) { if(tmpi % 8 == 0 && tmpi != 0) { tmpMem = mem.getCell(memoryCount * 8); memoryCount++; posInWord = 0; } tmpMem.writeByte(0,posInWord++); } } else { throw new NumberFormatException(); } } catch(NumberFormatException ex) { numError++; error.add("INVALIDVALUE",row,i+1,line); continue; } catch(IrregularStringOfHexException ex) { numError++; error.add("INVALIDVALUE",row,i+1,line); continue; } posInWord ++; end = line.length(); } else if(instr.compareToIgnoreCase(".WORD")==0 || instr.compareToIgnoreCase(".WORD64")==0) { Main.logger.debug("pamword: "+parameters); writeIntegerInMemory(row, i, end, line, parameters, 64, "WORD"); end = line.length(); } else if (instr.compareToIgnoreCase(".WORD32")==0) { writeIntegerInMemory(row, i, end, line, parameters, 32, "WORD32"); end = line.length(); } else if(instr.compareToIgnoreCase(".BYTE")==0) { writeIntegerInMemory(row, i, end, line, parameters, 8, "BYTE"); end = line.length(); } else if(instr.compareToIgnoreCase(".WORD16")==0) { writeIntegerInMemory(row, i, end, line, parameters,16 , "WORD16"); end = line.length(); } else if(instr.compareToIgnoreCase(".DOUBLE")==0) { writeDoubleInMemory(row, i, end, line, parameters); end = line.length(); } else { numError++; error.add("INVALIDCODEFORDATA",row,i+1,line); i = line.length(); continue; } } } else if(line.charAt(end)==':') { edumips64.Main.logger.debug("Processing a label.."); if(status==1) { edumips64.Main.logger.debug("in .data section"); MemoryElement tmpMem = null; tmpMem = mem.getCell(memoryCount * 8); try { symTab.setCellLabel(memoryCount * 8, line.substring(i, end)); } catch (SameLabelsException e) { // TODO: errore del parser edumips64.Main.logger.debug("Label " + line.substring(i, end) + " is already assigned"); } } else if(status==2) { edumips64.Main.logger.debug("in .text section"); lastLabel = line.substring(i,end); } edumips64.Main.logger.debug("done"); } else { if(status!=2) { numError++; error.add("INVALIDCODEFORDATA",row,i+1,line); i = line.length(); continue; } else if (status == 2) { boolean doPack = true; end++; Instruction tmpInst; // Check for halt-like instructions String temp = cleanFormat(line.substring(i)).toUpperCase(); if(temp.equals("HALT") || temp.equals("SYSCALL 0") || temp.equals("TRAP 0")) { halt = true; } //timmy for(int timmy = 0; timmy < Array.getLength(deprecateInstruction); timmy++) { if(deprecateInstruction[timmy].toUpperCase().equals(line.substring(i, end).toUpperCase())) { warning.add("WINMIPS64_NOT_MIPS64",row,i+1,line); error.addWarning("WINMIPS64_NOT_MIPS64",row,i+1,line); numWarning ++; } } tmpInst = Instruction.buildInstruction(line.substring(i,end).toUpperCase()); if (tmpInst == null) { numError++; error.add("INVALIDCODE",row,i+1,line); i = line.length(); continue; } String syntax = tmpInst.getSyntax(); instrCount += 4; if (syntax.compareTo("")!=0 && (line.length()<end+1)) { numError++; error.add("UNKNOWNSYNTAX",row,end,line); i = line.length(); continue; } if(syntax.compareTo("")!=0) { String param = cleanFormat(line.substring(end+1)); param = param.toUpperCase(); param = param.split(";")[0].trim(); Main.logger.debug("param: " + param); int indPar=0; for(int z=0; z < syntax.length(); z++) { if(syntax.charAt(z)=='%') { z++; if(syntax.charAt(z)=='R') //register { int endPar; if(z!=syntax.length()-1) endPar = param.indexOf(syntax.charAt(++z),indPar); else endPar = param.length(); if (endPar==-1) { numError++; error.add("SEPARATORMISS",row,indPar,line); i = line.length(); tmpInst.getParams().add(0); continue; } int reg; if ((reg = isRegister(param.substring(indPar,endPar).trim()))>=0) { tmpInst.getParams().add(reg); indPar = endPar+1; } else { numError++; error.add("INVALIDREGISTER",row,line.indexOf(param.substring(indPar,endPar))+1,line); tmpInst.getParams().add(0); i = line.length(); continue; } } else if(syntax.charAt(z)=='I') //immediate { int endPar; if(z!=syntax.length()-1) endPar = param.indexOf(syntax.charAt(++z),indPar); else endPar = param.length(); if (endPar==-1) { numError++; error.add("SEPARATORMISS",row,indPar,line); i = line.length(); tmpInst.getParams().add(0); continue; } int imm; if (isImmediate(param.substring(indPar,endPar))) { if (param.charAt(indPar)=='#') indPar++; if (isNumber(param.substring(indPar,endPar))) { try { imm = Integer.parseInt(param.substring(indPar,endPar)); if( imm < -32768 || imm > 32767) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); } tmpInst.getParams().add(imm); indPar = endPar+1; } else if (isHexNumber(param.substring(indPar,endPar))) { try { try { imm = (int) Long.parseLong(Converter.hexToShort(param.substring(indPar,endPar))); Main.logger.debug("imm = "+ imm); if( imm < -32768 || imm > 32767) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); } tmpInst.getParams().add(imm); indPar = endPar+1; } catch(IrregularStringOfHexException ex) { //non ci dovrebbe mai arrivare } } } else { try { int offset=0,cc; MemoryElement tmpMem; cc = param.indexOf("+",indPar); if (cc!=-1) { tmpMem = symTab.getCell(param.substring(indPar,cc).trim()); if (isNumber(param.substring(cc+1,endPar))) { try { imm = Integer.parseInt(param.substring(indPar,endPar)); if( imm < -32768 || imm > 32767) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); } tmpInst.getParams().add(tmpMem.getAddress() + imm); indPar = endPar+1; } else if (isHexNumber(param.substring(cc+1,endPar))) { try { try { imm = (int) Long.parseLong(Converter.hexToLong(param.substring(indPar,endPar))); if( imm < -32768 || imm > 32767) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); } tmpInst.getParams().add(tmpMem.getAddress() + imm); indPar = endPar+1; } catch(IrregularStringOfHexException ex) { //non ci dovrebbe mai arrivare } } else { MemoryElement tmpMem1 = symTab.getCell(param.substring(cc+1,endPar).trim()); tmpInst.getParams().add(tmpMem.getAddress() + tmpMem1.getAddress()); } } else { cc = param.indexOf("-",indPar); if (cc!=-1) { tmpMem = symTab.getCell(param.substring(indPar,cc).trim()); if (isNumber(param.substring(cc+1,endPar))) { try { imm = Integer.parseInt(param.substring(indPar,endPar)); if( imm < -32768 || imm > 32767) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); } tmpInst.getParams().add(tmpMem.getAddress() - imm); indPar = endPar+1; } else if (isHexNumber(param.substring(cc+1,endPar))) { try { try { imm = (int) Long.parseLong(Converter.hexToLong(param.substring(indPar,endPar))); if( imm < -32768 || imm > 32767) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); } tmpInst.getParams().add(tmpMem.getAddress() - imm); indPar = endPar+1; } catch(IrregularStringOfHexException ex) { //non ci dovrebbe mai arrivare } } else { MemoryElement tmpMem1 = symTab.getCell(param.substring(cc+1,endPar).trim()); tmpInst.getParams().add(tmpMem.getAddress() - tmpMem1.getAddress()); } } else { tmpMem = symTab.getCell(param.substring(indPar,endPar).trim()); tmpInst.getParams().add(tmpMem.getAddress()); } } } catch(MemoryElementNotFoundException ex) { numError++; error.add("INVALIDIMMEDIATE",row,line.indexOf(param.substring(indPar,endPar))+1,line); i = line.length(); tmpInst.getParams().add(0); continue; } } } else if(syntax.charAt(z)=='U') //Unsigned Immediate (5 bit) { int endPar; if(z!=syntax.length()-1) endPar = param.indexOf(syntax.charAt(++z),indPar); else endPar = param.length(); if (endPar==-1) { numError++; error.add("SEPARATORMISS",row,indPar,line); i = line.length(); tmpInst.getParams().add(0); continue; } int imm; if (isImmediate(param.substring(indPar,endPar))) { if (param.charAt(indPar)=='#') indPar++; if (isNumber(param.substring(indPar,endPar))) { try{ imm = Integer.parseInt(param.substring(indPar,endPar).trim()); if (imm < 0) { numError++; error.add("VALUEISNOTUNSIGNED",row,line.indexOf(param.substring(indPar,endPar))+1,line); i = line.length(); tmpInst.getParams().add(0); continue; } if( imm < 0 || imm > 31) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("5BIT_IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); } tmpInst.getParams().add(imm); indPar = endPar+1; } else if (isHexNumber(param.substring(indPar,endPar).trim())) { try { imm = (int) Long.parseLong(Converter.hexToLong(param.substring(indPar,endPar))); if (imm < 0) { numError++; error.add("VALUEISNOTUNSIGNED",row,line.indexOf(param.substring(indPar,endPar))+1,line); i = line.length(); tmpInst.getParams().add(0); continue; } tmpInst.getParams().add(imm); indPar = endPar+1; if( imm < 0 || imm > 31) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("5BIT_IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); tmpInst.getParams().add(imm); indPar = endPar+1; } catch(IrregularStringOfHexException ex) { //non ci dovrebbe mai arrivare } } } else { numError++; error.add("INVALIDIMMEDIATE",row,line.indexOf(param.substring(indPar,endPar))+1,line); i = line.length(); tmpInst.getParams().add(0); continue; } } else if(syntax.charAt(z)=='L') //Memory Label { int endPar; if(z!=syntax.length()-1) endPar = param.indexOf(syntax.charAt(++z),indPar); else endPar = param.length(); if (endPar==-1) { numError++; error.add("SEPARATORMISS",row,indPar,line); i = line.length(); tmpInst.getParams().add(0); continue; } try { MemoryElement tmpMem; if(param.substring(indPar,endPar).equals("")) tmpInst.getParams().add(0); else if(isNumber(param.substring(indPar,endPar).trim())) { int tmp = Integer.parseInt(param.substring(indPar,endPar).trim()); - if (tmp<0) + if (tmp<0 || tmp%4!=0 ) { numError++; - error.add("LABELNOTFOUND",row,line.indexOf(param.substring(indPar,endPar))+1,line); + error.add("MEMORYADDRESSINVALID",row,line.indexOf(param.substring(indPar,endPar))+1,line); i = line.length(); indPar = endPar+1; tmpInst.getParams().add(0); continue; } tmpInst.getParams().add(tmp); } else { int offset=0,cc; cc = param.indexOf("+",indPar); if (cc!=-1) { tmpMem = symTab.getCell(param.substring(indPar,cc).trim()); try { tmpInst.getParams().add(tmpMem.getAddress() + Integer.parseInt(param.substring(cc+1,endPar))); } catch(NumberFormatException ex) { numError++; error.add("LABELNOTFOUND",row,line.indexOf(param.substring(indPar,endPar))+1,line); i = line.length(); indPar = endPar+1; tmpInst.getParams().add(0); continue; } } else { cc = param.indexOf("-",indPar); if (cc!=-1) { tmpMem = symTab.getCell(param.substring(indPar,cc).trim()); try { tmpInst.getParams().add(tmpMem.getAddress() - Integer.parseInt(param.substring(cc+1,endPar))); } catch(NumberFormatException ex) { numError++; error.add("LABELNOTFOUND",row,line.indexOf(param.substring(indPar,endPar))+1,line); i = line.length(); indPar = endPar+1; tmpInst.getParams().add(0); continue; } } else { tmpMem = symTab.getCell(param.substring(indPar,endPar).trim()); tmpInst.getParams().add(tmpMem.getAddress()); } } } indPar = endPar+1; } catch (MemoryElementNotFoundException e) { numError++; error.add("LABELNOTFOUND",row,line.indexOf(param.substring(indPar,endPar))+1,line); i = line.length(); indPar = endPar+1; tmpInst.getParams().add(0); continue; } } else if(syntax.charAt(z)=='E') //Instruction Label { int endPar; if(z!=syntax.length()-1) endPar = param.indexOf(syntax.charAt(++z),indPar); else endPar = param.length(); if (endPar==-1) { numError++; error.add("SEPARATORMISS",row,indPar,line); i = line.length(); tmpInst.getParams().add(0); continue; } Integer labelAddr = symTab.getInstructionAddress(param.substring(indPar,endPar).trim()); if (labelAddr != null) { tmpInst.getParams().add(labelAddr); } else { VoidJump tmpVoid = new VoidJump(); tmpVoid.instr = tmpInst; tmpVoid.row = row; tmpVoid.line = line; tmpVoid.column = indPar; tmpVoid.label = param.substring(indPar,endPar); voidJump.add(tmpVoid); doPack = false; } } else if(syntax.charAt(z)=='B') //Instruction Label for branch { int endPar; if(z!=syntax.length()-1) endPar = param.indexOf(syntax.charAt(++z),indPar); else endPar = param.length(); if (endPar==-1) { numError++; error.add("SEPARATORMISS",row,indPar,line); i = line.length(); tmpInst.getParams().add(0); continue; } Integer labelAddr = symTab.getInstructionAddress(param.substring(indPar,endPar).trim()); if (labelAddr != null) { labelAddr -= instrCount + 4; tmpInst.getParams().add(labelAddr); } else { VoidJump tmpVoid = new VoidJump(); tmpVoid.instr = tmpInst; tmpVoid.row = row; tmpVoid.line = line; tmpVoid.column = indPar; tmpVoid.label = param.substring(indPar,endPar); tmpVoid.instrCount = instrCount; tmpVoid.isBranch = true; voidJump.add(tmpVoid); doPack = false; } } else { numError++; error.add("UNKNOWNSYNTAX",row,1,line); i = line.length(); tmpInst.getParams().add(0); continue; } } else { if(syntax.charAt(z)!=param.charAt(indPar++)) { numError++; error.add("UNKNOWNSYNTAX",row,1,line); i = line.length(); tmpInst.getParams().add(0); continue; } } } if( i == line.length()) continue; try { if (doPack) tmpInst.pack(); } catch(IrregularStringOfBitsException ex) { //ISGROUP HA SBAGLIATO QUALCOSA } } else { try { tmpInst.pack(); } catch(IrregularStringOfBitsException e) { } } Main.logger.debug("line: "+line); String comment[] = line.split(";",2); tmpInst.setFullName(replaceTab(comment[0].substring(i))); tmpInst.setFullName(replaceTab(comment[0].substring(i))); tmpInst.setFullName(replaceTab(comment[0].substring(i))); tmpInst.setFullName(replaceTab(comment[0].substring(i))); if (Array.getLength(comment)==2) if (Array.getLength(comment)==2) tmpInst.setComment(comment[1]); try { mem.addInstruction(tmpInst,instrCount); symTab.setInstructionLabel(instrCount, lastLabel.toUpperCase()); } catch(SymbolTableOverflowException ex) { if(isFirstOutOfInstructionMemory)//is first out of memory? { isFirstOutOfInstructionMemory = false; numError++; error.add("OUTOFINSTRUCTIONMEMORY",row,i+1,line); i = line.length(); continue; } } catch(SameLabelsException ex) { numError++; error.add("SAMELABEL", row, 1, line); i = line.length(); } // Il finally e' totalmente inutile, ma è bello utilizzarlo per la // prima volta in un programma ;) finally { lastLabel = ""; } end = line.length(); } } i=end; } catch(MemoryElementNotFoundException ex) { if(isFirstOutOfMemory)//is first out of memory? { isFirstOutOfMemory = false; numError++; error.add("OUTOFMEMORY",row,i+1,line); i = line.length(); continue; } } catch(IrregularWriteOperationException ex) { numError++; error.add("INVALIDVALUE",row,i+1,line); break; } } } for (int i=0; i< voidJump.size();i++) { Integer labelAddr = symTab.getInstructionAddress(voidJump.get(i).label.trim()); if (labelAddr != null) { if (voidJump.get(i).isBranch) labelAddr -= voidJump.get(i).instrCount + 4; voidJump.get(i).instr.getParams().add(labelAddr); try { voidJump.get(i).instr.pack(); } catch(IrregularStringOfBitsException ex) { //ISGROUP HA SBAGLIATO QUALCOSA } } else { numError++; error.add("LABELNOTFOUND",voidJump.get(i).row,voidJump.get(i).column ,voidJump.get(i).line); continue; } } in.close(); if(!halt) //if Halt is not present in code { numWarning++; warning.add("HALT_NOT_PRESENT",row,0,""); error.addWarning("HALT_NOT_PRESENT",row,0,""); try { Instruction tmpInst = Instruction.buildInstruction("SYSCALL"); tmpInst.getParams().add(0); tmpInst.setFullName("SYSCALL 0"); try { tmpInst.pack(); } catch(IrregularStringOfBitsException ex) { //ISGROUP HA SBAGLIATO QUALCOSA } mem.addInstruction(tmpInst,(instrCount+4)); symTab.setInstructionLabel((instrCount+4), ""); } catch(SymbolTableOverflowException ex) { if(isFirstOutOfInstructionMemory)//is first out of memory? { isFirstOutOfInstructionMemory = false; numError++; error.add("OUTOFINSTRUCTIONMEMORY",row,0,"Halt"); } } catch(SameLabelsException ex) {} // impossible } if (numError>0) { throw error; } else if (numWarning > 0) { throw warning; } } /** Clean multiple tab or spaces in a bad format String //and converts this String to upper case * @param the bad format String * @return the cleaned String */ public String cleanFormat(String s){ if(s.length()>0 && s.charAt(0)!=';' && s.charAt(0)!='\n' ) { //String[] nocomment=s.split(";"); //s=nocomment[0];//.toUpperCase(); s=s.trim(); s=s.replace("\t"," "); while(s.contains(" ")) s=s.replace(" "," "); s=s.replace(", ",","); s=s.replace(" ,",","); if(s.length()>0) return s; } return null; } /** Check if is a valid string for a register * @param reg the string to validate * @return -1 if reg isn't a valid register, else a number of register */ private int isRegister(String reg) { try { int num; if(reg.charAt(0)=='r' || reg.charAt(0)=='R' || reg.charAt(0)=='$')//ci sono altri modi di scrivere un registro??? if(isNumber(reg.substring(1))) { num = Integer.parseInt(reg.substring(1)); if (num<32 && num>=0) return num; } if(reg.charAt(0)=='$' && (num=isAlias(reg.substring(1)))!=-1) return num; } catch(Exception e){} return -1; } /** Check if the parameter is a valid string for an alias-register * @param reg the string to validate * @return -1 if reg isn't a valid alias-register, else a number of register */ private int isAlias(String reg) { for(AliasRegister x : AliasRegister.values()) { if(reg.equalsIgnoreCase(x.name())) return x.ordinal(); } return -1; } /** Check if a string is a number * @param num the string to validate * @return true if num is a number, else false */ private boolean isNumber(String num) { if (num.charAt(0)=='+' || num.charAt(0)=='-') num = num.substring(1); for (int i=0; i<num.length(); i++) if(num.charAt(i)<'0'|| num.charAt(i)>'9') return false; return true; } /** Check if a string is a Hex number * @param num the string to validate * @return true if num is a number, else false */ private boolean isHexNumber(String num) { try { if (num.substring(0,2).compareToIgnoreCase("0X")!=0) return false; for (int i=2; i<num.length(); i++) if((num.charAt(i)<'0'|| num.charAt(i)>'9') && (num.charAt(i)<'A' || num.charAt(i)>'F')) return false; return true; } catch(Exception e) { return false; } } /** Check if a number is a valid .byte * @param num the value to validate * @return true if num is a valid .byte, else false */ private boolean isValidByte(long num) { if (num>255||num<-127) return false; return true; } /** Check if is a valid string for a register * @param imm the string to validate * @return false if imm isn't a valid immediate, else true */ private boolean isImmediate(String imm) { try { if(imm.charAt(0)=='#') imm = imm.substring(1); if(isNumber(imm)) { return true; } else if(isHexNumber(imm)) { if(imm.length()<=6) return true; } return false; } catch(Exception e) { return false; } } /** Replace all Tabulator with space * @param text the string to replace * @return a new String */ protected static String replaceTab (String text) { return text.replace("\t"," "); } /** Write a double in memory * @param row number of row * @param i * @param end * @param line the line of code * @param instr params */ private void writeDoubleInMemory (int row, int i, int end, String line, String instr ) throws MemoryElementNotFoundException { Memory mem = Memory.getInstance(); String value[] = instr.split(","); MemoryElement tmpMem = null; for(int j=0; j< Array.getLength(value);j++) { tmpMem = mem.getCell(memoryCount * 8); memoryCount++; Pattern p = Pattern.compile("-?[0-9]+.[0-9]+"); Matcher m = p.matcher(value[j]); boolean b = m.matches(); p = Pattern.compile("-?[0-9]+.[0-9]+E-?[0-9]+"); m = p.matcher(value[j]); b = b || m.matches(); /*if(isHexNumber(value[j])) { try { //insert here support for exadecimal } catch(NumberFormatException ex) { numError++; error.add("DOUBLE_TOO_LARGE",row,i+1,line); continue; } catch( Exception e)//modificare in un altro modo { e.printStackTrace(); } } else*/ if (b) { try { tmpMem.setBits (edumips64.core.fpu.FPInstructionUtils.doubleToBin(value[j] ,true),0); } catch(edumips64.core.fpu.FPExponentTooLargeException ex) { numError++; error.add("DOUBLE_EXT_TOO_LARGE",row,i+1,line); continue; } catch(edumips64.core.fpu.FPOverflowException ex) { numError++; //error.add("DOUBLE_TOO_LARGE",row,i+1,line); error.add("FP_OVERFLOW",row,i+1,line); continue; } catch(edumips64.core.fpu.FPUnderflowException ex) { numError++; //error.add("MINUS_DOUBLE_TOO_LARGE",row,i+1,line); error.add("FP_UNDERFLOW",row,i+1,line); continue; } catch(Exception e) { e.printStackTrace(); //non ci dovrebbe arrivare mai ma se per caso ci arriva che faccio? } } else { //manca riempimento errore numError++; error.add("INVALIDVALUE",row,i+1,line); i = line.length(); continue; } } } /** Write an integer in memory * @param row number of row * @param i * @param end * @param line the line of code * @param instr * @param numBit * @param name type of data */ private void writeIntegerInMemory (int row, int i, int end, String line, String instr, int numBit, String name ) throws MemoryElementNotFoundException { Memory mem = Memory.getInstance(); int posInWord=0; //position of byte to write into a doubleword String value[] = instr.split(","); MemoryElement tmpMem = null; for(int j=0; j< Array.getLength(value);j++) { if(j%(64/numBit)==0) { posInWord = 0; tmpMem = mem.getCell(memoryCount * 8); memoryCount++; } if(isNumber(value[j])) { try { long num = Long.parseLong(value[j]); if (numBit==8) tmpMem.writeByte((int)num,posInWord); else if (numBit==16) tmpMem.writeHalf((int)num,posInWord); else if (numBit==32) tmpMem.writeWord(num,posInWord); else if (numBit==64) tmpMem.writeDoubleWord(num); if( (num < -(Converter.powLong(2,numBit-1)) || num > (Converter.powLong( 2,numBit)-1)) && numBit != 64) throw new NumberFormatException(); } catch(NumberFormatException ex) { numError++; error.add(name.toUpperCase()+"_TOO_LARGE",row,i+1,line); continue; } catch(Exception e) { e.printStackTrace(); //non ci dovrebbe arrivare mai ma se per caso ci arriva che faccio? } } else if(isHexNumber(value[j])) { try { long num = Long.parseLong(Converter.hexToLong(value[j])); if (numBit==8) tmpMem.writeByte((int)num,posInWord); else if (numBit==16) tmpMem.writeHalf((int)num,posInWord); else if (numBit==32) tmpMem.writeWord(num,posInWord); else if (numBit==64) { String tmp = value[j].substring(2); while(tmp.charAt(0)=='0') tmp=tmp.substring(1); if(tmp.length()>numBit/4) throw new NumberFormatException(); tmpMem.writeDoubleWord(num); } if( (num < -(Converter.powLong(2,numBit-1)) || num > (Converter.powLong( 2,numBit)-1)) && numBit != 64) throw new NumberFormatException(); } catch(NumberFormatException ex) { numError++; error.add(name.toUpperCase() + "_TOO_LARGE",row,i+1,line); continue; } catch( Exception e)//modificare in un altro modo { e.printStackTrace(); } } else { //manca riempimento errore numError++; error.add("INVALIDVALUE",row,i+1,line); i = line.length(); continue; } posInWord += numBit/8; } } private List<String> splitStringParameters(String params, boolean auto_terminate) throws StringFormatException { List<String> pList = new LinkedList<String>(); StringBuffer temp = new StringBuffer(); edumips64.Main.logger.debug("Params: " + params); params = params.trim(); edumips64.Main.logger.debug("After trimming: " + params); int length = params.length(); boolean in_string = false; boolean escaping = false; boolean comma = false; for(int i = 0; i < length; ++i) { char c = params.charAt(i); if(!in_string) { switch(c) { case '"': if((!comma && pList.size() != 0) || i == length - 1) throw new StringFormatException(); in_string = true; comma = false; break; case ' ': case '\t': break; case ',': if(comma || i == 0 || i == length - 1) throw new StringFormatException(); comma = true; break; default: throw new StringFormatException(); } } else { if(!escaping && c == '\\') escaping = true; else if(!escaping && c == '"') { if(temp.length() > 0) { if(auto_terminate) { edumips64.Main.logger.debug("Behaving like .asciiz."); temp.append((char)0); } edumips64.Main.logger.debug("Added to pList string " + temp.toString()); pList.add(temp.toString()); temp.setLength(0); } in_string = false; } else { if(escaping) { escaping = false; temp.append('\\'); } temp.append(c); } } } if(pList.size() == 0 && in_string) // TODO: Unterminated string literal throw new StringFormatException(); return pList; } }
false
true
private void doParsing () throws IOException,ParserMultiException { boolean isFirstOutOfInstructionMemory = false; isFirstOutOfMemory = true; boolean halt = false; int row = 0; int nline=0; numError = 0; numWarning =0; int instrCount = -4; // Hack fituso by Andrea String line; error = new ParserMultiException(); warning = new ParserMultiWarningException(); LinkedList<VoidJump> voidJump = new LinkedList<VoidJump>(); Memory mem = Memory.getInstance(); memoryCount=0; String lastLabel =""; while ((line = in.readLine())!=null) //read all file { row++; for(int i=0; i<line.length(); i++) { if(line.charAt(i)==';') //comments break; if(line.charAt(i)==' ' || line.charAt(i)=='\t') continue; int tab = line.indexOf('\t',i); int space = line.indexOf(' ',i); if (tab == -1) tab=line.length(); if (space == -1) space=line.length(); int end = Math.min(tab,space)-1; String instr = line.substring(i,end+1); String parameters = null; try { if (line.charAt(i)=='.') { edumips64.Main.logger.debug("Processing " + instr); if(instr.compareToIgnoreCase(".DATA")==0) { status = 1; } else if (instr.compareToIgnoreCase(".TEXT")==0 || instr.compareToIgnoreCase(".CODE")==0 ) { status = 2; } else { String name = instr.substring(1); // The name, without the dot. if(status != 1) { numError++; error.add(name.toUpperCase() + "INCODE", row, i + 1, line); i = line.length(); continue; } try { if(!((instr.compareToIgnoreCase(".ASCII") == 0) || instr.compareToIgnoreCase(".ASCIIZ") == 0)) { // We don't want strings to be uppercase, do we? parameters = cleanFormat(line.substring(end+2)); parameters = parameters.toUpperCase(); parameters = parameters.split(";")[0]; Main.logger.debug("parameters: " + parameters); } else parameters = line.substring(end + 2); parameters = parameters.split(";")[0].trim(); Main.logger.debug("parameters: " + parameters); } catch (StringIndexOutOfBoundsException e) { numWarning++; warning.add("VALUE_MISS", row, i+1, line); error.addWarning("VALUE_MISS", row, i+1, line); memoryCount++; i = line.length(); continue; } if (instr==null) { numWarning++; warning.add("VALUE_MISS", row, i+1, line); error.addWarning("VALUE_MISS", row, i+1, line); memoryCount++; i = line.length(); continue; } MemoryElement tmpMem = null; tmpMem = mem.getCell(memoryCount * 8); Main.logger.debug("line: "+line); String[] comment = (line.substring(i)).split(";",2); if (Array.getLength(comment) == 2) { Main.logger.debug("found comments: "+comment[1]); tmpMem.setComment(comment[1]); } tmpMem.setCode(comment[0]); if(instr.compareToIgnoreCase(".ASCII") == 0 || instr.compareToIgnoreCase(".ASCIIZ") == 0) { edumips64.Main.logger.debug(".ascii(z): parameters = " + parameters); boolean auto_terminate = false; if(instr.compareToIgnoreCase(".ASCIIZ") == 0) auto_terminate = true; try { List<String> pList = splitStringParameters(parameters, auto_terminate); for(String current_string : pList) { edumips64.Main.logger.debug("Current string: [" + current_string + "]"); edumips64.Main.logger.debug(".ascii(z): requested new memory cell (" + memoryCount + ")"); tmpMem = mem.getCell(memoryCount * 8); memoryCount++; int posInWord = 0; // TODO: Controllo sui parametri (es. virgolette?) int num = current_string.length(); boolean escape = false; boolean placeholder = false; int escaped = 0; // to avoid escape sequences to count as two bytes for(int tmpi = 0; tmpi < num; tmpi++) { if((tmpi - escaped) % 8 == 0 && (tmpi - escaped) != 0 && !escape) { edumips64.Main.logger.debug(".ascii(z): requested new memory cell (" + memoryCount + ")"); tmpMem = mem.getCell(memoryCount * 8); memoryCount++; posInWord = 0; } char c = current_string.charAt(tmpi); int to_write = (int)c; edumips64.Main.logger.debug("Char: " + c + " (" + to_write + ") [" + Integer.toHexString(to_write) + "]"); if(escape) { switch(c) { case '0': to_write = 0; break; case 'n': to_write = 10; break; case 't': to_write = 9; break; case '\\': to_write = 92; break; case '"': to_write = 34; break; default: throw new StringFormatException(); } edumips64.Main.logger.debug("(escaped to [" + Integer.toHexString(to_write) + "])"); escape = false; c = 0; // to avoid re-entering the escape if branch. } if(placeholder) { if(c != '%' && c != 's' && c != 'd' && c != 'i') { edumips64.Main.logger.debug("Invalid placeholder: %" + c); // Invalid placeholder throw new StringFormatException(); } placeholder = false; } if(c == '%' && !placeholder) { edumips64.Main.logger.debug("Expecting on next step a valid placeholder..."); placeholder = true; } if(c == '\\') { escape = true; escaped++; continue; } tmpMem.writeByte(to_write, posInWord++); } } } catch(StringFormatException ex) { edumips64.Main.logger.debug("Badly formed string list"); numError++; // TODO: more descriptive error message error.add("INVALIDVALUE",row,0,line); } end = line.length(); } else if(instr.compareToIgnoreCase(".SPACE") == 0) { int posInWord=0; //position of byte to write into a doubleword memoryCount++; try { if(isHexNumber(parameters)) parameters = Converter.hexToLong(parameters); if(isNumber(parameters)) { int num = Integer.parseInt(parameters); for(int tmpi = 0; tmpi < num; tmpi++) { if(tmpi % 8 == 0 && tmpi != 0) { tmpMem = mem.getCell(memoryCount * 8); memoryCount++; posInWord = 0; } tmpMem.writeByte(0,posInWord++); } } else { throw new NumberFormatException(); } } catch(NumberFormatException ex) { numError++; error.add("INVALIDVALUE",row,i+1,line); continue; } catch(IrregularStringOfHexException ex) { numError++; error.add("INVALIDVALUE",row,i+1,line); continue; } posInWord ++; end = line.length(); } else if(instr.compareToIgnoreCase(".WORD")==0 || instr.compareToIgnoreCase(".WORD64")==0) { Main.logger.debug("pamword: "+parameters); writeIntegerInMemory(row, i, end, line, parameters, 64, "WORD"); end = line.length(); } else if (instr.compareToIgnoreCase(".WORD32")==0) { writeIntegerInMemory(row, i, end, line, parameters, 32, "WORD32"); end = line.length(); } else if(instr.compareToIgnoreCase(".BYTE")==0) { writeIntegerInMemory(row, i, end, line, parameters, 8, "BYTE"); end = line.length(); } else if(instr.compareToIgnoreCase(".WORD16")==0) { writeIntegerInMemory(row, i, end, line, parameters,16 , "WORD16"); end = line.length(); } else if(instr.compareToIgnoreCase(".DOUBLE")==0) { writeDoubleInMemory(row, i, end, line, parameters); end = line.length(); } else { numError++; error.add("INVALIDCODEFORDATA",row,i+1,line); i = line.length(); continue; } } } else if(line.charAt(end)==':') { edumips64.Main.logger.debug("Processing a label.."); if(status==1) { edumips64.Main.logger.debug("in .data section"); MemoryElement tmpMem = null; tmpMem = mem.getCell(memoryCount * 8); try { symTab.setCellLabel(memoryCount * 8, line.substring(i, end)); } catch (SameLabelsException e) { // TODO: errore del parser edumips64.Main.logger.debug("Label " + line.substring(i, end) + " is already assigned"); } } else if(status==2) { edumips64.Main.logger.debug("in .text section"); lastLabel = line.substring(i,end); } edumips64.Main.logger.debug("done"); } else { if(status!=2) { numError++; error.add("INVALIDCODEFORDATA",row,i+1,line); i = line.length(); continue; } else if (status == 2) { boolean doPack = true; end++; Instruction tmpInst; // Check for halt-like instructions String temp = cleanFormat(line.substring(i)).toUpperCase(); if(temp.equals("HALT") || temp.equals("SYSCALL 0") || temp.equals("TRAP 0")) { halt = true; } //timmy for(int timmy = 0; timmy < Array.getLength(deprecateInstruction); timmy++) { if(deprecateInstruction[timmy].toUpperCase().equals(line.substring(i, end).toUpperCase())) { warning.add("WINMIPS64_NOT_MIPS64",row,i+1,line); error.addWarning("WINMIPS64_NOT_MIPS64",row,i+1,line); numWarning ++; } } tmpInst = Instruction.buildInstruction(line.substring(i,end).toUpperCase()); if (tmpInst == null) { numError++; error.add("INVALIDCODE",row,i+1,line); i = line.length(); continue; } String syntax = tmpInst.getSyntax(); instrCount += 4; if (syntax.compareTo("")!=0 && (line.length()<end+1)) { numError++; error.add("UNKNOWNSYNTAX",row,end,line); i = line.length(); continue; } if(syntax.compareTo("")!=0) { String param = cleanFormat(line.substring(end+1)); param = param.toUpperCase(); param = param.split(";")[0].trim(); Main.logger.debug("param: " + param); int indPar=0; for(int z=0; z < syntax.length(); z++) { if(syntax.charAt(z)=='%') { z++; if(syntax.charAt(z)=='R') //register { int endPar; if(z!=syntax.length()-1) endPar = param.indexOf(syntax.charAt(++z),indPar); else endPar = param.length(); if (endPar==-1) { numError++; error.add("SEPARATORMISS",row,indPar,line); i = line.length(); tmpInst.getParams().add(0); continue; } int reg; if ((reg = isRegister(param.substring(indPar,endPar).trim()))>=0) { tmpInst.getParams().add(reg); indPar = endPar+1; } else { numError++; error.add("INVALIDREGISTER",row,line.indexOf(param.substring(indPar,endPar))+1,line); tmpInst.getParams().add(0); i = line.length(); continue; } } else if(syntax.charAt(z)=='I') //immediate { int endPar; if(z!=syntax.length()-1) endPar = param.indexOf(syntax.charAt(++z),indPar); else endPar = param.length(); if (endPar==-1) { numError++; error.add("SEPARATORMISS",row,indPar,line); i = line.length(); tmpInst.getParams().add(0); continue; } int imm; if (isImmediate(param.substring(indPar,endPar))) { if (param.charAt(indPar)=='#') indPar++; if (isNumber(param.substring(indPar,endPar))) { try { imm = Integer.parseInt(param.substring(indPar,endPar)); if( imm < -32768 || imm > 32767) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); } tmpInst.getParams().add(imm); indPar = endPar+1; } else if (isHexNumber(param.substring(indPar,endPar))) { try { try { imm = (int) Long.parseLong(Converter.hexToShort(param.substring(indPar,endPar))); Main.logger.debug("imm = "+ imm); if( imm < -32768 || imm > 32767) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); } tmpInst.getParams().add(imm); indPar = endPar+1; } catch(IrregularStringOfHexException ex) { //non ci dovrebbe mai arrivare } } } else { try { int offset=0,cc; MemoryElement tmpMem; cc = param.indexOf("+",indPar); if (cc!=-1) { tmpMem = symTab.getCell(param.substring(indPar,cc).trim()); if (isNumber(param.substring(cc+1,endPar))) { try { imm = Integer.parseInt(param.substring(indPar,endPar)); if( imm < -32768 || imm > 32767) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); } tmpInst.getParams().add(tmpMem.getAddress() + imm); indPar = endPar+1; } else if (isHexNumber(param.substring(cc+1,endPar))) { try { try { imm = (int) Long.parseLong(Converter.hexToLong(param.substring(indPar,endPar))); if( imm < -32768 || imm > 32767) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); } tmpInst.getParams().add(tmpMem.getAddress() + imm); indPar = endPar+1; } catch(IrregularStringOfHexException ex) { //non ci dovrebbe mai arrivare } } else { MemoryElement tmpMem1 = symTab.getCell(param.substring(cc+1,endPar).trim()); tmpInst.getParams().add(tmpMem.getAddress() + tmpMem1.getAddress()); } } else { cc = param.indexOf("-",indPar); if (cc!=-1) { tmpMem = symTab.getCell(param.substring(indPar,cc).trim()); if (isNumber(param.substring(cc+1,endPar))) { try { imm = Integer.parseInt(param.substring(indPar,endPar)); if( imm < -32768 || imm > 32767) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); } tmpInst.getParams().add(tmpMem.getAddress() - imm); indPar = endPar+1; } else if (isHexNumber(param.substring(cc+1,endPar))) { try { try { imm = (int) Long.parseLong(Converter.hexToLong(param.substring(indPar,endPar))); if( imm < -32768 || imm > 32767) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); } tmpInst.getParams().add(tmpMem.getAddress() - imm); indPar = endPar+1; } catch(IrregularStringOfHexException ex) { //non ci dovrebbe mai arrivare } } else { MemoryElement tmpMem1 = symTab.getCell(param.substring(cc+1,endPar).trim()); tmpInst.getParams().add(tmpMem.getAddress() - tmpMem1.getAddress()); } } else { tmpMem = symTab.getCell(param.substring(indPar,endPar).trim()); tmpInst.getParams().add(tmpMem.getAddress()); } } } catch(MemoryElementNotFoundException ex) { numError++; error.add("INVALIDIMMEDIATE",row,line.indexOf(param.substring(indPar,endPar))+1,line); i = line.length(); tmpInst.getParams().add(0); continue; } } } else if(syntax.charAt(z)=='U') //Unsigned Immediate (5 bit) { int endPar; if(z!=syntax.length()-1) endPar = param.indexOf(syntax.charAt(++z),indPar); else endPar = param.length(); if (endPar==-1) { numError++; error.add("SEPARATORMISS",row,indPar,line); i = line.length(); tmpInst.getParams().add(0); continue; } int imm; if (isImmediate(param.substring(indPar,endPar))) { if (param.charAt(indPar)=='#') indPar++; if (isNumber(param.substring(indPar,endPar))) { try{ imm = Integer.parseInt(param.substring(indPar,endPar).trim()); if (imm < 0) { numError++; error.add("VALUEISNOTUNSIGNED",row,line.indexOf(param.substring(indPar,endPar))+1,line); i = line.length(); tmpInst.getParams().add(0); continue; } if( imm < 0 || imm > 31) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("5BIT_IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); } tmpInst.getParams().add(imm); indPar = endPar+1; } else if (isHexNumber(param.substring(indPar,endPar).trim())) { try { imm = (int) Long.parseLong(Converter.hexToLong(param.substring(indPar,endPar))); if (imm < 0) { numError++; error.add("VALUEISNOTUNSIGNED",row,line.indexOf(param.substring(indPar,endPar))+1,line); i = line.length(); tmpInst.getParams().add(0); continue; } tmpInst.getParams().add(imm); indPar = endPar+1; if( imm < 0 || imm > 31) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("5BIT_IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); tmpInst.getParams().add(imm); indPar = endPar+1; } catch(IrregularStringOfHexException ex) { //non ci dovrebbe mai arrivare } } } else { numError++; error.add("INVALIDIMMEDIATE",row,line.indexOf(param.substring(indPar,endPar))+1,line); i = line.length(); tmpInst.getParams().add(0); continue; } } else if(syntax.charAt(z)=='L') //Memory Label { int endPar; if(z!=syntax.length()-1) endPar = param.indexOf(syntax.charAt(++z),indPar); else endPar = param.length(); if (endPar==-1) { numError++; error.add("SEPARATORMISS",row,indPar,line); i = line.length(); tmpInst.getParams().add(0); continue; } try { MemoryElement tmpMem; if(param.substring(indPar,endPar).equals("")) tmpInst.getParams().add(0); else if(isNumber(param.substring(indPar,endPar).trim())) { int tmp = Integer.parseInt(param.substring(indPar,endPar).trim()); if (tmp<0) { numError++; error.add("LABELNOTFOUND",row,line.indexOf(param.substring(indPar,endPar))+1,line); i = line.length(); indPar = endPar+1; tmpInst.getParams().add(0); continue; } tmpInst.getParams().add(tmp); } else { int offset=0,cc; cc = param.indexOf("+",indPar); if (cc!=-1) { tmpMem = symTab.getCell(param.substring(indPar,cc).trim()); try { tmpInst.getParams().add(tmpMem.getAddress() + Integer.parseInt(param.substring(cc+1,endPar))); } catch(NumberFormatException ex) { numError++; error.add("LABELNOTFOUND",row,line.indexOf(param.substring(indPar,endPar))+1,line); i = line.length(); indPar = endPar+1; tmpInst.getParams().add(0); continue; } } else { cc = param.indexOf("-",indPar); if (cc!=-1) { tmpMem = symTab.getCell(param.substring(indPar,cc).trim()); try { tmpInst.getParams().add(tmpMem.getAddress() - Integer.parseInt(param.substring(cc+1,endPar))); } catch(NumberFormatException ex) { numError++; error.add("LABELNOTFOUND",row,line.indexOf(param.substring(indPar,endPar))+1,line); i = line.length(); indPar = endPar+1; tmpInst.getParams().add(0); continue; } } else { tmpMem = symTab.getCell(param.substring(indPar,endPar).trim()); tmpInst.getParams().add(tmpMem.getAddress()); } } } indPar = endPar+1; } catch (MemoryElementNotFoundException e) { numError++; error.add("LABELNOTFOUND",row,line.indexOf(param.substring(indPar,endPar))+1,line); i = line.length(); indPar = endPar+1; tmpInst.getParams().add(0); continue; } } else if(syntax.charAt(z)=='E') //Instruction Label { int endPar; if(z!=syntax.length()-1) endPar = param.indexOf(syntax.charAt(++z),indPar); else endPar = param.length(); if (endPar==-1) { numError++; error.add("SEPARATORMISS",row,indPar,line); i = line.length(); tmpInst.getParams().add(0); continue; } Integer labelAddr = symTab.getInstructionAddress(param.substring(indPar,endPar).trim()); if (labelAddr != null) { tmpInst.getParams().add(labelAddr); } else { VoidJump tmpVoid = new VoidJump(); tmpVoid.instr = tmpInst; tmpVoid.row = row; tmpVoid.line = line; tmpVoid.column = indPar; tmpVoid.label = param.substring(indPar,endPar); voidJump.add(tmpVoid); doPack = false; } } else if(syntax.charAt(z)=='B') //Instruction Label for branch { int endPar; if(z!=syntax.length()-1) endPar = param.indexOf(syntax.charAt(++z),indPar); else endPar = param.length(); if (endPar==-1) { numError++; error.add("SEPARATORMISS",row,indPar,line); i = line.length(); tmpInst.getParams().add(0); continue; } Integer labelAddr = symTab.getInstructionAddress(param.substring(indPar,endPar).trim()); if (labelAddr != null) { labelAddr -= instrCount + 4; tmpInst.getParams().add(labelAddr); } else { VoidJump tmpVoid = new VoidJump(); tmpVoid.instr = tmpInst; tmpVoid.row = row; tmpVoid.line = line; tmpVoid.column = indPar; tmpVoid.label = param.substring(indPar,endPar); tmpVoid.instrCount = instrCount; tmpVoid.isBranch = true; voidJump.add(tmpVoid); doPack = false; } } else { numError++; error.add("UNKNOWNSYNTAX",row,1,line); i = line.length(); tmpInst.getParams().add(0); continue; } } else { if(syntax.charAt(z)!=param.charAt(indPar++)) { numError++; error.add("UNKNOWNSYNTAX",row,1,line); i = line.length(); tmpInst.getParams().add(0); continue; } } } if( i == line.length()) continue; try { if (doPack) tmpInst.pack(); } catch(IrregularStringOfBitsException ex) { //ISGROUP HA SBAGLIATO QUALCOSA } } else { try { tmpInst.pack(); } catch(IrregularStringOfBitsException e) { } } Main.logger.debug("line: "+line); String comment[] = line.split(";",2); tmpInst.setFullName(replaceTab(comment[0].substring(i))); tmpInst.setFullName(replaceTab(comment[0].substring(i))); tmpInst.setFullName(replaceTab(comment[0].substring(i))); tmpInst.setFullName(replaceTab(comment[0].substring(i))); if (Array.getLength(comment)==2) if (Array.getLength(comment)==2) tmpInst.setComment(comment[1]); try { mem.addInstruction(tmpInst,instrCount); symTab.setInstructionLabel(instrCount, lastLabel.toUpperCase()); } catch(SymbolTableOverflowException ex) { if(isFirstOutOfInstructionMemory)//is first out of memory? { isFirstOutOfInstructionMemory = false; numError++; error.add("OUTOFINSTRUCTIONMEMORY",row,i+1,line); i = line.length(); continue; } } catch(SameLabelsException ex) { numError++; error.add("SAMELABEL", row, 1, line); i = line.length(); } // Il finally e' totalmente inutile, ma è bello utilizzarlo per la // prima volta in un programma ;) finally { lastLabel = ""; } end = line.length(); } } i=end; } catch(MemoryElementNotFoundException ex) { if(isFirstOutOfMemory)//is first out of memory? { isFirstOutOfMemory = false; numError++; error.add("OUTOFMEMORY",row,i+1,line); i = line.length(); continue; } } catch(IrregularWriteOperationException ex) { numError++; error.add("INVALIDVALUE",row,i+1,line); break; } } } for (int i=0; i< voidJump.size();i++) { Integer labelAddr = symTab.getInstructionAddress(voidJump.get(i).label.trim()); if (labelAddr != null) { if (voidJump.get(i).isBranch) labelAddr -= voidJump.get(i).instrCount + 4; voidJump.get(i).instr.getParams().add(labelAddr); try { voidJump.get(i).instr.pack(); } catch(IrregularStringOfBitsException ex) { //ISGROUP HA SBAGLIATO QUALCOSA } } else { numError++; error.add("LABELNOTFOUND",voidJump.get(i).row,voidJump.get(i).column ,voidJump.get(i).line); continue; } } in.close(); if(!halt) //if Halt is not present in code { numWarning++; warning.add("HALT_NOT_PRESENT",row,0,""); error.addWarning("HALT_NOT_PRESENT",row,0,""); try { Instruction tmpInst = Instruction.buildInstruction("SYSCALL"); tmpInst.getParams().add(0); tmpInst.setFullName("SYSCALL 0"); try { tmpInst.pack(); } catch(IrregularStringOfBitsException ex) { //ISGROUP HA SBAGLIATO QUALCOSA } mem.addInstruction(tmpInst,(instrCount+4)); symTab.setInstructionLabel((instrCount+4), ""); } catch(SymbolTableOverflowException ex) { if(isFirstOutOfInstructionMemory)//is first out of memory? { isFirstOutOfInstructionMemory = false; numError++; error.add("OUTOFINSTRUCTIONMEMORY",row,0,"Halt"); } } catch(SameLabelsException ex) {} // impossible } if (numError>0) { throw error; } else if (numWarning > 0) { throw warning; } }
private void doParsing () throws IOException,ParserMultiException { boolean isFirstOutOfInstructionMemory = false; isFirstOutOfMemory = true; boolean halt = false; int row = 0; int nline=0; numError = 0; numWarning =0; int instrCount = -4; // Hack fituso by Andrea String line; error = new ParserMultiException(); warning = new ParserMultiWarningException(); LinkedList<VoidJump> voidJump = new LinkedList<VoidJump>(); Memory mem = Memory.getInstance(); memoryCount=0; String lastLabel =""; while ((line = in.readLine())!=null) //read all file { row++; for(int i=0; i<line.length(); i++) { if(line.charAt(i)==';') //comments break; if(line.charAt(i)==' ' || line.charAt(i)=='\t') continue; int tab = line.indexOf('\t',i); int space = line.indexOf(' ',i); if (tab == -1) tab=line.length(); if (space == -1) space=line.length(); int end = Math.min(tab,space)-1; String instr = line.substring(i,end+1); String parameters = null; try { if (line.charAt(i)=='.') { edumips64.Main.logger.debug("Processing " + instr); if(instr.compareToIgnoreCase(".DATA")==0) { status = 1; } else if (instr.compareToIgnoreCase(".TEXT")==0 || instr.compareToIgnoreCase(".CODE")==0 ) { status = 2; } else { String name = instr.substring(1); // The name, without the dot. if(status != 1) { numError++; error.add(name.toUpperCase() + "INCODE", row, i + 1, line); i = line.length(); continue; } try { if(!((instr.compareToIgnoreCase(".ASCII") == 0) || instr.compareToIgnoreCase(".ASCIIZ") == 0)) { // We don't want strings to be uppercase, do we? parameters = cleanFormat(line.substring(end+2)); parameters = parameters.toUpperCase(); parameters = parameters.split(";")[0]; Main.logger.debug("parameters: " + parameters); } else parameters = line.substring(end + 2); parameters = parameters.split(";")[0].trim(); Main.logger.debug("parameters: " + parameters); } catch (StringIndexOutOfBoundsException e) { numWarning++; warning.add("VALUE_MISS", row, i+1, line); error.addWarning("VALUE_MISS", row, i+1, line); memoryCount++; i = line.length(); continue; } if (instr==null) { numWarning++; warning.add("VALUE_MISS", row, i+1, line); error.addWarning("VALUE_MISS", row, i+1, line); memoryCount++; i = line.length(); continue; } MemoryElement tmpMem = null; tmpMem = mem.getCell(memoryCount * 8); Main.logger.debug("line: "+line); String[] comment = (line.substring(i)).split(";",2); if (Array.getLength(comment) == 2) { Main.logger.debug("found comments: "+comment[1]); tmpMem.setComment(comment[1]); } tmpMem.setCode(comment[0]); if(instr.compareToIgnoreCase(".ASCII") == 0 || instr.compareToIgnoreCase(".ASCIIZ") == 0) { edumips64.Main.logger.debug(".ascii(z): parameters = " + parameters); boolean auto_terminate = false; if(instr.compareToIgnoreCase(".ASCIIZ") == 0) auto_terminate = true; try { List<String> pList = splitStringParameters(parameters, auto_terminate); for(String current_string : pList) { edumips64.Main.logger.debug("Current string: [" + current_string + "]"); edumips64.Main.logger.debug(".ascii(z): requested new memory cell (" + memoryCount + ")"); tmpMem = mem.getCell(memoryCount * 8); memoryCount++; int posInWord = 0; // TODO: Controllo sui parametri (es. virgolette?) int num = current_string.length(); boolean escape = false; boolean placeholder = false; int escaped = 0; // to avoid escape sequences to count as two bytes for(int tmpi = 0; tmpi < num; tmpi++) { if((tmpi - escaped) % 8 == 0 && (tmpi - escaped) != 0 && !escape) { edumips64.Main.logger.debug(".ascii(z): requested new memory cell (" + memoryCount + ")"); tmpMem = mem.getCell(memoryCount * 8); memoryCount++; posInWord = 0; } char c = current_string.charAt(tmpi); int to_write = (int)c; edumips64.Main.logger.debug("Char: " + c + " (" + to_write + ") [" + Integer.toHexString(to_write) + "]"); if(escape) { switch(c) { case '0': to_write = 0; break; case 'n': to_write = 10; break; case 't': to_write = 9; break; case '\\': to_write = 92; break; case '"': to_write = 34; break; default: throw new StringFormatException(); } edumips64.Main.logger.debug("(escaped to [" + Integer.toHexString(to_write) + "])"); escape = false; c = 0; // to avoid re-entering the escape if branch. } if(placeholder) { if(c != '%' && c != 's' && c != 'd' && c != 'i') { edumips64.Main.logger.debug("Invalid placeholder: %" + c); // Invalid placeholder throw new StringFormatException(); } placeholder = false; } if(c == '%' && !placeholder) { edumips64.Main.logger.debug("Expecting on next step a valid placeholder..."); placeholder = true; } if(c == '\\') { escape = true; escaped++; continue; } tmpMem.writeByte(to_write, posInWord++); } } } catch(StringFormatException ex) { edumips64.Main.logger.debug("Badly formed string list"); numError++; // TODO: more descriptive error message error.add("INVALIDVALUE",row,0,line); } end = line.length(); } else if(instr.compareToIgnoreCase(".SPACE") == 0) { int posInWord=0; //position of byte to write into a doubleword memoryCount++; try { if(isHexNumber(parameters)) parameters = Converter.hexToLong(parameters); if(isNumber(parameters)) { int num = Integer.parseInt(parameters); for(int tmpi = 0; tmpi < num; tmpi++) { if(tmpi % 8 == 0 && tmpi != 0) { tmpMem = mem.getCell(memoryCount * 8); memoryCount++; posInWord = 0; } tmpMem.writeByte(0,posInWord++); } } else { throw new NumberFormatException(); } } catch(NumberFormatException ex) { numError++; error.add("INVALIDVALUE",row,i+1,line); continue; } catch(IrregularStringOfHexException ex) { numError++; error.add("INVALIDVALUE",row,i+1,line); continue; } posInWord ++; end = line.length(); } else if(instr.compareToIgnoreCase(".WORD")==0 || instr.compareToIgnoreCase(".WORD64")==0) { Main.logger.debug("pamword: "+parameters); writeIntegerInMemory(row, i, end, line, parameters, 64, "WORD"); end = line.length(); } else if (instr.compareToIgnoreCase(".WORD32")==0) { writeIntegerInMemory(row, i, end, line, parameters, 32, "WORD32"); end = line.length(); } else if(instr.compareToIgnoreCase(".BYTE")==0) { writeIntegerInMemory(row, i, end, line, parameters, 8, "BYTE"); end = line.length(); } else if(instr.compareToIgnoreCase(".WORD16")==0) { writeIntegerInMemory(row, i, end, line, parameters,16 , "WORD16"); end = line.length(); } else if(instr.compareToIgnoreCase(".DOUBLE")==0) { writeDoubleInMemory(row, i, end, line, parameters); end = line.length(); } else { numError++; error.add("INVALIDCODEFORDATA",row,i+1,line); i = line.length(); continue; } } } else if(line.charAt(end)==':') { edumips64.Main.logger.debug("Processing a label.."); if(status==1) { edumips64.Main.logger.debug("in .data section"); MemoryElement tmpMem = null; tmpMem = mem.getCell(memoryCount * 8); try { symTab.setCellLabel(memoryCount * 8, line.substring(i, end)); } catch (SameLabelsException e) { // TODO: errore del parser edumips64.Main.logger.debug("Label " + line.substring(i, end) + " is already assigned"); } } else if(status==2) { edumips64.Main.logger.debug("in .text section"); lastLabel = line.substring(i,end); } edumips64.Main.logger.debug("done"); } else { if(status!=2) { numError++; error.add("INVALIDCODEFORDATA",row,i+1,line); i = line.length(); continue; } else if (status == 2) { boolean doPack = true; end++; Instruction tmpInst; // Check for halt-like instructions String temp = cleanFormat(line.substring(i)).toUpperCase(); if(temp.equals("HALT") || temp.equals("SYSCALL 0") || temp.equals("TRAP 0")) { halt = true; } //timmy for(int timmy = 0; timmy < Array.getLength(deprecateInstruction); timmy++) { if(deprecateInstruction[timmy].toUpperCase().equals(line.substring(i, end).toUpperCase())) { warning.add("WINMIPS64_NOT_MIPS64",row,i+1,line); error.addWarning("WINMIPS64_NOT_MIPS64",row,i+1,line); numWarning ++; } } tmpInst = Instruction.buildInstruction(line.substring(i,end).toUpperCase()); if (tmpInst == null) { numError++; error.add("INVALIDCODE",row,i+1,line); i = line.length(); continue; } String syntax = tmpInst.getSyntax(); instrCount += 4; if (syntax.compareTo("")!=0 && (line.length()<end+1)) { numError++; error.add("UNKNOWNSYNTAX",row,end,line); i = line.length(); continue; } if(syntax.compareTo("")!=0) { String param = cleanFormat(line.substring(end+1)); param = param.toUpperCase(); param = param.split(";")[0].trim(); Main.logger.debug("param: " + param); int indPar=0; for(int z=0; z < syntax.length(); z++) { if(syntax.charAt(z)=='%') { z++; if(syntax.charAt(z)=='R') //register { int endPar; if(z!=syntax.length()-1) endPar = param.indexOf(syntax.charAt(++z),indPar); else endPar = param.length(); if (endPar==-1) { numError++; error.add("SEPARATORMISS",row,indPar,line); i = line.length(); tmpInst.getParams().add(0); continue; } int reg; if ((reg = isRegister(param.substring(indPar,endPar).trim()))>=0) { tmpInst.getParams().add(reg); indPar = endPar+1; } else { numError++; error.add("INVALIDREGISTER",row,line.indexOf(param.substring(indPar,endPar))+1,line); tmpInst.getParams().add(0); i = line.length(); continue; } } else if(syntax.charAt(z)=='I') //immediate { int endPar; if(z!=syntax.length()-1) endPar = param.indexOf(syntax.charAt(++z),indPar); else endPar = param.length(); if (endPar==-1) { numError++; error.add("SEPARATORMISS",row,indPar,line); i = line.length(); tmpInst.getParams().add(0); continue; } int imm; if (isImmediate(param.substring(indPar,endPar))) { if (param.charAt(indPar)=='#') indPar++; if (isNumber(param.substring(indPar,endPar))) { try { imm = Integer.parseInt(param.substring(indPar,endPar)); if( imm < -32768 || imm > 32767) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); } tmpInst.getParams().add(imm); indPar = endPar+1; } else if (isHexNumber(param.substring(indPar,endPar))) { try { try { imm = (int) Long.parseLong(Converter.hexToShort(param.substring(indPar,endPar))); Main.logger.debug("imm = "+ imm); if( imm < -32768 || imm > 32767) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); } tmpInst.getParams().add(imm); indPar = endPar+1; } catch(IrregularStringOfHexException ex) { //non ci dovrebbe mai arrivare } } } else { try { int offset=0,cc; MemoryElement tmpMem; cc = param.indexOf("+",indPar); if (cc!=-1) { tmpMem = symTab.getCell(param.substring(indPar,cc).trim()); if (isNumber(param.substring(cc+1,endPar))) { try { imm = Integer.parseInt(param.substring(indPar,endPar)); if( imm < -32768 || imm > 32767) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); } tmpInst.getParams().add(tmpMem.getAddress() + imm); indPar = endPar+1; } else if (isHexNumber(param.substring(cc+1,endPar))) { try { try { imm = (int) Long.parseLong(Converter.hexToLong(param.substring(indPar,endPar))); if( imm < -32768 || imm > 32767) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); } tmpInst.getParams().add(tmpMem.getAddress() + imm); indPar = endPar+1; } catch(IrregularStringOfHexException ex) { //non ci dovrebbe mai arrivare } } else { MemoryElement tmpMem1 = symTab.getCell(param.substring(cc+1,endPar).trim()); tmpInst.getParams().add(tmpMem.getAddress() + tmpMem1.getAddress()); } } else { cc = param.indexOf("-",indPar); if (cc!=-1) { tmpMem = symTab.getCell(param.substring(indPar,cc).trim()); if (isNumber(param.substring(cc+1,endPar))) { try { imm = Integer.parseInt(param.substring(indPar,endPar)); if( imm < -32768 || imm > 32767) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); } tmpInst.getParams().add(tmpMem.getAddress() - imm); indPar = endPar+1; } else if (isHexNumber(param.substring(cc+1,endPar))) { try { try { imm = (int) Long.parseLong(Converter.hexToLong(param.substring(indPar,endPar))); if( imm < -32768 || imm > 32767) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); } tmpInst.getParams().add(tmpMem.getAddress() - imm); indPar = endPar+1; } catch(IrregularStringOfHexException ex) { //non ci dovrebbe mai arrivare } } else { MemoryElement tmpMem1 = symTab.getCell(param.substring(cc+1,endPar).trim()); tmpInst.getParams().add(tmpMem.getAddress() - tmpMem1.getAddress()); } } else { tmpMem = symTab.getCell(param.substring(indPar,endPar).trim()); tmpInst.getParams().add(tmpMem.getAddress()); } } } catch(MemoryElementNotFoundException ex) { numError++; error.add("INVALIDIMMEDIATE",row,line.indexOf(param.substring(indPar,endPar))+1,line); i = line.length(); tmpInst.getParams().add(0); continue; } } } else if(syntax.charAt(z)=='U') //Unsigned Immediate (5 bit) { int endPar; if(z!=syntax.length()-1) endPar = param.indexOf(syntax.charAt(++z),indPar); else endPar = param.length(); if (endPar==-1) { numError++; error.add("SEPARATORMISS",row,indPar,line); i = line.length(); tmpInst.getParams().add(0); continue; } int imm; if (isImmediate(param.substring(indPar,endPar))) { if (param.charAt(indPar)=='#') indPar++; if (isNumber(param.substring(indPar,endPar))) { try{ imm = Integer.parseInt(param.substring(indPar,endPar).trim()); if (imm < 0) { numError++; error.add("VALUEISNOTUNSIGNED",row,line.indexOf(param.substring(indPar,endPar))+1,line); i = line.length(); tmpInst.getParams().add(0); continue; } if( imm < 0 || imm > 31) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("5BIT_IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); } tmpInst.getParams().add(imm); indPar = endPar+1; } else if (isHexNumber(param.substring(indPar,endPar).trim())) { try { imm = (int) Long.parseLong(Converter.hexToLong(param.substring(indPar,endPar))); if (imm < 0) { numError++; error.add("VALUEISNOTUNSIGNED",row,line.indexOf(param.substring(indPar,endPar))+1,line); i = line.length(); tmpInst.getParams().add(0); continue; } tmpInst.getParams().add(imm); indPar = endPar+1; if( imm < 0 || imm > 31) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("5BIT_IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); tmpInst.getParams().add(imm); indPar = endPar+1; } catch(IrregularStringOfHexException ex) { //non ci dovrebbe mai arrivare } } } else { numError++; error.add("INVALIDIMMEDIATE",row,line.indexOf(param.substring(indPar,endPar))+1,line); i = line.length(); tmpInst.getParams().add(0); continue; } } else if(syntax.charAt(z)=='L') //Memory Label { int endPar; if(z!=syntax.length()-1) endPar = param.indexOf(syntax.charAt(++z),indPar); else endPar = param.length(); if (endPar==-1) { numError++; error.add("SEPARATORMISS",row,indPar,line); i = line.length(); tmpInst.getParams().add(0); continue; } try { MemoryElement tmpMem; if(param.substring(indPar,endPar).equals("")) tmpInst.getParams().add(0); else if(isNumber(param.substring(indPar,endPar).trim())) { int tmp = Integer.parseInt(param.substring(indPar,endPar).trim()); if (tmp<0 || tmp%4!=0 ) { numError++; error.add("MEMORYADDRESSINVALID",row,line.indexOf(param.substring(indPar,endPar))+1,line); i = line.length(); indPar = endPar+1; tmpInst.getParams().add(0); continue; } tmpInst.getParams().add(tmp); } else { int offset=0,cc; cc = param.indexOf("+",indPar); if (cc!=-1) { tmpMem = symTab.getCell(param.substring(indPar,cc).trim()); try { tmpInst.getParams().add(tmpMem.getAddress() + Integer.parseInt(param.substring(cc+1,endPar))); } catch(NumberFormatException ex) { numError++; error.add("LABELNOTFOUND",row,line.indexOf(param.substring(indPar,endPar))+1,line); i = line.length(); indPar = endPar+1; tmpInst.getParams().add(0); continue; } } else { cc = param.indexOf("-",indPar); if (cc!=-1) { tmpMem = symTab.getCell(param.substring(indPar,cc).trim()); try { tmpInst.getParams().add(tmpMem.getAddress() - Integer.parseInt(param.substring(cc+1,endPar))); } catch(NumberFormatException ex) { numError++; error.add("LABELNOTFOUND",row,line.indexOf(param.substring(indPar,endPar))+1,line); i = line.length(); indPar = endPar+1; tmpInst.getParams().add(0); continue; } } else { tmpMem = symTab.getCell(param.substring(indPar,endPar).trim()); tmpInst.getParams().add(tmpMem.getAddress()); } } } indPar = endPar+1; } catch (MemoryElementNotFoundException e) { numError++; error.add("LABELNOTFOUND",row,line.indexOf(param.substring(indPar,endPar))+1,line); i = line.length(); indPar = endPar+1; tmpInst.getParams().add(0); continue; } } else if(syntax.charAt(z)=='E') //Instruction Label { int endPar; if(z!=syntax.length()-1) endPar = param.indexOf(syntax.charAt(++z),indPar); else endPar = param.length(); if (endPar==-1) { numError++; error.add("SEPARATORMISS",row,indPar,line); i = line.length(); tmpInst.getParams().add(0); continue; } Integer labelAddr = symTab.getInstructionAddress(param.substring(indPar,endPar).trim()); if (labelAddr != null) { tmpInst.getParams().add(labelAddr); } else { VoidJump tmpVoid = new VoidJump(); tmpVoid.instr = tmpInst; tmpVoid.row = row; tmpVoid.line = line; tmpVoid.column = indPar; tmpVoid.label = param.substring(indPar,endPar); voidJump.add(tmpVoid); doPack = false; } } else if(syntax.charAt(z)=='B') //Instruction Label for branch { int endPar; if(z!=syntax.length()-1) endPar = param.indexOf(syntax.charAt(++z),indPar); else endPar = param.length(); if (endPar==-1) { numError++; error.add("SEPARATORMISS",row,indPar,line); i = line.length(); tmpInst.getParams().add(0); continue; } Integer labelAddr = symTab.getInstructionAddress(param.substring(indPar,endPar).trim()); if (labelAddr != null) { labelAddr -= instrCount + 4; tmpInst.getParams().add(labelAddr); } else { VoidJump tmpVoid = new VoidJump(); tmpVoid.instr = tmpInst; tmpVoid.row = row; tmpVoid.line = line; tmpVoid.column = indPar; tmpVoid.label = param.substring(indPar,endPar); tmpVoid.instrCount = instrCount; tmpVoid.isBranch = true; voidJump.add(tmpVoid); doPack = false; } } else { numError++; error.add("UNKNOWNSYNTAX",row,1,line); i = line.length(); tmpInst.getParams().add(0); continue; } } else { if(syntax.charAt(z)!=param.charAt(indPar++)) { numError++; error.add("UNKNOWNSYNTAX",row,1,line); i = line.length(); tmpInst.getParams().add(0); continue; } } } if( i == line.length()) continue; try { if (doPack) tmpInst.pack(); } catch(IrregularStringOfBitsException ex) { //ISGROUP HA SBAGLIATO QUALCOSA } } else { try { tmpInst.pack(); } catch(IrregularStringOfBitsException e) { } } Main.logger.debug("line: "+line); String comment[] = line.split(";",2); tmpInst.setFullName(replaceTab(comment[0].substring(i))); tmpInst.setFullName(replaceTab(comment[0].substring(i))); tmpInst.setFullName(replaceTab(comment[0].substring(i))); tmpInst.setFullName(replaceTab(comment[0].substring(i))); if (Array.getLength(comment)==2) if (Array.getLength(comment)==2) tmpInst.setComment(comment[1]); try { mem.addInstruction(tmpInst,instrCount); symTab.setInstructionLabel(instrCount, lastLabel.toUpperCase()); } catch(SymbolTableOverflowException ex) { if(isFirstOutOfInstructionMemory)//is first out of memory? { isFirstOutOfInstructionMemory = false; numError++; error.add("OUTOFINSTRUCTIONMEMORY",row,i+1,line); i = line.length(); continue; } } catch(SameLabelsException ex) { numError++; error.add("SAMELABEL", row, 1, line); i = line.length(); } // Il finally e' totalmente inutile, ma è bello utilizzarlo per la // prima volta in un programma ;) finally { lastLabel = ""; } end = line.length(); } } i=end; } catch(MemoryElementNotFoundException ex) { if(isFirstOutOfMemory)//is first out of memory? { isFirstOutOfMemory = false; numError++; error.add("OUTOFMEMORY",row,i+1,line); i = line.length(); continue; } } catch(IrregularWriteOperationException ex) { numError++; error.add("INVALIDVALUE",row,i+1,line); break; } } } for (int i=0; i< voidJump.size();i++) { Integer labelAddr = symTab.getInstructionAddress(voidJump.get(i).label.trim()); if (labelAddr != null) { if (voidJump.get(i).isBranch) labelAddr -= voidJump.get(i).instrCount + 4; voidJump.get(i).instr.getParams().add(labelAddr); try { voidJump.get(i).instr.pack(); } catch(IrregularStringOfBitsException ex) { //ISGROUP HA SBAGLIATO QUALCOSA } } else { numError++; error.add("LABELNOTFOUND",voidJump.get(i).row,voidJump.get(i).column ,voidJump.get(i).line); continue; } } in.close(); if(!halt) //if Halt is not present in code { numWarning++; warning.add("HALT_NOT_PRESENT",row,0,""); error.addWarning("HALT_NOT_PRESENT",row,0,""); try { Instruction tmpInst = Instruction.buildInstruction("SYSCALL"); tmpInst.getParams().add(0); tmpInst.setFullName("SYSCALL 0"); try { tmpInst.pack(); } catch(IrregularStringOfBitsException ex) { //ISGROUP HA SBAGLIATO QUALCOSA } mem.addInstruction(tmpInst,(instrCount+4)); symTab.setInstructionLabel((instrCount+4), ""); } catch(SymbolTableOverflowException ex) { if(isFirstOutOfInstructionMemory)//is first out of memory? { isFirstOutOfInstructionMemory = false; numError++; error.add("OUTOFINSTRUCTIONMEMORY",row,0,"Halt"); } } catch(SameLabelsException ex) {} // impossible } if (numError>0) { throw error; } else if (numWarning > 0) { throw warning; } }
diff --git a/com/imjake9/snes/tile/gui/DrawingPanel.java b/com/imjake9/snes/tile/gui/DrawingPanel.java index d4c89ce..faf13ce 100644 --- a/com/imjake9/snes/tile/gui/DrawingPanel.java +++ b/com/imjake9/snes/tile/gui/DrawingPanel.java @@ -1,311 +1,314 @@ package com.imjake9.snes.tile.gui; import com.imjake9.snes.tile.DataConverter; import com.imjake9.snes.tile.SNESTile; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Composite; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.image.BufferedImage; import javax.swing.JPanel; import javax.swing.JViewport; import javax.swing.Scrollable; import javax.swing.SwingConstants; public class DrawingPanel extends JPanel implements MouseListener, MouseMotionListener, Scrollable { private BufferedImage buffer; private BufferedImage overlay; private PalettePanel palette; private byte[] data; private int scalingFactor = 2; private Tool currentTool = Tool.MARQUEE; public DrawingPanel() { this.setBackground(Color.BLACK); this.addMouseListener(this); this.addMouseMotionListener(this); } public void setPalette(PalettePanel palette) { this.palette = palette; } public void setData(byte[] data) { this.data = DataConverter.fromSNES4BPP(data); repaintAll(); } public byte[] getData() { return DataConverter.toSNES4BPP(data); } public int getScalingFactor() { return scalingFactor; } public void setCurrentTool(Tool tool) { currentTool = tool; } public void setCurrentTool(String tool) { currentTool = Tool.valueOf(tool); } public Tool getCurrentTool() { return currentTool; } public void setPixelColor(Point location, byte index) { Color color = palette.getColor(index); buffer.setRGB(location.x, location.y, color.getRGB()); int tile = location.x/8 + (location.y / 8)*16; int pixel = location.x%8 + (location.y%8)*8; data[tile*64 + pixel] = index; repaint(); } public Graphics2D getOverlay() { return overlay.createGraphics(); } public void clearOverlay() { Graphics2D g = getOverlay(); Composite c = g.getComposite(); g.setComposite(AlphaComposite.Src); g.setColor(new Color(0x00000000, true)); g.fillRect(0, 0, overlay.getWidth(), overlay.getHeight()); g.setComposite(c); } @Override public void paintComponent(Graphics g) { g.setColor(Color.BLACK); g.fillRect(0, 0, this.getWidth(), this.getHeight()); if (palette == null || data == null || buffer == null) { return; } g.drawImage(buffer, 0, 0, buffer.getWidth() * scalingFactor, buffer.getHeight() * scalingFactor, null); g.drawImage(overlay, 0, 0, overlay.getWidth() * scalingFactor, overlay.getHeight() * scalingFactor, null); } public void repaintAll() { + if (data == null) { + return; + } Dimension size = recalculatePreferredSize(); buffer = new BufferedImage(size.width / scalingFactor, size.height / scalingFactor, BufferedImage.TYPE_INT_RGB); overlay = new BufferedImage(buffer.getWidth(), buffer.getHeight(), BufferedImage.TYPE_INT_ARGB); int rowPos = 0, colPos = 0; for (int i = 0; i < data.length; i++) { int tileRow = (i % 64) / 8; int tileCol = i % 8; if (i != 0 && tileRow == 0 && tileCol == 0) { colPos += 8; if (colPos > 15 * 8) { colPos = 0; rowPos += 8; } } buffer.setRGB(colPos + tileCol, rowPos + tileRow, palette.getColor(data[i]).getRGB()); } repaint(); } private Dimension recalculatePreferredSize() { Dimension size = new Dimension(8 * 16 * scalingFactor, (data.length/(8 * 16) + 7) / 8 * 8 * scalingFactor); setPreferredSize(size); JViewport viewport = (JViewport) getParent(); viewport.doLayout(); return size; } public void incrementScalingFactor() { scalingFactor *= 2; boolean rescale = true; Point initialPoint = ((JViewport) getParent()).getViewPosition(); if (scalingFactor > 32) { rescale = false; scalingFactor = 32; } repaintAll(); if (rescale) { ((JViewport) getParent()).setViewPosition(new Point(initialPoint.x, initialPoint.y * 2)); } } public void decrementScalingFactor() { scalingFactor /= 2; boolean rescale = true; Point initialPoint = ((JViewport) getParent()).getViewPosition(); if (scalingFactor < 1) { rescale = false; scalingFactor = 1; } repaintAll(); if (rescale) { ((JViewport) getParent()).setViewPosition(new Point(initialPoint.x, initialPoint.y / 2)); } } private Point getSelectedPixel(MouseEvent me) { return new Point(me.getX()/scalingFactor, me.getY()/scalingFactor); } @Override public void mouseClicked(MouseEvent me) { currentTool.mouseClicked(getSelectedPixel(me)); } @Override public void mousePressed(MouseEvent me) { currentTool.mouseDown(getSelectedPixel(me)); currentTool.mouseDragged(getSelectedPixel(me)); } @Override public void mouseReleased(MouseEvent me) { currentTool.mouseUp(getSelectedPixel(me)); } @Override public void mouseEntered(MouseEvent me) {} @Override public void mouseExited(MouseEvent me) {} @Override public void mouseDragged(MouseEvent me) { currentTool.mouseDragged(getSelectedPixel(me)); } @Override public void mouseMoved(MouseEvent me) {} @Override public Dimension getPreferredScrollableViewportSize() { return getPreferredSize(); } @Override public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) { return 16; } @Override public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) { return orientation == SwingConstants.VERTICAL ? visibleRect.height : visibleRect.width; } @Override public boolean getScrollableTracksViewportWidth() { return false; } @Override public boolean getScrollableTracksViewportHeight() { return false; } public static enum Tool { MARQUEE, PENCIL { @Override public void mouseDragged(Point location) { SNESTile window = SNESTile.getInstance(); window.getDrawingPanel().setPixelColor(location, window.getPalettePanel().getCurrentColor()); } }, FILL_RECT { private Point rectStart; @Override public void mouseDown(Point location) { rectStart = location; } @Override public void mouseDragged(Point location) { DrawingPanel panel = SNESTile.getInstance().getDrawingPanel(); PalettePanel palette = SNESTile.getInstance().getPalettePanel(); panel.clearOverlay(); Graphics2D g = panel.getOverlay(); Rectangle rect = getDrawableRect(rectStart, location); g.setColor(palette.getColor(palette.getCurrentColor())); g.fillRect(rect.x, rect.y, rect.width + 1, rect.height + 1); panel.repaint(); } @Override public void mouseUp(Point location) { DrawingPanel panel = SNESTile.getInstance().getDrawingPanel(); PalettePanel palette = SNESTile.getInstance().getPalettePanel(); panel.clearOverlay(); Rectangle rect = getDrawableRect(rectStart, location); for (int i = rect.x; i < rect.x + rect.width + 1; i++) { for (int j = rect.y; j < rect.y + rect.height + 1; j++) { panel.setPixelColor(new Point(i, j), palette.getCurrentColor()); } } panel.repaint(); } }, STROKE_RECT { private Point rectStart; @Override public void mouseDown(Point location) { rectStart = location; } @Override public void mouseDragged(Point location) { DrawingPanel panel = SNESTile.getInstance().getDrawingPanel(); PalettePanel palette = SNESTile.getInstance().getPalettePanel(); panel.clearOverlay(); Graphics2D g = panel.getOverlay(); Rectangle rect = getDrawableRect(rectStart, location); g.setColor(palette.getColor(palette.getCurrentColor())); g.drawRect(rect.x, rect.y, rect.width, rect.height); panel.repaint(); } @Override public void mouseUp(Point location) { DrawingPanel panel = SNESTile.getInstance().getDrawingPanel(); PalettePanel palette = SNESTile.getInstance().getPalettePanel(); panel.clearOverlay(); Rectangle rect = getDrawableRect(rectStart, location); for (int i = rect.x; i < rect.x + rect.width; i++) { panel.setPixelColor(new Point(i, rect.y), palette.getCurrentColor()); panel.setPixelColor(new Point(i, rect.y + rect.height), palette.getCurrentColor()); } for (int i = rect.y; i < rect.y + rect.height; i++) { panel.setPixelColor(new Point(rect.x, i), palette.getCurrentColor()); panel.setPixelColor(new Point(rect.x + rect.width, i), palette.getCurrentColor()); } panel.setPixelColor(new Point(rect.x + rect.width, rect.y + rect.height), palette.getCurrentColor()); panel.repaint(); } }, FILL_ELLIPSE, STROKE_ELLIPSE; private static Rectangle getDrawableRect(Point a, Point b) { return new Rectangle(Math.min(a.x, b.x), Math.min(a.y, b.y), Math.abs(a.x - b.x), Math.abs(a.y - b.y)); } public void mouseClicked(Point location) {} public void mouseDown(Point location) {} public void mouseUp(Point location) {} public void mouseDragged(Point location) {} } }
true
true
public void repaintAll() { Dimension size = recalculatePreferredSize(); buffer = new BufferedImage(size.width / scalingFactor, size.height / scalingFactor, BufferedImage.TYPE_INT_RGB); overlay = new BufferedImage(buffer.getWidth(), buffer.getHeight(), BufferedImage.TYPE_INT_ARGB); int rowPos = 0, colPos = 0; for (int i = 0; i < data.length; i++) { int tileRow = (i % 64) / 8; int tileCol = i % 8; if (i != 0 && tileRow == 0 && tileCol == 0) { colPos += 8; if (colPos > 15 * 8) { colPos = 0; rowPos += 8; } } buffer.setRGB(colPos + tileCol, rowPos + tileRow, palette.getColor(data[i]).getRGB()); } repaint(); }
public void repaintAll() { if (data == null) { return; } Dimension size = recalculatePreferredSize(); buffer = new BufferedImage(size.width / scalingFactor, size.height / scalingFactor, BufferedImage.TYPE_INT_RGB); overlay = new BufferedImage(buffer.getWidth(), buffer.getHeight(), BufferedImage.TYPE_INT_ARGB); int rowPos = 0, colPos = 0; for (int i = 0; i < data.length; i++) { int tileRow = (i % 64) / 8; int tileCol = i % 8; if (i != 0 && tileRow == 0 && tileCol == 0) { colPos += 8; if (colPos > 15 * 8) { colPos = 0; rowPos += 8; } } buffer.setRGB(colPos + tileCol, rowPos + tileRow, palette.getColor(data[i]).getRGB()); } repaint(); }
diff --git a/com/benzrf/sblock/sburbchat/channel/channels/RPChannel.java b/com/benzrf/sblock/sburbchat/channel/channels/RPChannel.java index 80db0dc..b10fbbf 100644 --- a/com/benzrf/sblock/sburbchat/channel/channels/RPChannel.java +++ b/com/benzrf/sblock/sburbchat/channel/channels/RPChannel.java @@ -1,420 +1,420 @@ package com.benzrf.sblock.sburbchat.channel.channels; import java.util.HashMap; import java.util.Map; import org.bukkit.ChatColor; import com.benzrf.sblock.sburbchat.User; import com.benzrf.sblock.sburbchat.channel.AccessLevel; import com.benzrf.sblock.sburbchat.channel.ChannelType; import com.benzrf.sblock.sburbchat.commandparser.PrivilegeLevel; public class RPChannel extends NickChannel { public RPChannel(){} public RPChannel(String name, AccessLevel listeningAccess, AccessLevel sendingAccess, String creator) { super(name, listeningAccess, sendingAccess, creator); } @Override public void setChat(String m, User sender) { if (this.muteList.contains(sender.getName())) { sender.sendMessage(ChatColor.RED + "You are muted in channel " + ChatColor.GOLD + this.name + ChatColor.RED + "!"); return; } if (!this.nickMap.containsKey(sender.getName())) { sender.sendMessage(ChatColor.RED + "You must have a canon nick to chat in channel " + ChatColor.GOLD + this.name + ChatColor.RED + "!"); return; } switch (this.sendingAccess) { case PUBLIC: break; case PRIVATE: if (this.modList.contains(sender.getName())) { break; } else { return; } case REQUEST: if (approvedList.contains(sender.getName())) { break; } else { return; } } - msg = sender.hasPermission("sburbchat.chatcolor") ? msg.replaceAll("&([0-9a-fk-or])", "") : msg; - this.sendToAll(this.getChatPrefix(sender, msg) + ((msg.startsWith("\\#") || msg.startsWith("#")) ? canonNicks.get(this.nickMap.get(sender.getName())).applyColor(msg.substring(1)) : canonNicks.get(this.nickMap.get(sender.getName())).apply(msg))); + m = sender.hasPermission("sburbchat.chatcolor") ? m.replaceAll("&([0-9a-fk-or])", "") : m; + this.sendToAll(this.getChatPrefix(sender, m) + ((m.startsWith("\\#") || m.startsWith("#")) ? canonNicks.get(this.nickMap.get(sender.getName())).applyColor(m.substring(1)) : canonNicks.get(this.nickMap.get(sender.getName())).apply(m))); } @Override public void setNick(String nick, User sender) { for (String s : canonNicks.keySet()) { if (nick.equalsIgnoreCase(ChatColor.stripColor(s.toLowerCase()))) { nick = s; if (!this.nickMap.containsValue(nick)) { this.nickMap.put(sender.getName(), nick); this.sendToAll(ChatColor.YELLOW + sender.getName() + " has set their nick to " + ChatColor.DARK_BLUE + nick + ChatColor.YELLOW + "!"); } else { sender.sendMessage(ChatColor.RED + "The nick " + ChatColor.DARK_BLUE + nick + ChatColor.RED + " is already taken in channel " + ChatColor.GOLD + this.name + "!"); } return; } } sender.sendMessage(ChatColor.RED + "The nick " + ChatColor.DARK_BLUE + nick + ChatColor.RED + " is not canon!"); } @Override public ChannelType getType() { return ChannelType.RP; } @Override public void setColorAccess(PrivilegeLevel level, User user) { user.sendMessageFromChannel(ChatColor.RED + "Roleplay channels never allow color changes!", this); } static Map<String, Quirker> canonNicks = new HashMap<String, Quirker>(); static { canonNicks.put(ChatColor.BLUE + "John", new Quirker(ChatColor.BLUE.toString(), "", null)); canonNicks.put(ChatColor.LIGHT_PURPLE + "Rose", new Quirker(ChatColor.LIGHT_PURPLE.toString(), "", null)); canonNicks.put(ChatColor.DARK_RED + "Dave", new Quirker(ChatColor.DARK_RED.toString(), "", null)); canonNicks.put(ChatColor.GREEN + "Jade", new Quirker(ChatColor.GREEN.toString(), "", null)); canonNicks.put(ChatColor.DARK_GRAY + "Karkat", new Quirker(ChatColor.DARK_GRAY.toString(), "", new Quirkf(){String apply(String msg){return Quirkf.karkat(msg);}}));//"a", "A", "b", "B", "c", "C", "d", "D", "e", "E", "f", "F", "g", "G", "h", "H", "i", "I", "j", "J", "k", "K", "l", "L", "m", "M", "n", "N", "o", "O", "p", "P", "q", "Q", "r", "R", "s", "S", "t", "T", "u", "U", "v", "V", "w", "W", "x", "X", "y", "Y", "z", "Z")); canonNicks.put(ChatColor.DARK_PURPLE + "Gamzee", new Quirker(ChatColor.DARK_PURPLE.toString(), "", new Quirkf(){String apply(String msg){return Quirkf.gamzee(msg);}})); canonNicks.put(ChatColor.DARK_AQUA + "Terezi", new Quirker(ChatColor.DARK_AQUA.toString(), "", new Quirkf(){String apply(String msg){return Quirkf.terezi(msg);}})); canonNicks.put(ChatColor.YELLOW + "Sollux", new Quirker(ChatColor.YELLOW.toString(), "", new Quirkf(){String apply(String msg){return Quirkf.sollux(msg);}})); canonNicks.put(ChatColor.GOLD + "Tavros", new Quirker(ChatColor.GOLD.toString(), "", new Quirkf(){String apply(String msg){return Quirkf.tavros(msg);}})); canonNicks.put(ChatColor.DARK_RED + "Aradia", new Quirker(ChatColor.DARK_RED.toString(), "", new Quirkf(){String apply(String msg){return Quirkf.aradia(msg);}})); canonNicks.put(ChatColor.DARK_GREEN + "Nepeta", new Quirker(ChatColor.DARK_GREEN.toString() + ":33 < ", "", new Quirkf(){String apply(String msg){return Quirkf.nepeta(msg);}})); canonNicks.put(ChatColor.BLUE + "Vriska", new Quirker(ChatColor.BLUE.toString(), "", new Quirkf(){String apply(String msg){return Quirkf.vriska(msg);}})); canonNicks.put(ChatColor.DARK_BLUE + "Equius", new Quirker(ChatColor.DARK_BLUE.toString() + "D --> ", "", new Quirkf(){String apply(String msg){return Quirkf.equius(msg);}})); canonNicks.put(ChatColor.DARK_GREEN + "Kanaya", new Quirker(ChatColor.DARK_GREEN.toString(), "", new Quirkf(){String apply(String msg){return Quirkf.kanaya(msg);}})); canonNicks.put(ChatColor.DARK_PURPLE + "Eridan", new Quirker(ChatColor.DARK_PURPLE.toString(), "", new Quirkf(){String apply(String msg){return Quirkf.eridan(msg);}})); canonNicks.put(ChatColor.DARK_PURPLE + "Feferi", new Quirker(ChatColor.DARK_PURPLE.toString(), "", new Quirkf(){String apply(String msg){return Quirkf.feferi(msg);}})); canonNicks.put(ChatColor.BLUE + "Jane", new Quirker(ChatColor.BLUE.toString(), "", null)); canonNicks.put(ChatColor.LIGHT_PURPLE + "Roxy", new Quirker(ChatColor.LIGHT_PURPLE.toString(), "", null)); canonNicks.put(ChatColor.GOLD + "Dirk", new Quirker(ChatColor.GOLD.toString(), "", null)); canonNicks.put(ChatColor.DARK_GREEN + "Jake", new Quirker(ChatColor.DARK_GREEN.toString(), "", null)); canonNicks.put(ChatColor.RED + "Kankri", new Quirker(ChatColor.RED.toString(), "", new Quirkf(){String apply(String msg){return Quirkf.kankri(msg);}}));//"a", "A", "b", "B", "c", "C", "d", "D", "e", "E", "f", "F", "g", "G", "h", "H", "i", "I", "j", "J", "k", "K", "l", "L", "m", "M", "n", "N", "o", "O", "p", "P", "q", "Q", "r", "R", "s", "S", "t", "T", "u", "U", "v", "V", "w", "W", "x", "X", "y", "Y", "z", "Z")); canonNicks.put(ChatColor.DARK_PURPLE + "Kurloz", new Quirker(ChatColor.DARK_PURPLE.toString(), "", new Quirkf(){String apply(String msg){return Quirkf.kurloz(msg);}})); canonNicks.put(ChatColor.DARK_AQUA + "Latula", new Quirker(ChatColor.DARK_AQUA.toString(), "", new Quirkf(){String apply(String msg){return Quirkf.latula(msg);}})); canonNicks.put(ChatColor.YELLOW + "Mituna", new Quirker(ChatColor.YELLOW.toString(), "", new Quirkf(){String apply(String msg){return Quirkf.mituna(msg);}})); canonNicks.put(ChatColor.GOLD + "Rufioh", new Quirker(ChatColor.GOLD.toString(), "", new Quirkf(){String apply(String msg){return Quirkf.rufioh(msg);}})); //canonNicks.put(ChatColor.DARK_RED + "Damara", new Quirker(ChatColor.DARK_RED.toString(), "", new Quirkf(){String apply(String msg){return Quirkf.damara(msg);}})); canonNicks.put(ChatColor.DARK_GREEN + "Meulin", new Quirker(ChatColor.DARK_GREEN.toString() + "(^._.^) ", "", new Quirkf(){String apply(String msg){return Quirkf.meulin(msg);}})); canonNicks.put(ChatColor.BLUE + "Arenea", new Quirker(ChatColor.BLUE.toString(), "", new Quirkf(){String apply(String msg){return Quirkf.vriska(msg);}})); //Same as Vriska? canonNicks.put(ChatColor.DARK_BLUE + "Horuss", new Quirker(ChatColor.DARK_BLUE.toString() + "8=D < ", "", new Quirkf(){String apply(String msg){return Quirkf.horuss(msg);}})); canonNicks.put(ChatColor.DARK_GREEN + "Porrim", new Quirker(ChatColor.DARK_GREEN.toString(), "", new Quirkf(){String apply(String msg){return Quirkf.porrim(msg);}})); canonNicks.put(ChatColor.DARK_PURPLE + "Cronus", new Quirker(ChatColor.DARK_PURPLE.toString(), "", new Quirkf(){String apply(String msg){return Quirkf.cronus(msg);}})); canonNicks.put(ChatColor.DARK_PURPLE + "Meenah", new Quirker(ChatColor.DARK_PURPLE.toString(), "", new Quirkf(){String apply(String msg){return Quirkf.meenah(msg);}})); canonNicks.put(ChatColor.GRAY + "Calliope", new Quirker(ChatColor.GRAY.toString(), "", new Quirkf(){String apply(String msg){return Quirkf.calliope(msg);}})); canonNicks.put(ChatColor.DARK_GRAY + "Caliborn", new Quirker(ChatColor.DARK_GRAY.toString(), "", new Quirkf(){String apply(String msg){return Quirkf.caliborn(msg);}})); } private static final long serialVersionUID = -4463076541248313240L; } class Quirker { public Quirker(String prefix, String suffix, Quirkf quirk) { this.prefix = prefix; this.color = prefix.substring(0, 2); this.suffix = suffix; this.quirk = quirk; } public String apply(String msg) { return prefix + (quirk == null ? msg : quirk.apply(msg)) + suffix; } public String applyColor(String msg) { return color + msg; } private Quirkf quirk; private String prefix; private String suffix; private String color; } abstract class Quirkf { abstract String apply(String msg); /** * Applies Caliborn's quirk to a string. * @param msg * @return */ static String caliborn(String msg) { return msg.toUpperCase().replace('U', 'u').replaceAll("[:=][O\\)\\(DPS\\/]", "tumut"); } /** * Applies Calliope's quirk to a string. * @param msg * @return */ static String calliope(String msg) { return msg.toLowerCase().replace('u', 'U'); //TODO Force British spellings } /** * Applies Meenah's quirk to a string. * @param msg * @return */ static String meenah(String msg) { return msg.replace("H", ")(").replace("E","-E").replace("fucking","glubbing").replace("fuck", "glub"); //TODO More fish puns! } /** * Applies Cronus's quirk to a string. * @param msg * @return */ static String cronus(String msg) { return msg.replace("v", "vw").replace("V","VW").replace("w", "wv").replace("W", "WV").replace("B", "8"); } /** * Applies Porrim's quirk to a string. * @param msg * @return */ static String porrim(String msg) { return msg.replace("o", "o+").replace("O","O+").replaceAll("[pP][lL][uU][sS]", "+"); } /** * Applies Horuss' quirk to a string. * @param msg * @return */ static String horuss(String msg) { return msg.replace('x', '%').replace("loo", "100").replace("lue", "100").replace("ool","001").replaceAll("[sS][tT][rR][oO][nN][gG]", "STRONG") .replace("nay", "neigh").replace("fuck", "f*ck").replace("shit", "sh*t").replace("cock", "c*ck").replace("bitch", "b*tch") .replace("cunt", "c*nt").replace("tits", "t*ts"); } /** * Applies Meulin's quirk to a string. * @param msg * @return */ static String meulin(String msg) { return msg.toUpperCase().replace("EE", "33").replace("FOR", "FUR").replace("PER", "PURR"); } /** * Applies Damara's quirk to a string. * Does not yet work due to character encoding issues. * @param msg * @return */ static String damara(String msg) { return null; // return fakeJapanese[new Random().nextInt(fakeJapanese.length)]; } /** * Applies Rufioh's quirk to a string. * @param msg * @return */ static String rufioh(String msg) { return msg.replace("i", "1").replace(",", "... "); } /** * Applies Mituna's quirk to a string. * @param msg * @return */ static String mituna(String msg) { return msg.toUpperCase().replace("E", "3").replace("A", "4").replace("S", "5") .replace("O", "0").replace("T", "7").replace("I","1").replace("B", "8"); } /** * Applies Latula's quirk to a string. * @param msg * @return */ static String latula(String msg) { return msg.toLowerCase().replace("a", "4").replace("i", "1").replace("e", "3"); } /** * Applies Kurloz's quirk to a string. * NOTE: Kurloz speaks in mimes/images, which isn't really possible in MC, so I based his quirk * on his purple text when using his telepathic ability. * @param msg * @return */ static String kurloz(String msg) { return msg.toUpperCase().replaceAll("\\p{Punct}", ""); } /** * Applies Kankri's quirk to a string. * @param msg * @return */ static String kankri(String msg) { return msg.replaceAll("[Bb]", "6").replaceAll("[Oo]", "9"); } static String karkat(String msg) { return msg.toUpperCase(); } static String gamzee(String msg) { boolean odd = true; char[] c = msg.toCharArray(); for (int i = 0; i < c.length; i++) { if (odd) { if (c[i] == 'o') { try { if (!(c[i - 1] == ':' && (c[i + 1] == ')' || c[i + 1] == '('))) { c[i] = Character.toUpperCase(c[i]); } } catch (ArrayIndexOutOfBoundsException e) { } } else { c[i] = Character.toUpperCase(c[i]); } } else { c[i] = Character.toLowerCase(c[i]); } odd = !odd; } return new String(c); } static String terezi(String msg) { return msg.toUpperCase().replace('A', '4').replace('I', '1').replace('E', '3').replace("'", ""); } static String sollux(String msg) { return msg.replace("i", "ii").replaceAll("(?<=(^| ))(too|to)(?=($| ))", "two").replace('s', '2'); } static String tavros(String msg) { char[] c = msg.toCharArray(); for (int i = 0; i < c.length; i++) { if (c[i] == '.') { c[i] = ','; } else { c[i] = (Character.isUpperCase(c[i]) ? Character.toLowerCase(c[i]) : Character.toUpperCase(c[i])); } } c[0] = Character.toLowerCase(c[0]); return new String(c); } static String aradia(String msg) { return msg.toLowerCase().replace('o', '0').replace("'", ""); } static String nepeta(String msg) { return msg.replaceAll("(e|E)(e|E)", "33"); } static String vriska(String msg) { return msg.replace('b', '8').replace('B', '8').replace("ate", "8").replaceAll("(.)\\\\8", "$1$1$1$1$1$1$1$1"); } static String equius(String msg) { return msg.replace('x', '%').replace("loo", "100").replace("lue", "100").replaceAll("(s|S)(t|T)(r|R)(o|O)(n|N)(g|G)", "STRONG").replace("nay", "neigh"); } static String kanaya(String msg) { String[] caps = msg.replace("'", "").split(" "); StringBuilder sb = new StringBuilder(); for (String s : caps) { sb.append(Character.toUpperCase(s.charAt(0))).append(s.toLowerCase().substring(1)).append(" "); } return sb.toString(); } static String eridan(String msg) { return msg.toLowerCase().replaceAll("(?<!w)w(?!w)", "ww").replaceAll("(?<!v)v(?!v)", "vv").replaceAll("(?<=[^ ])ing(?=( |$))", "in"); } static String feferi(String msg) { return msg.replace("h", ")(").replace("H", ")(").replace("E", "-E"); } }
true
true
public void setChat(String m, User sender) { if (this.muteList.contains(sender.getName())) { sender.sendMessage(ChatColor.RED + "You are muted in channel " + ChatColor.GOLD + this.name + ChatColor.RED + "!"); return; } if (!this.nickMap.containsKey(sender.getName())) { sender.sendMessage(ChatColor.RED + "You must have a canon nick to chat in channel " + ChatColor.GOLD + this.name + ChatColor.RED + "!"); return; } switch (this.sendingAccess) { case PUBLIC: break; case PRIVATE: if (this.modList.contains(sender.getName())) { break; } else { return; } case REQUEST: if (approvedList.contains(sender.getName())) { break; } else { return; } } msg = sender.hasPermission("sburbchat.chatcolor") ? msg.replaceAll("&([0-9a-fk-or])", "") : msg; this.sendToAll(this.getChatPrefix(sender, msg) + ((msg.startsWith("\\#") || msg.startsWith("#")) ? canonNicks.get(this.nickMap.get(sender.getName())).applyColor(msg.substring(1)) : canonNicks.get(this.nickMap.get(sender.getName())).apply(msg))); }
public void setChat(String m, User sender) { if (this.muteList.contains(sender.getName())) { sender.sendMessage(ChatColor.RED + "You are muted in channel " + ChatColor.GOLD + this.name + ChatColor.RED + "!"); return; } if (!this.nickMap.containsKey(sender.getName())) { sender.sendMessage(ChatColor.RED + "You must have a canon nick to chat in channel " + ChatColor.GOLD + this.name + ChatColor.RED + "!"); return; } switch (this.sendingAccess) { case PUBLIC: break; case PRIVATE: if (this.modList.contains(sender.getName())) { break; } else { return; } case REQUEST: if (approvedList.contains(sender.getName())) { break; } else { return; } } m = sender.hasPermission("sburbchat.chatcolor") ? m.replaceAll("&([0-9a-fk-or])", "") : m; this.sendToAll(this.getChatPrefix(sender, m) + ((m.startsWith("\\#") || m.startsWith("#")) ? canonNicks.get(this.nickMap.get(sender.getName())).applyColor(m.substring(1)) : canonNicks.get(this.nickMap.get(sender.getName())).apply(m))); }
diff --git a/portfolio/elevatorcontrol/DoorControl.java b/portfolio/elevatorcontrol/DoorControl.java index bfab65e..4386e5c 100644 --- a/portfolio/elevatorcontrol/DoorControl.java +++ b/portfolio/elevatorcontrol/DoorControl.java @@ -1,390 +1,390 @@ /* * 18-649 Fall 2013 * Group 22 * David Chow davidcho * Brody Anderson bcanders * Yang Liu yangliu2 * Jeffrey Lau jalau * DoorControl.java * @author: Brody Anderson (bcanders) */ package simulator.elevatorcontrol; import java.util.ArrayList; import jSimPack.SimTime; import jSimPack.SimTime.SimTimeUnit; import simulator.elevatormodules.*; import simulator.framework.Controller; import simulator.framework.Direction; import simulator.framework.DoorCommand; import simulator.framework.Elevator; import simulator.framework.Hallway; import simulator.framework.ReplicationComputer; import simulator.framework.Side; import simulator.payloads.CanMailbox; import simulator.payloads.CanMailbox.ReadableCanMailbox; import simulator.payloads.DoorMotorPayload; import simulator.payloads.DoorMotorPayload.WriteableDoorMotorPayload; import simulator.payloads.translators.BooleanCanPayloadTranslator; public class DoorControl extends Controller { //enumerate states private enum State { CAR_MOVING, OPENING_DOOR, WAIT_FOR_DWELL, CLOSING_DOOR, NUDGING_DOOR, } // Initialize state to CAR_MOVING private State state = State.CAR_MOVING; // State Variables: // long integer with number of msec desired for door // dwell during current cycle. private final SimTime Dwell = new SimTime("2s"); // a count-down timer for Door Dwell[b] (implemented in simulation by // scheduling a future task execution at time of expiration) private SimTime CountDown; // Which hallway and side is this DoorControl for? private Hallway h; private Side s; private int maxReversals = 2; private int reversalCount; private boolean open_flag = true; private Direction p_dir = Direction.STOP; private int p_floor = 1; private Hallway p_hall = Hallway.BOTH; //store the period for the controller private SimTime period; // initialize local variables private int currentFloor; private int lastValidFloor; // 0: front,left, 1: front,right, 2: back,left, 3: back,right ReadableCanMailbox networkDoorClosed; DoorClosedCanPayloadTranslator mDoorClosed; ReadableCanMailbox networkDoorOpen; DoorOpenedCanPayloadTranslator mDoorOpen; ReadableCanMailbox networkDoorReversal1; DoorReversalCanPayloadTranslator mDoorReversal1; ReadableCanMailbox networkDoorReversal2; DoorReversalCanPayloadTranslator mDoorReversal2; ReadableCanMailbox networkCarWeight; CarWeightCanPayloadTranslator mCarWeight; int length = 2*Elevator.numFloors; ReadableCanMailbox[] networkAtFloor = new ReadableCanMailbox[length]; AtFloorCanPayloadTranslator[] mAtFloor = new AtFloorCanPayloadTranslator[length]; ReadableCanMailbox networkDesiredFloor; DesiredFloorCanPayloadTranslator mDesiredFloor; ReadableCanMailbox[] networkCarCall; CarCallCanPayloadTranslator[] mCarCall; ReadableCanMailbox[] networkHallCall; HallCallCanPayloadTranslator[] mHallCall; // Outputs WriteableDoorMotorPayload DoorMotor; ReadableCanMailbox networkDriveSpeed; DriveSpeedCanPayloadTranslator mDriveSpeed; /** * The arguments listed in the .cf configuration file should match the order and * type given here. * * Make sure that the constructor matches * the method signatures in ControllerBuilder.makeAll(). */ public DoorControl(Hallway h, Side s, SimTime period, boolean verbose) { super("DoorControl" + ReplicationComputer.makeReplicationString(h,s), verbose); this.period = period; this.h = h; this.s = s; this.currentFloor = 1; this.lastValidFloor = 1; log("Created DoorControl with period = ", period); // make the mailboxes and translators for all network messages networkDoorClosed = CanMailbox.getReadableCanMailbox(MessageDictionary.DOOR_CLOSED_SENSOR_BASE_CAN_ID + ReplicationComputer.computeReplicationId(h, s)); mDoorClosed = new DoorClosedCanPayloadTranslator(networkDoorClosed, h,s); canInterface.registerTimeTriggered(networkDoorClosed); networkDoorOpen = CanMailbox.getReadableCanMailbox(MessageDictionary.DOOR_OPEN_SENSOR_BASE_CAN_ID + ReplicationComputer.computeReplicationId(h, s)); mDoorOpen = new DoorOpenedCanPayloadTranslator(networkDoorOpen, h, s); canInterface.registerTimeTriggered(networkDoorOpen); networkDoorReversal1 = CanMailbox.getReadableCanMailbox(MessageDictionary.DOOR_REVERSAL_SENSOR_BASE_CAN_ID + ReplicationComputer.computeReplicationId(h, Side.LEFT)); mDoorReversal1 = new DoorReversalCanPayloadTranslator(networkDoorReversal1, h, Side.LEFT); canInterface.registerTimeTriggered(networkDoorReversal1); networkDoorReversal2 = CanMailbox.getReadableCanMailbox(MessageDictionary.DOOR_REVERSAL_SENSOR_BASE_CAN_ID + ReplicationComputer.computeReplicationId(h, Side.RIGHT)); mDoorReversal2 = new DoorReversalCanPayloadTranslator(networkDoorReversal2, h, Side.RIGHT); canInterface.registerTimeTriggered(networkDoorReversal2); networkCarWeight = CanMailbox.getReadableCanMailbox(MessageDictionary.CAR_WEIGHT_CAN_ID); mCarWeight = new CarWeightCanPayloadTranslator(networkCarWeight); canInterface.registerTimeTriggered(networkCarWeight); networkDesiredFloor = CanMailbox.getReadableCanMailbox(MessageDictionary.DESIRED_FLOOR_CAN_ID); mDesiredFloor = new DesiredFloorCanPayloadTranslator(networkDesiredFloor); canInterface.registerTimeTriggered(networkDesiredFloor); for (int floor = 1; floor <= Elevator.numFloors; floor++) { for (Hallway hall : Hallway.replicationValues) { int index = ReplicationComputer.computeReplicationId(floor, hall); networkAtFloor[index] = CanMailbox.getReadableCanMailbox(MessageDictionary.AT_FLOOR_BASE_CAN_ID + ReplicationComputer.computeReplicationId(floor, hall)); mAtFloor[index] = new AtFloorCanPayloadTranslator(networkAtFloor[index], floor, hall); canInterface.registerTimeTriggered(networkAtFloor[index]); } } networkDriveSpeed = CanMailbox.getReadableCanMailbox(MessageDictionary.DRIVE_SPEED_CAN_ID); mDriveSpeed = new DriveSpeedCanPayloadTranslator(networkDriveSpeed); // leave this as is canInterface.registerTimeTriggered(networkDriveSpeed); networkCarCall = new CanMailbox.ReadableCanMailbox[Elevator.numFloors*2]; mCarCall = new CarCallCanPayloadTranslator[Elevator.numFloors*2]; for(int floors = 1; floors <= Elevator.numFloors; floors++) { for (Hallway H : Hallway.replicationValues) { int index = ReplicationComputer.computeReplicationId(floors,H); networkCarCall[index] = CanMailbox.getReadableCanMailbox( MessageDictionary.CAR_CALL_BASE_CAN_ID + ReplicationComputer.computeReplicationId(floors,H)); mCarCall[index] = new CarCallCanPayloadTranslator(networkCarCall[index], floors, H); canInterface.registerTimeTriggered(networkCarCall[index]); } } //HallCall networkHallCall = new CanMailbox.ReadableCanMailbox[Elevator.numFloors*4]; mHallCall = new HallCallCanPayloadTranslator[Elevator.numFloors*4]; for(int floors = 1; floors <= Elevator.numFloors; floors++) { for (Hallway h1 : Hallway.replicationValues) { for (Direction d : Direction.replicationValues) { int index = ReplicationComputer.computeReplicationId(floors,h1,d); networkHallCall[index] = CanMailbox.getReadableCanMailbox( MessageDictionary.HALL_CALL_BASE_CAN_ID + ReplicationComputer.computeReplicationId(floors,h1,d)); mHallCall[index] = new HallCallCanPayloadTranslator(networkHallCall[index],floors,h1,d); canInterface.registerTimeTriggered(networkHallCall[index]); } } } DoorMotor = DoorMotorPayload.getWriteablePayload(h,s); physicalInterface.sendTimeTriggered(DoorMotor, period); /* issuing the timer start method with no callback data means a NULL value * will be passed to the callback later. Use the callback data to distinguish * callbacks from multiple calls to timer.start() (e.g. if you have multiple * timers. */ timer.start(period); } /** * CurrentFloor is a simple helper function that returns an int * representing the floor at which mAtFloor[f,d] is true * @return - the floor at which mAtFloor[f,d] is true */ private int CurrentMAtFloor() { int f; int cFloor = -1; for (int floor = 1; floor <= Elevator.numFloors; floor++) { for (Hallway hall : Hallway.replicationValues) { f = ReplicationComputer.computeReplicationId(floor,hall); if (mAtFloor[f].getValue()){ if (cFloor != -1) { // This should never happen! // Errormessage } else { cFloor = floor; } } } } return cFloor; } @Override public void timerExpired(Object callbackData) { if (CurrentMAtFloor() != -1) { this.lastValidFloor = CurrentMAtFloor(); } this.currentFloor = this.lastValidFloor; State newState = state; switch (state) { case CAR_MOVING: // S1 // State 1 actions: DoorMotor.set(DoorCommand.STOP); this.CountDown = this.Dwell; this.reversalCount = 0; set_open_flag(); // State 1 transitions // #transition 5.T.1 //If desired hallway is BOTH, open all doors. if(mDesiredFloor.getHallway() == Hallway.BOTH){ if (mAtFloor[ReplicationComputer.computeReplicationId( mDesiredFloor.getFloor(),Hallway.FRONT)].getValue() == true && mDriveSpeed.getSpeed() == 0.0 && this.open_flag) { newState = State.OPENING_DOOR; // T1 } } else if (mAtFloor[ReplicationComputer.computeReplicationId( mDesiredFloor.getFloor(),mDesiredFloor.getHallway())].getValue() == true && mDriveSpeed.getSpeed() == 0.0 && mDesiredFloor.getHallway() == this.h && this.open_flag) { newState = State.OPENING_DOOR; // T1 } break; case OPENING_DOOR: // S2 // State 2 actions: DoorMotor.set(DoorCommand.OPEN); this.CountDown = this.Dwell; // State 2 transitions // #transition 5.T.2 if (this.mDoorOpen.getValue() == true) { newState = State.WAIT_FOR_DWELL; // T2 } break; case WAIT_FOR_DWELL: // S3 // State 3 actions: DoorMotor.set(DoorCommand.STOP); // decrement Countdown by the period this.CountDown = SimTime.subtract(this.CountDown, this.period); // Increase the countdown whenver the elevator is over weight if (mCarWeight.getValue() >= Elevator.MaxCarCapacity) { this.CountDown = this.Dwell; } // State 3 transitions if (this.CountDown.isPositive()) { // Countdown has reached 0 newState = state; } // #transition 5.T.3 else { // Countdown still greater than 0 - newState = State.CLOSING_DOOR; // T3 + if (this.reversalCount < this.maxReversals){ + newState = State.CLOSING_DOOR; // T3 + } + else { + newState = State.NUDGING_DOOR; + } } break; case CLOSING_DOOR: // S4 // State 4 actions: DoorMotor.set(DoorCommand.CLOSE); this.CountDown = this.Dwell; // State 4 transitions // #transition 5.T.5 and 5.T.6 if ((mCarWeight.getValue() >= Elevator.MaxCarCapacity) || (mCarCall[ReplicationComputer.computeReplicationId( this.currentFloor, this.h)].getValue() == true)) { newState = State.OPENING_DOOR; // T5 } else if (mDoorReversal1.getValue() || mDoorReversal2.getValue()) { // Check for door reversal - if (this.reversalCount < this.maxReversals){ - newState = State.OPENING_DOOR; // T5 - reversalCount++; - } - else { // Too many reversals have been done - newState = State.NUDGING_DOOR; // T6 - } + newState = State.OPENING_DOOR; // T5 + reversalCount++; } // #transition 5.T.4 else if (mDoorClosed.getValue()) { newState = State.CAR_MOVING; //T4 p_dir = mDesiredFloor.getDirection(); p_floor = mDesiredFloor.getFloor(); p_hall = mDesiredFloor.getHallway(); } else { newState = state; } break; case NUDGING_DOOR: // S5 DoorMotor.set(DoorCommand.NUDGE); this.CountDown = this.Dwell; // State 5 transitions // #transition 5.T.8 if ((mCarWeight.getValue() >= Elevator.MaxCarCapacity) || (mCarCall[ReplicationComputer.computeReplicationId( this.currentFloor, this.h)].getValue() == true)) { newState = State.OPENING_DOOR; // T8 } // #transition 5.T.7 else if (mDoorClosed.getValue()) { newState = State.CAR_MOVING; //T7 p_dir = mDesiredFloor.getDirection(); p_floor = mDesiredFloor.getFloor(); p_hall = mDesiredFloor.getHallway(); } else { newState = state; } break; default: throw new RuntimeException("State " + state + " was not recognized."); } //log the results of this iteration /* if (state == newState) { log("DoorControl remains in state: ",state); } else { log("Transition:",state,"->",newState); }*/ //update the state variable state = newState; //report the current state setState(STATE_KEY,newState.toString()); //schedule the next iteration of the controller //you must do this at the end of the timer callback in order to restart //the timer timer.start(period); } private void set_open_flag() { if (mCarCall[ReplicationComputer.computeReplicationId(this.currentFloor, this.h)].getValue()) { this.open_flag = true; } else if (mDesiredFloor.getDirection() != Direction.STOP && mHallCall[ReplicationComputer.computeReplicationId(this.currentFloor, this.h, mDesiredFloor.getDirection())].getValue()) { this.open_flag = true; } else if (p_dir == mDesiredFloor.getDirection() && p_floor == mDesiredFloor.getFloor() && p_hall == mDesiredFloor.getHallway()) { this.open_flag = false; } else { this.open_flag = true; } return; } }
false
true
public void timerExpired(Object callbackData) { if (CurrentMAtFloor() != -1) { this.lastValidFloor = CurrentMAtFloor(); } this.currentFloor = this.lastValidFloor; State newState = state; switch (state) { case CAR_MOVING: // S1 // State 1 actions: DoorMotor.set(DoorCommand.STOP); this.CountDown = this.Dwell; this.reversalCount = 0; set_open_flag(); // State 1 transitions // #transition 5.T.1 //If desired hallway is BOTH, open all doors. if(mDesiredFloor.getHallway() == Hallway.BOTH){ if (mAtFloor[ReplicationComputer.computeReplicationId( mDesiredFloor.getFloor(),Hallway.FRONT)].getValue() == true && mDriveSpeed.getSpeed() == 0.0 && this.open_flag) { newState = State.OPENING_DOOR; // T1 } } else if (mAtFloor[ReplicationComputer.computeReplicationId( mDesiredFloor.getFloor(),mDesiredFloor.getHallway())].getValue() == true && mDriveSpeed.getSpeed() == 0.0 && mDesiredFloor.getHallway() == this.h && this.open_flag) { newState = State.OPENING_DOOR; // T1 } break; case OPENING_DOOR: // S2 // State 2 actions: DoorMotor.set(DoorCommand.OPEN); this.CountDown = this.Dwell; // State 2 transitions // #transition 5.T.2 if (this.mDoorOpen.getValue() == true) { newState = State.WAIT_FOR_DWELL; // T2 } break; case WAIT_FOR_DWELL: // S3 // State 3 actions: DoorMotor.set(DoorCommand.STOP); // decrement Countdown by the period this.CountDown = SimTime.subtract(this.CountDown, this.period); // Increase the countdown whenver the elevator is over weight if (mCarWeight.getValue() >= Elevator.MaxCarCapacity) { this.CountDown = this.Dwell; } // State 3 transitions if (this.CountDown.isPositive()) { // Countdown has reached 0 newState = state; } // #transition 5.T.3 else { // Countdown still greater than 0 newState = State.CLOSING_DOOR; // T3 } break; case CLOSING_DOOR: // S4 // State 4 actions: DoorMotor.set(DoorCommand.CLOSE); this.CountDown = this.Dwell; // State 4 transitions // #transition 5.T.5 and 5.T.6 if ((mCarWeight.getValue() >= Elevator.MaxCarCapacity) || (mCarCall[ReplicationComputer.computeReplicationId( this.currentFloor, this.h)].getValue() == true)) { newState = State.OPENING_DOOR; // T5 } else if (mDoorReversal1.getValue() || mDoorReversal2.getValue()) { // Check for door reversal if (this.reversalCount < this.maxReversals){ newState = State.OPENING_DOOR; // T5 reversalCount++; } else { // Too many reversals have been done newState = State.NUDGING_DOOR; // T6 } } // #transition 5.T.4 else if (mDoorClosed.getValue()) { newState = State.CAR_MOVING; //T4 p_dir = mDesiredFloor.getDirection(); p_floor = mDesiredFloor.getFloor(); p_hall = mDesiredFloor.getHallway(); } else { newState = state; } break; case NUDGING_DOOR: // S5 DoorMotor.set(DoorCommand.NUDGE); this.CountDown = this.Dwell; // State 5 transitions // #transition 5.T.8 if ((mCarWeight.getValue() >= Elevator.MaxCarCapacity) || (mCarCall[ReplicationComputer.computeReplicationId( this.currentFloor, this.h)].getValue() == true)) { newState = State.OPENING_DOOR; // T8 } // #transition 5.T.7 else if (mDoorClosed.getValue()) { newState = State.CAR_MOVING; //T7 p_dir = mDesiredFloor.getDirection(); p_floor = mDesiredFloor.getFloor(); p_hall = mDesiredFloor.getHallway(); } else { newState = state; } break; default: throw new RuntimeException("State " + state + " was not recognized."); } //log the results of this iteration /* if (state == newState) { log("DoorControl remains in state: ",state); } else {
public void timerExpired(Object callbackData) { if (CurrentMAtFloor() != -1) { this.lastValidFloor = CurrentMAtFloor(); } this.currentFloor = this.lastValidFloor; State newState = state; switch (state) { case CAR_MOVING: // S1 // State 1 actions: DoorMotor.set(DoorCommand.STOP); this.CountDown = this.Dwell; this.reversalCount = 0; set_open_flag(); // State 1 transitions // #transition 5.T.1 //If desired hallway is BOTH, open all doors. if(mDesiredFloor.getHallway() == Hallway.BOTH){ if (mAtFloor[ReplicationComputer.computeReplicationId( mDesiredFloor.getFloor(),Hallway.FRONT)].getValue() == true && mDriveSpeed.getSpeed() == 0.0 && this.open_flag) { newState = State.OPENING_DOOR; // T1 } } else if (mAtFloor[ReplicationComputer.computeReplicationId( mDesiredFloor.getFloor(),mDesiredFloor.getHallway())].getValue() == true && mDriveSpeed.getSpeed() == 0.0 && mDesiredFloor.getHallway() == this.h && this.open_flag) { newState = State.OPENING_DOOR; // T1 } break; case OPENING_DOOR: // S2 // State 2 actions: DoorMotor.set(DoorCommand.OPEN); this.CountDown = this.Dwell; // State 2 transitions // #transition 5.T.2 if (this.mDoorOpen.getValue() == true) { newState = State.WAIT_FOR_DWELL; // T2 } break; case WAIT_FOR_DWELL: // S3 // State 3 actions: DoorMotor.set(DoorCommand.STOP); // decrement Countdown by the period this.CountDown = SimTime.subtract(this.CountDown, this.period); // Increase the countdown whenver the elevator is over weight if (mCarWeight.getValue() >= Elevator.MaxCarCapacity) { this.CountDown = this.Dwell; } // State 3 transitions if (this.CountDown.isPositive()) { // Countdown has reached 0 newState = state; } // #transition 5.T.3 else { // Countdown still greater than 0 if (this.reversalCount < this.maxReversals){ newState = State.CLOSING_DOOR; // T3 } else { newState = State.NUDGING_DOOR; } } break; case CLOSING_DOOR: // S4 // State 4 actions: DoorMotor.set(DoorCommand.CLOSE); this.CountDown = this.Dwell; // State 4 transitions // #transition 5.T.5 and 5.T.6 if ((mCarWeight.getValue() >= Elevator.MaxCarCapacity) || (mCarCall[ReplicationComputer.computeReplicationId( this.currentFloor, this.h)].getValue() == true)) { newState = State.OPENING_DOOR; // T5 } else if (mDoorReversal1.getValue() || mDoorReversal2.getValue()) { // Check for door reversal newState = State.OPENING_DOOR; // T5 reversalCount++; } // #transition 5.T.4 else if (mDoorClosed.getValue()) { newState = State.CAR_MOVING; //T4 p_dir = mDesiredFloor.getDirection(); p_floor = mDesiredFloor.getFloor(); p_hall = mDesiredFloor.getHallway(); } else { newState = state; } break; case NUDGING_DOOR: // S5 DoorMotor.set(DoorCommand.NUDGE); this.CountDown = this.Dwell; // State 5 transitions // #transition 5.T.8 if ((mCarWeight.getValue() >= Elevator.MaxCarCapacity) || (mCarCall[ReplicationComputer.computeReplicationId( this.currentFloor, this.h)].getValue() == true)) { newState = State.OPENING_DOOR; // T8 } // #transition 5.T.7 else if (mDoorClosed.getValue()) { newState = State.CAR_MOVING; //T7 p_dir = mDesiredFloor.getDirection(); p_floor = mDesiredFloor.getFloor(); p_hall = mDesiredFloor.getHallway(); } else { newState = state; } break; default: throw new RuntimeException("State " + state + " was not recognized."); } //log the results of this iteration /* if (state == newState) { log("DoorControl remains in state: ",state); } else {
diff --git a/src/org/racenet/racesow/Player.java b/src/org/racenet/racesow/Player.java index 7a34542..fe90fe4 100755 --- a/src/org/racenet/racesow/Player.java +++ b/src/org/racenet/racesow/Player.java @@ -1,1022 +1,1023 @@ package org.racenet.racesow; import java.util.List; import java.util.Random; import org.racenet.framework.AndroidAudio; import org.racenet.framework.AndroidSound; import org.racenet.framework.AnimatedBlock; import org.racenet.framework.Camera2; import org.racenet.framework.CameraText; import org.racenet.framework.FifoPool; import org.racenet.framework.FifoPool.PoolObjectFactory; import org.racenet.framework.GLGame; import org.racenet.framework.GameObject; import org.racenet.framework.Polygon; import org.racenet.framework.TexturedBlock; import org.racenet.framework.TexturedShape; import org.racenet.framework.Vector2; import org.racenet.racesow.GameScreen.GameState; import org.racenet.racesow.threads.InternalScoresThread; import android.content.Context; import android.content.SharedPreferences; import android.os.Handler; import android.os.Message; import android.util.Log; /** * Class which represents the player in the game. * Executes actions like shoot and jump and moves * the player througt the world. * * @author al * */ class Player extends AnimatedBlock { public final Vector2 velocity = new Vector2(); public final Vector2 accel = new Vector2(); // animations public static final short ANIM_RUN = 0; public static final short ANIM_JUMP = 1; public static final short ANIM_WALLJUMP = 2; public static final short ANIM_BURN = 3; public static final short ANIM_INVISIBLE = 4; public static final short ANIM_ROCKET_RUN = 5; public static final short ANIM_ROCKET_JUMP = 6; public static final short ANIM_ROCKET_WALLJUMP = 7; public static final short ANIM_PLASMA_RUN = 8; public static final short ANIM_PLASMA_JUMP = 9; public static final short ANIM_PLASMA_WALLJUMP = 10; public static final short ANIM_DROWN = 11; // sounds public static final short SOUND_JUMP1 = 0; public static final short SOUND_JUMP2 = 1; public static final short SOUND_WJ1 = 2; public static final short SOUND_WJ2 = 3; public static final short SOUND_DIE = 4; public static final short SOUND_PICKUP = 5; public static final short SOUND_ROCKET = 6; public static final short SOUND_PLASMA = 7; private AndroidSound sounds[] = new AndroidSound[8]; // firerates private static final float FIRERATE_ROCKET = 1.75f; private static final float FIRERATE_PLASMA = 0.04f; private float lastShot = 0; private boolean onFloor = false; private float lastWallJumped = 0; private float distanceOnJump = -1; private boolean distanceRemembered = false; public float virtualSpeed = 0; private float startSpeed = 450; private boolean enableAnimation = false; private boolean isDead = false; private float animDuration = 0; private TexturedBlock attachedItem; private Camera2 camera; private Random rGen; private float volume = 0.1f; private String model = "male"; private Map map; private FifoPool<TexturedBlock> plasmaPool; private FifoPool<TexturedBlock> rocketPool; private boolean soundEnabled; private GameScreen gameScreen; CameraText restartMessage; CameraText timeMessage; CameraText finishMessage; CameraText recordMessage; GameObject tutorialActive; CameraText tutorialMessage1; CameraText tutorialMessage2; CameraText tutorialMessage3; private int frames = 0; /** * Constructor. * * @param GLGame game * @param Map map * @param Camera2 camera * @param float x * @param float y * @param boolean soundEnabled */ public Player(final GLGame game, Map map, Camera2 camera, float x, float y, boolean soundEnabled) { // create the TexturedShape with static width and height super(game, new Vector2(x,y), new Vector2(x + 3.4f, y), new Vector2(x + 3.4f, y + 6.5f), new Vector2(x, y + 6.5f)); this.soundEnabled = soundEnabled; this.rGen = new Random(); this.camera = camera; this.map = map; // load the sounds AndroidAudio audio = (AndroidAudio)game.getAudio(); this.sounds[SOUND_JUMP1] = (AndroidSound)audio.newSound("sounds/player/" + this.model + "/jump_1.ogg"); this.sounds[SOUND_JUMP2] = (AndroidSound)audio.newSound("sounds/player/" + this.model + "/jump_2.ogg"); this.sounds[SOUND_WJ1] = (AndroidSound)audio.newSound("sounds/player/" + this.model + "/wj_1.ogg"); this.sounds[SOUND_WJ2] = (AndroidSound)audio.newSound("sounds/player/" + this.model + "/wj_2.ogg"); this.sounds[SOUND_DIE] = (AndroidSound)audio.newSound("sounds/player/" + this.model + "/death.ogg"); this.sounds[SOUND_PICKUP] = (AndroidSound)audio.newSound("sounds/weapon_pickup.ogg"); this.sounds[SOUND_ROCKET] = (AndroidSound)audio.newSound("sounds/rocket_explosion.ogg"); this.sounds[SOUND_PLASMA] = (AndroidSound)audio.newSound("sounds/plasmagun.ogg"); this.loadAnimations(); this.setupVertices(); // create a first-in-first-out pool for plasma decals this.plasmaPool = new FifoPool<TexturedBlock>(new PoolObjectFactory<TexturedBlock>() { public TexturedBlock createObject() { return new TexturedBlock( game, "decals/plasma_hit.png", GameObject.FUNC_NONE, -1, -1, new Vector2(-1, 0), new Vector2(2, 0) ); } }, 10); // create a first-in-first-out pool for rocket decals this.rocketPool = new FifoPool<TexturedBlock>(new PoolObjectFactory<TexturedBlock>() { public TexturedBlock createObject() { return new TexturedBlock( game, "decals/rocket_hit.png", GameObject.FUNC_NONE, -1, -1, new Vector2(-3, 0), new Vector2(5, 0) ); } }, 1); } /** * Player requires to know the gameScreen * * @param GameScreen gameScreen */ public void setGameScreen(GameScreen gameScreen) { this.gameScreen = gameScreen; } /** * Load all defined animations */ public void loadAnimations() { String[][] animations = new String[12][]; animations[ANIM_RUN] = new String[] { "player/" + this.model + "/default.png" }; animations[ANIM_JUMP] = new String[] { "player/" + this.model + "/jump_f1.png", "player/" + this.model + "/jump_f2.png", "player/" + this.model + "/jump_f1.png" }; animations[ANIM_ROCKET_RUN] = new String[] { "player/" + this.model + "/rocket_run.png" }; animations[ANIM_ROCKET_JUMP] = new String[] { "player/" + this.model + "/rocket_jump_f1.png", "player/" + this.model + "/rocket_jump_f2.png", "player/" + this.model + "/rocket_jump_f1.png" }; animations[ANIM_ROCKET_WALLJUMP] = new String[] { "player/" + this.model + "/rocket_walljump_f1.png", "player/" + this.model + "/rocket_walljump_f2.png", "player/" + this.model + "/rocket_walljump_f1.png" }; animations[ANIM_PLASMA_RUN] = new String[] { "player/" + this.model + "/plasma_run.png" }; animations[ANIM_PLASMA_JUMP] = new String[] { "player/" + this.model + "/plasma_jump_f1.png", "player/" + this.model + "/plasma_jump_f2.png", "player/" + this.model + "/plasma_jump_f1.png" }; animations[ANIM_PLASMA_WALLJUMP] = new String[] { "player/" + this.model + "/plasma_walljump_f1.png", "player/" + this.model + "/plasma_walljump_f2.png", "player/" + this.model + "/plasma_walljump_f1.png" }; animations[ANIM_WALLJUMP] = new String[] { "player/" + this.model + "/walljump_f1.png", "player/" + this.model + "/walljump_f2.png", "player/" + this.model + "/walljump_f1.png" }; animations[ANIM_BURN] = new String[] { "player/" + this.model + "/burn_f1.png", "player/" + this.model + "/burn_f2.png", "player/" + this.model + "/burn_f3.png", "player/" + this.model + "/burn_f4.png" }; animations[ANIM_DROWN] = new String[] { "player/" + this.model + "/drown_f1.png", "player/" + this.model + "/drown_f2.png", "player/" + this.model + "/drown_f3.png", "player/" + this.model + "/drown_f4.png" }; animations[ANIM_INVISIBLE] = new String[] { "player/" + this.model + "/invisible.png" }; this.setAnimations(animations); } /** * Remove a tutorial message and continue the * game if the proper event is beeing passed * * @param String event */ public void updateTutorial(String event) { if (this.tutorialActive != null) { if (!event.equals("reset") && !event.equals(this.tutorialActive.event)) return; this.tutorialActive = null; ((GameScreen)this.game.getCurrentScreen()).state = GameState.Running; if (this.tutorialMessage1 != null) { synchronized (this) { this.camera.removeHud(this.tutorialMessage1); this.tutorialMessage1 = null; } } if (this.tutorialMessage2 != null) { synchronized (this) { this.camera.removeHud(this.tutorialMessage2); this.tutorialMessage2 = null; } } if (this.tutorialMessage3 != null) { synchronized (this) { this.camera.removeHud(this.tutorialMessage3); this.tutorialMessage3 = null; } } } } /** * Execute the jump action * * @param float jumpPressedTime */ public void jump(float jumpPressedTime) { if (this.isDead) return; // only for an initial jump action (not if the player holds jump) if (jumpPressedTime == 0) { this.updateTutorial("jump"); } // remember the distance to the ground when falling and pressing jump if (!this.distanceRemembered && this.velocity.y < 0) { TexturedShape ground = this.map.getGround(this); if (ground != null) { this.distanceOnJump = Math.max(0.32f, this.getPosition().y - (ground.getPosition().y + ground.getHeightAt(this.getPosition().x))); this.distanceRemembered = true; } } // only jump when the player is on the floor if (this.onFloor) { this.onFloor = false; if (this.soundEnabled) { int jumpSound = this.rGen.nextInt(SOUND_JUMP2 - SOUND_JUMP1 + 1) + SOUND_JUMP1; this.sounds[jumpSound].play(this.volume); } // reset to startspeed when no speed left if (this.virtualSpeed == 0) { this.virtualSpeed = this.startSpeed; } // give the player a speed boost according to // the distance when initially pressed jump if (this.distanceOnJump > 0) { float boost = (30000 / (this.virtualSpeed / 2) / this.distanceOnJump); this.virtualSpeed += boost; } this.velocity.add(0, 20); this.distanceRemembered = false; this.distanceOnJump = -1; // choose the proper jump animation if (this.attachedItem != null) { switch (this.attachedItem.func) { case GameObject.ITEM_ROCKET: this.activeAnimId = Player.ANIM_ROCKET_JUMP; break; case GameObject.ITEM_PLASMA: this.activeAnimId = Player.ANIM_PLASMA_JUMP; break; default: this.activeAnimId = Player.ANIM_JUMP; break; } } else { this.activeAnimId = Player.ANIM_JUMP; } this.enableAnimation = true; this.animDuration = 0.3f; // when in the air check for walls to perform a walljump } else { // allow walljump only in certain intervals if (jumpPressedTime == 0 && System.nanoTime() / 1000000000.0f > this.lastWallJumped + 1.5f) { List<GameObject> colliders = this.map.getPotentialWallColliders(this); int length = colliders.size(); for (int i = 0; i < length; i++) { GameObject part = colliders.get(i); CollisionInfo info = this.intersect(part); if (info.collided) { if (this.soundEnabled) { int wjSound = this.rGen.nextInt(SOUND_WJ2 - SOUND_WJ1 + 1) + SOUND_WJ1; this.sounds[wjSound].play(this.volume); } // add some velocity after a walljump this.velocity.set(this.velocity.x + 5, 17); // remember the walljump time for the interval to work this.lastWallJumped = System.nanoTime() / 1000000000.0f; // choose the proper animation if (this.attachedItem != null) { switch (this.attachedItem.func) { case GameObject.ITEM_ROCKET: this.activeAnimId = Player.ANIM_ROCKET_WALLJUMP; break; case GameObject.ITEM_PLASMA: this.activeAnimId = Player.ANIM_PLASMA_WALLJUMP; break; default: this.activeAnimId = Player.ANIM_WALLJUMP; break; } } else { this.activeAnimId = Player.ANIM_WALLJUMP; } this.enableAnimation = true; this.animDuration = 0.3f; } } } } } /** * Execute the shoot action * * @param float shootPressedTime */ public void shoot(float shootPressedTime) { this.updateTutorial("shoot"); // if there is no attached item or the // player is dead we can not shoot if (this.attachedItem == null || this.isDead) return; float currentTime = System.nanoTime() / 1000000000.0f; switch (this.attachedItem.func) { // when shooting with the rocketlauncher case GameObject.ITEM_ROCKET: boolean hitWall = false; if (currentTime >= this.lastShot + FIRERATE_ROCKET) { // prefer wall-rockets List<GameObject> colliders = this.map.getPotentialWallColliders(this); int length = colliders.size(); for (int i = 0; i < length; i++) { GameObject part = colliders.get(i); CollisionInfo info = this.intersect(part); if (info.collided) { hitWall = true; float impactX = this.getPosition().x; float impactY = this.getPosition().y; // give the player some speed boost for wall-rockets this.velocity.set(this.velocity.x, this.velocity.y < 0 ? 30 : this.velocity.y + 20); this.virtualSpeed += 200; if (this.soundEnabled) { this.sounds[SOUND_ROCKET].play(this.volume * 1.5f); } // show the rocket explosion TexturedBlock decal = this.rocketPool.newObject(); decal.setPosition(new Vector2(impactX, impactY)); map.addDecal(decal, 0.25f); this.lastShot = currentTime; break; } } // if we didn't hit a wall then hit the ground if (!hitWall) { TexturedShape ground = map.getGround(this); if (ground != null) { float impactY = ground.getPosition().y + ground.getHeightAt(this.getPosition().x) - 4; float distance = this.getPosition().y - impactY; // only allow to hit blocks without functionality (ie. no lava) if (ground.func == GameObject.FUNC_NONE) { this.addToPosition(0, 1); this.velocity.add(0, 100 / distance); this.onFloor = false; } if (this.soundEnabled) { this.sounds[SOUND_ROCKET].play(this.volume * 1.5f); } // show the rocket explosion TexturedBlock decal = this.rocketPool.newObject(); decal.setPosition(new Vector2(this.getPosition().x, impactY)); map.addDecal(decal, 0.25f); } this.lastShot = currentTime; } } break; // when shooting with the plasma gun case GameObject.ITEM_PLASMA: if (currentTime >= this.lastShot + FIRERATE_PLASMA) { // plasma can only hit walls List<GameObject> colliders = this.map.getPotentialWallColliders(this); int length = colliders.size(); for (int i = 0; i < length; i++) { GameObject part = colliders.get(i); CollisionInfo info = this.intersect(part); if (info.collided) { float impactX = this.getPosition().x; float impactY = this.getPosition().y + 1; // give the player some speed boost this.velocity.add(0, 2.5f); this.virtualSpeed += 15; if (this.soundEnabled) { this.sounds[SOUND_PLASMA].play(this.volume * 1.2f); } // show the plasma impact TexturedBlock decal = (TexturedBlock)this.plasmaPool.newObject(); decal.setPosition(new Vector2(impactX, impactY)); map.addDecal(decal, 0.25f); this.lastShot = currentTime; break; } } this.lastShot = currentTime; } break; } } /** * Move the player in the map * * @param Vector2 gravity * @param float deltaTime * @param boolean pressingJump */ public void move(Vector2 gravity, float deltaTime, boolean pressingJump) { // workaround for initial loading if (++frames < 3) return; // if enabled run a player animation if (this.enableAnimation) { this.animTime += deltaTime; if (this.animTime > this.animDuration) { this.enableAnimation = false; this.animTime = 0; if (this.activeAnimId == Player.ANIM_BURN || this.activeAnimId == Player.ANIM_DROWN) { this.activeAnimId = Player.ANIM_INVISIBLE; // when the animation is over, choose // the proper default animation } else { if (this.attachedItem != null) { switch (this.attachedItem.func) { case GameObject.ITEM_ROCKET: this.activeAnimId = Player.ANIM_ROCKET_RUN; break; case GameObject.ITEM_PLASMA: this.activeAnimId = Player.ANIM_PLASMA_RUN; break; default: this.activeAnimId = Player.ANIM_RUN; break; } } else { this.activeAnimId = Player.ANIM_RUN; } } } } if (this.isDead) return; // see if the player collides with a map-function boolean stop = false; List<GameObject> colliders = this.map.getPotentialFuncColliders(this); int length = colliders.size(); for (int i = 0; i < length; i++) { GameObject part = colliders.get(i); CollisionInfo info = this.intersect(part); if (info.collided) { switch (part.func) { case GameObject.FUNC_START_TIMER: this.map.startTimer(); break; case GameObject.FUNC_STOP_TIMER: this.finishRace(); break; case GameObject.FUNC_TUTORIAL: this.showTutorialMessage(part); break; } } if (stop) break; } // see if the player picks up an item (plasmagun, rocketlauncher) length = this.map.items.size(); for (int i = 0; i < length; i++) { TexturedShape item = this.map.items.get(i); float playerX = this.getPosition().x; float itemX = item.getPosition().x; if (playerX >= itemX && playerX <= itemX + item.width) { String texture = ""; switch (item.func) { case GameObject.ITEM_ROCKET: texture = "items/rocket.png"; this.activeAnimId = ANIM_ROCKET_RUN; break; case GameObject.ITEM_PLASMA: texture = "items/plasma.png"; this.activeAnimId = ANIM_PLASMA_RUN; break; } // show a weapon icon in the HUD TexturedBlock hudItem = new TexturedBlock( this.game, texture, item.func, -1, -1, new Vector2(-(this.camera.frustumWidth / 2) + 1, -(this.camera.frustumHeight / 2) + 1), new Vector2(-(this.camera.frustumWidth / 2) + 10, -(this.camera.frustumHeight / 2) + 10) ); camera.addHud(hudItem); this.map.items.remove(item); this.map.pickedUpItems.add(item); if (this.attachedItem != null) { synchronized (this) { this.camera.removeHud(this.attachedItem); this.attachedItem.texture.dispose(); } } this.lastShot = 0; this.attachedItem = hudItem; if (this.soundEnabled) { this.sounds[SOUND_PICKUP].play(this.volume); } break; } } // when player is in the air if (!this.onFloor) { // apply gravity this.velocity.add(gravity.x * deltaTime, gravity.y * deltaTime); // move the player this.addToPosition(this.velocity.x * deltaTime, this.velocity.y * deltaTime); // check for collision with the ground colliders = this.map.getPotentialGroundColliders(this); length = colliders.size(); for (int i = 0; i < length; i++) { GameObject ground = colliders.get(i); CollisionInfo info = this.intersect(ground); // check for functional collisions like water or lava if (info.collided) { switch (ground.func) { case GameObject.FUNC_LAVA: this.activeAnimId = Player.ANIM_BURN; this.enableAnimation = true; this.animDuration = 0.4f; this.die(); return; case GameObject.FUNC_WATER: this.activeAnimId = Player.ANIM_DROWN; this.enableAnimation = true; this.animDuration = 0.4f; this.die(); return; } // ground if (info.type == Polygon.TOP) { this.setPosition(new Vector2(this.getPosition().x, this.getPosition().y + info.distance)); this.velocity.set(this.velocity.x, 0); this.onFloor = true; // wall } else if (info.type == Polygon.LEFT) { this.setPosition(new Vector2(this.getPosition().x - info.distance, this.getPosition().y)); this.velocity.set(0, this.velocity.y); this.virtualSpeed = 0; // ramp up } else if (info.type == Polygon.RAMPUP) { this.setPosition(new Vector2(this.getPosition().x, this.getPosition().y - info.distance)); if (pressingJump && this.virtualSpeed >= 900) { float m = (ground.vertices[2].y - ground.vertices[0].y) / (ground.vertices[2].x - ground.vertices[0].x); this.velocity.set(this.velocity.x, this.velocity.x * m); } else { this.velocity.set(this.velocity.x, 0); this.onFloor = true; } // ramp down } else if (info.type == Polygon.RAMPDOWN) { float m = (ground.vertices[0].y - ground.vertices[2].y) / (ground.vertices[0].x - ground.vertices[2].x); Log.d("DEBUG", "m " + String.valueOf(new Float(m))); this.velocity.set(this.velocity.x, 0); this.virtualSpeed += (-m + 1) * (-m + 1) * (-m + 1) * 128; this.onFloor = true; } break; } } // when on the ground... } else { + this.velocity.set(this.velocity.x, 0); // ... lose some speed if (this.virtualSpeed > 0) { this.virtualSpeed = Math.max(0, this.virtualSpeed - 10000 * deltaTime); } } // apply the velocity given by the virtual-speed this.velocity.set(this.virtualSpeed / 23, this.velocity.y); } /** * Let the player die */ public void die() { this.virtualSpeed = 0; if (this.soundEnabled) { this.sounds[SOUND_DIE].play(this.volume); } this.isDead = true; this.showRestartMessage(); } /** * Show a restart message */ public void showRestartMessage() { this.restartMessage = this.gameScreen.createCameraText(-30, -0); this.restartMessage.text = "Press back to restart"; this.restartMessage.red = 1; this.restartMessage.green = 0; this.restartMessage.blue = 0; this.restartMessage.scale = 0.15f; this.restartMessage.space = 0.1f; this.camera.addHud(this.restartMessage); } /** * Show the current time */ public void showTimeMessage() { this.timeMessage = this.gameScreen.createCameraText(-27, 5); this.timeMessage.text = "Your time: " + String.format("%.4f", this.map.getCurrentTime()); this.timeMessage.red = 0; this.timeMessage.green = 0; this.timeMessage.blue = 1; this.timeMessage.scale = 0.15f; this.timeMessage.space = 0.1f; this.camera.addHud(this.timeMessage); } /** * Show "new record" message */ public void showtRecordMessage() { this.recordMessage = this.gameScreen.createCameraText(-27, 10); this.recordMessage.text = "New personal record!"; this.recordMessage.red = 0; this.recordMessage.green = 1; this.recordMessage.blue = 0; this.recordMessage.scale = 0.15f; this.recordMessage.space = 0.1f; this.camera.addHud(this.recordMessage); } /** * Show "race finished" message */ public void showtFinishMessage() { this.finishMessage= this.gameScreen.createCameraText(-20, 10); this.finishMessage.text = "Race finished!"; this.finishMessage.red = 1; this.finishMessage.green = 1; this.finishMessage.blue = 0; this.finishMessage.scale = 0.15f; this.finishMessage.space = 0.1f; this.camera.addHud(this.finishMessage); } /** * Show a tutorial message * * @param GameObject tutorial */ public void showTutorialMessage(GameObject tutorial) { if (tutorial.finished || this.tutorialActive != null) return; this.tutorialActive = tutorial; tutorial.finished = true; ((GameScreen)this.game.getCurrentScreen()).state = GameState.Paused; this.tutorialMessage1= this.gameScreen.createCameraText(-32, 10); this.tutorialMessage1.text = tutorial.info1; this.tutorialMessage1.red = 0; this.tutorialMessage1.green = 1; this.tutorialMessage1.blue = 0; this.tutorialMessage1.scale = 0.1f; this.tutorialMessage1.space = 0.075f; this.camera.addHud(this.tutorialMessage1); this.tutorialMessage2 = this.gameScreen.createCameraText(-32, 6); this.tutorialMessage2.text = tutorial.info2; this.tutorialMessage2.red = 0; this.tutorialMessage2.green = 1; this.tutorialMessage2.blue = 0; this.tutorialMessage2.scale = 0.1f; this.tutorialMessage2.space = 0.075f; this.camera.addHud(this.tutorialMessage2); this.tutorialMessage3 = this.gameScreen.createCameraText(-32, 2); this.tutorialMessage3.text = tutorial.info3; this.tutorialMessage3.red = 0; this.tutorialMessage3.green = 1; this.tutorialMessage3.blue = 0; this.tutorialMessage3.scale = 0.1f; this.tutorialMessage3.space = 0.075f; this.camera.addHud(this.tutorialMessage3); } /** * Finish the race. Called when stopTimer is touched. */ public void finishRace() { if (!this.map.inRace()) return; this.map.stopTimer(); SharedPreferences prefs = this.game.getSharedPreferences("racesow", Context.MODE_PRIVATE); // save the time to the local scores InternalScoresThread t = new InternalScoresThread( this.game.getApplicationContext(), this.map.fileName, prefs.getString("name", "player"), this.map.getCurrentTime(), new Handler() { @Override public void handleMessage(Message msg) { if (msg.getData().getBoolean("record")) { Player.this.showtRecordMessage(); } else { Player.this.showtFinishMessage(); } Player.this.showTimeMessage(); Player.this.showRestartMessage(); } }); t.start(); } /** * Reset the player to the initial position * and also reset some variables and messages. * * @param float x * @param float y */ public void reset(float x, float y) { this.updateTutorial("reset"); this.isDead = false; this.activeAnimId = ANIM_RUN; this.virtualSpeed = 0; this.setPosition(new Vector2(x, y)); this.velocity.set(0, 0); if (this.attachedItem != null) { synchronized (this) { this.camera.removeHud(this.attachedItem); this.attachedItem.texture.dispose(); this.attachedItem = null; } } if (this.restartMessage != null) { synchronized (this) { this.camera.removeHud(this.restartMessage); this.restartMessage.dispose(); } } if (this.timeMessage != null) { synchronized (this) { this.camera.removeHud(this.timeMessage); this.timeMessage.dispose(); } } if (this.finishMessage != null) { synchronized (this) { this.camera.removeHud(this.finishMessage); this.finishMessage.dispose(); } } if (this.recordMessage != null) { synchronized (this) { this.camera.removeHud(this.recordMessage); this.recordMessage.dispose(); } } } }
true
true
public void move(Vector2 gravity, float deltaTime, boolean pressingJump) { // workaround for initial loading if (++frames < 3) return; // if enabled run a player animation if (this.enableAnimation) { this.animTime += deltaTime; if (this.animTime > this.animDuration) { this.enableAnimation = false; this.animTime = 0; if (this.activeAnimId == Player.ANIM_BURN || this.activeAnimId == Player.ANIM_DROWN) { this.activeAnimId = Player.ANIM_INVISIBLE; // when the animation is over, choose // the proper default animation } else { if (this.attachedItem != null) { switch (this.attachedItem.func) { case GameObject.ITEM_ROCKET: this.activeAnimId = Player.ANIM_ROCKET_RUN; break; case GameObject.ITEM_PLASMA: this.activeAnimId = Player.ANIM_PLASMA_RUN; break; default: this.activeAnimId = Player.ANIM_RUN; break; } } else { this.activeAnimId = Player.ANIM_RUN; } } } } if (this.isDead) return; // see if the player collides with a map-function boolean stop = false; List<GameObject> colliders = this.map.getPotentialFuncColliders(this); int length = colliders.size(); for (int i = 0; i < length; i++) { GameObject part = colliders.get(i); CollisionInfo info = this.intersect(part); if (info.collided) { switch (part.func) { case GameObject.FUNC_START_TIMER: this.map.startTimer(); break; case GameObject.FUNC_STOP_TIMER: this.finishRace(); break; case GameObject.FUNC_TUTORIAL: this.showTutorialMessage(part); break; } } if (stop) break; } // see if the player picks up an item (plasmagun, rocketlauncher) length = this.map.items.size(); for (int i = 0; i < length; i++) { TexturedShape item = this.map.items.get(i); float playerX = this.getPosition().x; float itemX = item.getPosition().x; if (playerX >= itemX && playerX <= itemX + item.width) { String texture = ""; switch (item.func) { case GameObject.ITEM_ROCKET: texture = "items/rocket.png"; this.activeAnimId = ANIM_ROCKET_RUN; break; case GameObject.ITEM_PLASMA: texture = "items/plasma.png"; this.activeAnimId = ANIM_PLASMA_RUN; break; } // show a weapon icon in the HUD TexturedBlock hudItem = new TexturedBlock( this.game, texture, item.func, -1, -1, new Vector2(-(this.camera.frustumWidth / 2) + 1, -(this.camera.frustumHeight / 2) + 1), new Vector2(-(this.camera.frustumWidth / 2) + 10, -(this.camera.frustumHeight / 2) + 10) ); camera.addHud(hudItem); this.map.items.remove(item); this.map.pickedUpItems.add(item); if (this.attachedItem != null) { synchronized (this) { this.camera.removeHud(this.attachedItem); this.attachedItem.texture.dispose(); } } this.lastShot = 0; this.attachedItem = hudItem; if (this.soundEnabled) { this.sounds[SOUND_PICKUP].play(this.volume); } break; } } // when player is in the air if (!this.onFloor) { // apply gravity this.velocity.add(gravity.x * deltaTime, gravity.y * deltaTime); // move the player this.addToPosition(this.velocity.x * deltaTime, this.velocity.y * deltaTime); // check for collision with the ground colliders = this.map.getPotentialGroundColliders(this); length = colliders.size(); for (int i = 0; i < length; i++) { GameObject ground = colliders.get(i); CollisionInfo info = this.intersect(ground); // check for functional collisions like water or lava if (info.collided) { switch (ground.func) { case GameObject.FUNC_LAVA: this.activeAnimId = Player.ANIM_BURN; this.enableAnimation = true; this.animDuration = 0.4f; this.die(); return; case GameObject.FUNC_WATER: this.activeAnimId = Player.ANIM_DROWN; this.enableAnimation = true; this.animDuration = 0.4f; this.die(); return; } // ground if (info.type == Polygon.TOP) { this.setPosition(new Vector2(this.getPosition().x, this.getPosition().y + info.distance)); this.velocity.set(this.velocity.x, 0); this.onFloor = true; // wall } else if (info.type == Polygon.LEFT) { this.setPosition(new Vector2(this.getPosition().x - info.distance, this.getPosition().y)); this.velocity.set(0, this.velocity.y); this.virtualSpeed = 0; // ramp up } else if (info.type == Polygon.RAMPUP) { this.setPosition(new Vector2(this.getPosition().x, this.getPosition().y - info.distance)); if (pressingJump && this.virtualSpeed >= 900) { float m = (ground.vertices[2].y - ground.vertices[0].y) / (ground.vertices[2].x - ground.vertices[0].x); this.velocity.set(this.velocity.x, this.velocity.x * m); } else { this.velocity.set(this.velocity.x, 0); this.onFloor = true; } // ramp down } else if (info.type == Polygon.RAMPDOWN) { float m = (ground.vertices[0].y - ground.vertices[2].y) / (ground.vertices[0].x - ground.vertices[2].x); Log.d("DEBUG", "m " + String.valueOf(new Float(m))); this.velocity.set(this.velocity.x, 0); this.virtualSpeed += (-m + 1) * (-m + 1) * (-m + 1) * 128; this.onFloor = true; } break; } } // when on the ground... } else { // ... lose some speed if (this.virtualSpeed > 0) { this.virtualSpeed = Math.max(0, this.virtualSpeed - 10000 * deltaTime); } } // apply the velocity given by the virtual-speed this.velocity.set(this.virtualSpeed / 23, this.velocity.y); }
public void move(Vector2 gravity, float deltaTime, boolean pressingJump) { // workaround for initial loading if (++frames < 3) return; // if enabled run a player animation if (this.enableAnimation) { this.animTime += deltaTime; if (this.animTime > this.animDuration) { this.enableAnimation = false; this.animTime = 0; if (this.activeAnimId == Player.ANIM_BURN || this.activeAnimId == Player.ANIM_DROWN) { this.activeAnimId = Player.ANIM_INVISIBLE; // when the animation is over, choose // the proper default animation } else { if (this.attachedItem != null) { switch (this.attachedItem.func) { case GameObject.ITEM_ROCKET: this.activeAnimId = Player.ANIM_ROCKET_RUN; break; case GameObject.ITEM_PLASMA: this.activeAnimId = Player.ANIM_PLASMA_RUN; break; default: this.activeAnimId = Player.ANIM_RUN; break; } } else { this.activeAnimId = Player.ANIM_RUN; } } } } if (this.isDead) return; // see if the player collides with a map-function boolean stop = false; List<GameObject> colliders = this.map.getPotentialFuncColliders(this); int length = colliders.size(); for (int i = 0; i < length; i++) { GameObject part = colliders.get(i); CollisionInfo info = this.intersect(part); if (info.collided) { switch (part.func) { case GameObject.FUNC_START_TIMER: this.map.startTimer(); break; case GameObject.FUNC_STOP_TIMER: this.finishRace(); break; case GameObject.FUNC_TUTORIAL: this.showTutorialMessage(part); break; } } if (stop) break; } // see if the player picks up an item (plasmagun, rocketlauncher) length = this.map.items.size(); for (int i = 0; i < length; i++) { TexturedShape item = this.map.items.get(i); float playerX = this.getPosition().x; float itemX = item.getPosition().x; if (playerX >= itemX && playerX <= itemX + item.width) { String texture = ""; switch (item.func) { case GameObject.ITEM_ROCKET: texture = "items/rocket.png"; this.activeAnimId = ANIM_ROCKET_RUN; break; case GameObject.ITEM_PLASMA: texture = "items/plasma.png"; this.activeAnimId = ANIM_PLASMA_RUN; break; } // show a weapon icon in the HUD TexturedBlock hudItem = new TexturedBlock( this.game, texture, item.func, -1, -1, new Vector2(-(this.camera.frustumWidth / 2) + 1, -(this.camera.frustumHeight / 2) + 1), new Vector2(-(this.camera.frustumWidth / 2) + 10, -(this.camera.frustumHeight / 2) + 10) ); camera.addHud(hudItem); this.map.items.remove(item); this.map.pickedUpItems.add(item); if (this.attachedItem != null) { synchronized (this) { this.camera.removeHud(this.attachedItem); this.attachedItem.texture.dispose(); } } this.lastShot = 0; this.attachedItem = hudItem; if (this.soundEnabled) { this.sounds[SOUND_PICKUP].play(this.volume); } break; } } // when player is in the air if (!this.onFloor) { // apply gravity this.velocity.add(gravity.x * deltaTime, gravity.y * deltaTime); // move the player this.addToPosition(this.velocity.x * deltaTime, this.velocity.y * deltaTime); // check for collision with the ground colliders = this.map.getPotentialGroundColliders(this); length = colliders.size(); for (int i = 0; i < length; i++) { GameObject ground = colliders.get(i); CollisionInfo info = this.intersect(ground); // check for functional collisions like water or lava if (info.collided) { switch (ground.func) { case GameObject.FUNC_LAVA: this.activeAnimId = Player.ANIM_BURN; this.enableAnimation = true; this.animDuration = 0.4f; this.die(); return; case GameObject.FUNC_WATER: this.activeAnimId = Player.ANIM_DROWN; this.enableAnimation = true; this.animDuration = 0.4f; this.die(); return; } // ground if (info.type == Polygon.TOP) { this.setPosition(new Vector2(this.getPosition().x, this.getPosition().y + info.distance)); this.velocity.set(this.velocity.x, 0); this.onFloor = true; // wall } else if (info.type == Polygon.LEFT) { this.setPosition(new Vector2(this.getPosition().x - info.distance, this.getPosition().y)); this.velocity.set(0, this.velocity.y); this.virtualSpeed = 0; // ramp up } else if (info.type == Polygon.RAMPUP) { this.setPosition(new Vector2(this.getPosition().x, this.getPosition().y - info.distance)); if (pressingJump && this.virtualSpeed >= 900) { float m = (ground.vertices[2].y - ground.vertices[0].y) / (ground.vertices[2].x - ground.vertices[0].x); this.velocity.set(this.velocity.x, this.velocity.x * m); } else { this.velocity.set(this.velocity.x, 0); this.onFloor = true; } // ramp down } else if (info.type == Polygon.RAMPDOWN) { float m = (ground.vertices[0].y - ground.vertices[2].y) / (ground.vertices[0].x - ground.vertices[2].x); Log.d("DEBUG", "m " + String.valueOf(new Float(m))); this.velocity.set(this.velocity.x, 0); this.virtualSpeed += (-m + 1) * (-m + 1) * (-m + 1) * 128; this.onFloor = true; } break; } } // when on the ground... } else { this.velocity.set(this.velocity.x, 0); // ... lose some speed if (this.virtualSpeed > 0) { this.virtualSpeed = Math.max(0, this.virtualSpeed - 10000 * deltaTime); } } // apply the velocity given by the virtual-speed this.velocity.set(this.virtualSpeed / 23, this.velocity.y); }
diff --git a/jbpm-console-ng-human-tasks/jbpm-console-ng-human-tasks-backend/src/test/java/org/jbpm/console/ng/ht/backend/server/TaskServiceEntryPointLocalTest.java b/jbpm-console-ng-human-tasks/jbpm-console-ng-human-tasks-backend/src/test/java/org/jbpm/console/ng/ht/backend/server/TaskServiceEntryPointLocalTest.java index 1433ae1b4..a906e2c33 100644 --- a/jbpm-console-ng-human-tasks/jbpm-console-ng-human-tasks-backend/src/test/java/org/jbpm/console/ng/ht/backend/server/TaskServiceEntryPointLocalTest.java +++ b/jbpm-console-ng-human-tasks/jbpm-console-ng-human-tasks-backend/src/test/java/org/jbpm/console/ng/ht/backend/server/TaskServiceEntryPointLocalTest.java @@ -1,54 +1,54 @@ package org.jbpm.console.ng.ht.backend.server; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ArchivePaths; import org.jboss.shrinkwrap.api.Filters; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.runner.RunWith; @RunWith(Arquillian.class) public class TaskServiceEntryPointLocalTest extends TaskServiceEntryPointBaseTest { @Deployment() public static Archive<?> createDeployment() { return ShrinkWrap .create(JavaArchive.class, "jbpm-console-ng-human-task-cdi.jar") .addPackage("org.jboss.seam.transaction") // core jbpm .addPackage("org.jbpm.shared.services.api") .addPackage("org.jbpm.shared.services.impl") .addPackage("org.jbpm.services.task") .addPackage("org.jbpm.services.task.annotations") .addPackage("org.jbpm.services.task.api") .addPackage("org.jbpm.services.task.impl") .addPackage("org.jbpm.services.task.impl.model") .addPackage("org.jbpm.services.task.events") .addPackage("org.jbpm.services.task.exception") .addPackage("org.jbpm.services.task.rule") .addPackage("org.jbpm.services.task.rule.impl") .addPackage("org.jbpm.services.task.identity") .addPackage("org.jbpm.services.task.factories") .addPackage("org.jbpm.services.task.internals") .addPackage("org.jbpm.services.task.internals.lifecycle") .addPackage("org.jbpm.services.task.lifecycle.listeners") .addPackage("org.jbpm.services.task.query") .addPackage("org.jbpm.services.task.util") .addPackage("org.jbpm.services.task.deadlines") // deadlines .addPackage("org.jbpm.services.task.deadlines.notifications.impl") .addPackage("org.jbpm.services.task.subtask") // console-ng task service .addPackage("org.jbpm.console.ng.ht.service") - .addPackages(true, Filters.exclude(FormServiceEntryPointImpl.class), "org.jbpm.console.ng.ht.backend.server") + .addPackages(true, Filters.exclude(FormServiceEntryPointImpl.class, FormModelerProcessStarterEntryPointImpl.class), "org.jbpm.console.ng.ht.backend.server") // .addPackage("org.jbpm.services.task.commands") // This should not be // required here .addAsManifestResource("META-INF/persistence.xml", ArchivePaths.create("persistence.xml")) .addAsManifestResource("META-INF/Taskorm.xml", ArchivePaths.create("Taskorm.xml")) .addAsManifestResource("META-INF/beans.xml", ArchivePaths.create("beans.xml")); } }
true
true
public static Archive<?> createDeployment() { return ShrinkWrap .create(JavaArchive.class, "jbpm-console-ng-human-task-cdi.jar") .addPackage("org.jboss.seam.transaction") // core jbpm .addPackage("org.jbpm.shared.services.api") .addPackage("org.jbpm.shared.services.impl") .addPackage("org.jbpm.services.task") .addPackage("org.jbpm.services.task.annotations") .addPackage("org.jbpm.services.task.api") .addPackage("org.jbpm.services.task.impl") .addPackage("org.jbpm.services.task.impl.model") .addPackage("org.jbpm.services.task.events") .addPackage("org.jbpm.services.task.exception") .addPackage("org.jbpm.services.task.rule") .addPackage("org.jbpm.services.task.rule.impl") .addPackage("org.jbpm.services.task.identity") .addPackage("org.jbpm.services.task.factories") .addPackage("org.jbpm.services.task.internals") .addPackage("org.jbpm.services.task.internals.lifecycle") .addPackage("org.jbpm.services.task.lifecycle.listeners") .addPackage("org.jbpm.services.task.query") .addPackage("org.jbpm.services.task.util") .addPackage("org.jbpm.services.task.deadlines") // deadlines .addPackage("org.jbpm.services.task.deadlines.notifications.impl") .addPackage("org.jbpm.services.task.subtask") // console-ng task service .addPackage("org.jbpm.console.ng.ht.service") .addPackages(true, Filters.exclude(FormServiceEntryPointImpl.class), "org.jbpm.console.ng.ht.backend.server") // .addPackage("org.jbpm.services.task.commands") // This should not be // required here .addAsManifestResource("META-INF/persistence.xml", ArchivePaths.create("persistence.xml")) .addAsManifestResource("META-INF/Taskorm.xml", ArchivePaths.create("Taskorm.xml")) .addAsManifestResource("META-INF/beans.xml", ArchivePaths.create("beans.xml")); }
public static Archive<?> createDeployment() { return ShrinkWrap .create(JavaArchive.class, "jbpm-console-ng-human-task-cdi.jar") .addPackage("org.jboss.seam.transaction") // core jbpm .addPackage("org.jbpm.shared.services.api") .addPackage("org.jbpm.shared.services.impl") .addPackage("org.jbpm.services.task") .addPackage("org.jbpm.services.task.annotations") .addPackage("org.jbpm.services.task.api") .addPackage("org.jbpm.services.task.impl") .addPackage("org.jbpm.services.task.impl.model") .addPackage("org.jbpm.services.task.events") .addPackage("org.jbpm.services.task.exception") .addPackage("org.jbpm.services.task.rule") .addPackage("org.jbpm.services.task.rule.impl") .addPackage("org.jbpm.services.task.identity") .addPackage("org.jbpm.services.task.factories") .addPackage("org.jbpm.services.task.internals") .addPackage("org.jbpm.services.task.internals.lifecycle") .addPackage("org.jbpm.services.task.lifecycle.listeners") .addPackage("org.jbpm.services.task.query") .addPackage("org.jbpm.services.task.util") .addPackage("org.jbpm.services.task.deadlines") // deadlines .addPackage("org.jbpm.services.task.deadlines.notifications.impl") .addPackage("org.jbpm.services.task.subtask") // console-ng task service .addPackage("org.jbpm.console.ng.ht.service") .addPackages(true, Filters.exclude(FormServiceEntryPointImpl.class, FormModelerProcessStarterEntryPointImpl.class), "org.jbpm.console.ng.ht.backend.server") // .addPackage("org.jbpm.services.task.commands") // This should not be // required here .addAsManifestResource("META-INF/persistence.xml", ArchivePaths.create("persistence.xml")) .addAsManifestResource("META-INF/Taskorm.xml", ArchivePaths.create("Taskorm.xml")) .addAsManifestResource("META-INF/beans.xml", ArchivePaths.create("beans.xml")); }
diff --git a/gem-maven-plugin/src/main/java/de/saumya/mojo/gem/ExecMojo.java b/gem-maven-plugin/src/main/java/de/saumya/mojo/gem/ExecMojo.java index bc08ca20..24753bdb 100644 --- a/gem-maven-plugin/src/main/java/de/saumya/mojo/gem/ExecMojo.java +++ b/gem-maven-plugin/src/main/java/de/saumya/mojo/gem/ExecMojo.java @@ -1,88 +1,88 @@ package de.saumya.mojo.gem; import java.io.File; import java.io.IOException; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import de.saumya.mojo.ruby.script.Script; import de.saumya.mojo.ruby.script.ScriptException; /** * executes a ruby script in context of the gems from pom. the arguments for * jruby are build like this: * <code>${jruby.args} ${exec.file} ${exec.args} ${args}</code> <br/> * to execute an inline script the exec parameters are ignored. * * @goal exec * @requiresDependencyResolution test * @execute phase="process-resources" */ public class ExecMojo extends AbstractGemMojo { /** * ruby code from the pom configuration part which gets executed. * * @parameter default-value="${exec.script}" */ protected String script = null; /** * ruby file which gets executed in context of the given gems.. * * @parameter default-value="${exec.file}" */ protected File file = null; /** * output file where the standard out will be written * * @parameter default-value="${jruby.outputFile}" */ protected File outputFile = null; /** * arguments for the ruby script given through file parameter. * * @parameter default-value="${exec.args}" */ protected String execArgs = null; @Override public void execute() throws MojoExecutionException, MojoFailureException { // TODO jruby-complete tries to install gems // file:/jruby-complete-1.5.1.jar!/META-INF/jruby.home/lib/ruby/gems/1.8 // instead of in $HOME/.gem this.includeOpenSSL = this.jrubyFork; super.execute(); } @Override public void executeWithGems() throws MojoExecutionException, ScriptException, IOException { Script s; if (this.script != null && this.script.length() > 0) { s = this.factory.newScript(this.script); } else if (this.file != null) { s = this.factory.newScript(this.file); } else { s = this.factory.newArguments(); } s.addArgs(this.execArgs); s.addArgs(this.args); if (s.isValid()) { if(outputFile != null){ s.executeIn(launchDirectory(), outputFile); } else { s.executeIn(launchDirectory()); } } else { - getLog().warn("no arguments given. use -Dexec.args=... or -Dexec.script=... or -Dexec.file=..."); + getLog().warn("no arguments given. use -Dexec.script=... or -Dexec.file=..."); } } }
true
true
public void executeWithGems() throws MojoExecutionException, ScriptException, IOException { Script s; if (this.script != null && this.script.length() > 0) { s = this.factory.newScript(this.script); } else if (this.file != null) { s = this.factory.newScript(this.file); } else { s = this.factory.newArguments(); } s.addArgs(this.execArgs); s.addArgs(this.args); if (s.isValid()) { if(outputFile != null){ s.executeIn(launchDirectory(), outputFile); } else { s.executeIn(launchDirectory()); } } else { getLog().warn("no arguments given. use -Dexec.args=... or -Dexec.script=... or -Dexec.file=..."); } }
public void executeWithGems() throws MojoExecutionException, ScriptException, IOException { Script s; if (this.script != null && this.script.length() > 0) { s = this.factory.newScript(this.script); } else if (this.file != null) { s = this.factory.newScript(this.file); } else { s = this.factory.newArguments(); } s.addArgs(this.execArgs); s.addArgs(this.args); if (s.isValid()) { if(outputFile != null){ s.executeIn(launchDirectory(), outputFile); } else { s.executeIn(launchDirectory()); } } else { getLog().warn("no arguments given. use -Dexec.script=... or -Dexec.file=..."); } }
diff --git a/src/main/java/hudson/plugins/sshslaves/SSHLauncher.java b/src/main/java/hudson/plugins/sshslaves/SSHLauncher.java index b9d552b..9a7f050 100644 --- a/src/main/java/hudson/plugins/sshslaves/SSHLauncher.java +++ b/src/main/java/hudson/plugins/sshslaves/SSHLauncher.java @@ -1,706 +1,706 @@ package hudson.plugins.sshslaves; import static hudson.Util.fixEmpty; import static java.util.logging.Level.FINE; import com.trilead.ssh2.SCPClient; import hudson.AbortException; import hudson.EnvVars; import hudson.Extension; import hudson.Util; import hudson.model.Descriptor; import hudson.model.Hudson; import hudson.model.JDK; import hudson.model.TaskListener; import hudson.remoting.Channel; import hudson.slaves.ComputerLauncher; import hudson.slaves.EnvironmentVariablesNodeProperty; import hudson.slaves.NodeProperty; import hudson.slaves.NodePropertyDescriptor; import hudson.slaves.SlaveComputer; import hudson.tools.JDKInstaller; import hudson.tools.JDKInstaller.CPU; import hudson.tools.JDKInstaller.Platform; import hudson.tools.ToolLocationNodeProperty; import hudson.tools.ToolLocationNodeProperty.ToolLocation; import hudson.util.DescribableList; import hudson.util.IOException2; import hudson.util.NullStream; import hudson.util.Secret; import hudson.util.StreamCopyThread; import java.io.BufferedOutputStream; import java.io.BufferedReader; 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.PrintStream; import java.io.StringWriter; import java.net.URL; import java.text.NumberFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.logging.Logger; import java.util.regex.Pattern; import org.apache.commons.io.IOUtils; import org.apache.commons.io.output.CountingOutputStream; import org.apache.commons.io.output.TeeOutputStream; import org.kohsuke.putty.PuTTYKey; import org.kohsuke.stapler.DataBoundConstructor; import com.trilead.ssh2.Connection; import com.trilead.ssh2.SFTPv3Client; import com.trilead.ssh2.SFTPv3FileAttributes; import com.trilead.ssh2.Session; import com.trilead.ssh2.StreamGobbler; /** * A computer launcher that tries to start a linux slave by opening an SSH connection and trying to find java. */ public class SSHLauncher extends ComputerLauncher { /** * Field host */ private final String host; /** * Field port */ private final int port; /** * Field username */ private final String username; /** * Field password * * @todo remove password once authentication is stored in the descriptor. */ private final Secret password; /** * File path of the private key. */ private final String privatekey; /** * Field jvmOptions. */ private final String jvmOptions; /** * Field connection */ private transient Connection connection; /** * Constructor SSHLauncher creates a new SSHLauncher instance. * * @param host The host to connect to. * @param port The port to connect on. * @param username The username to connect as. * @param password The password to connect with. * @param privatekey The ssh privatekey to connect with. * @param jvmOptions */ @DataBoundConstructor public SSHLauncher(String host, int port, String username, String password, String privatekey, String jvmOptions) { this.host = host; this.jvmOptions = jvmOptions; this.port = port == 0 ? 22 : port; this.username = username; this.password = fixEmpty(password)!=null ? Secret.fromString(password) : null; this.privatekey = privatekey; } /** * {@inheritDoc} */ @Override public boolean isLaunchSupported() { return true; } /** * Gets the JVM Options used to launch the slave JVM. * @return */ public String getJvmOptions() { return jvmOptions == null ? "" : jvmOptions; } /** * Gets the formatted current time stamp. * * @return the formatted current time stamp. */ private static String getTimestamp() { return String.format("[%1$tD %1$tT]", new Date()); } /** * Returns the remote root workspace (without trailing slash). * * @param computer The slave computer to get the root workspace of. * * @return the remote root workspace (without trailing slash). */ private static String getWorkingDirectory(SlaveComputer computer) { String workingDirectory = computer.getNode().getRemoteFS(); while (workingDirectory.endsWith("/")) { workingDirectory = workingDirectory.substring(0, workingDirectory.length() - 1); } return workingDirectory; } /** * {@inheritDoc} */ @Override public synchronized void launch(final SlaveComputer computer, final TaskListener listener) throws InterruptedException { connection = new Connection(host, port); try { openConnection(listener); verifyNoHeaderJunk(listener); reportEnvironment(listener); String java = null; List<String> tried = new ArrayList<String>(); outer: for (JavaProvider provider : JavaProvider.all()) { for (String javaCommand : provider.getJavas(computer, listener, connection)) { LOGGER.fine("Trying Java at "+javaCommand); try { tried.add(javaCommand); java = checkJavaVersion(listener, javaCommand); if (java != null) { break outer; } } catch (IOException e) { LOGGER.log(FINE, "Failed to check the Java version",e); // try the next one } } } final String workingDirectory = getWorkingDirectory(computer); if (java == null) { // attempt auto JDK installation ByteArrayOutputStream buf = new ByteArrayOutputStream(); try { java = attemptToInstallJDK(listener, workingDirectory, buf); } catch (IOException e) { throw new IOException2("Could not find any known supported java version in "+tried+", and we also failed to install JDK as a fallback",e); } } copySlaveJar(listener, workingDirectory); startSlave(computer, listener, java, workingDirectory); PluginImpl.register(connection); } catch (RuntimeException e) { e.printStackTrace(listener.error(Messages.SSHLauncher_UnexpectedError())); } catch (Error e) { e.printStackTrace(listener.error(Messages.SSHLauncher_UnexpectedError())); } catch (IOException e) { e.printStackTrace(listener.getLogger()); connection.close(); connection = null; listener.getLogger().println(Messages.SSHLauncher_ConnectionClosed(getTimestamp())); } } /** * Makes sure that SSH connection won't produce any unwanted text, which will interfere with sftp execution. */ private void verifyNoHeaderJunk(TaskListener listener) throws IOException, InterruptedException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); connection.exec("true",baos); String s = baos.toString(); if (s.length()!=0) { listener.getLogger().println(Messages.SSHLauncher_SSHHeeaderJunkDetected()); listener.getLogger().println(s); throw new AbortException(); } } /** * Attempts to install JDK, and return the path to Java. */ private String attemptToInstallJDK(TaskListener listener, String workingDirectory, ByteArrayOutputStream buf) throws IOException, InterruptedException { if (connection.exec("uname -a",new TeeOutputStream(buf,listener.getLogger()))!=0) throw new IOException("Failed to run 'uname' to obtain the environment"); // guess the platform from uname output. I don't use the specific options because I'm not sure // if various platforms have the consistent options // // === some of the output collected ==== // Linux bear 2.6.28-15-generic #49-Ubuntu SMP Tue Aug 18 19:25:34 UTC 2009 x86_64 GNU/Linux // Linux wssqe20 2.6.24-24-386 #1 Tue Aug 18 16:24:26 UTC 2009 i686 GNU/Linux // SunOS hudson 5.11 snv_79a i86pc i386 i86pc // SunOS legolas 5.9 Generic_112233-12 sun4u sparc SUNW,Sun-Fire-280R // CYGWIN_NT-5.1 franz 1.7.0(0.185/5/3) 2008-07-22 19:09 i686 Cygwin // Windows_NT WINXPIE7 5 01 586 // (this one is from MKS) String uname = buf.toString(); Platform p = null; CPU cpu = null; if (uname.contains("GNU/Linux")) p = Platform.LINUX; if (uname.contains("SunOS")) p = Platform.SOLARIS; if (uname.contains("CYGWIN")) p = Platform.WINDOWS; if (uname.contains("Windows_NT")) p = Platform.WINDOWS; if (uname.contains("sparc")) cpu = CPU.Sparc; if (uname.contains("x86_64")) cpu = CPU.amd64; if (Pattern.compile("\\bi?[3-6]86\\b").matcher(uname).find()) cpu = CPU.i386; // look for ix86 as a word if (p==null || cpu==null) throw new IOException(Messages.SSHLauncher_FailedToDetectEnvironment(uname)); String javaDir = workingDirectory + "/jdk"; // this is where we install Java to String bundleFile = workingDirectory + "/" + p.bundleFileName; // this is where we download the bundle to SFTPClient sftp = new SFTPClient(connection); // wipe out and recreate the Java directory connection.exec("rm -rf "+javaDir,listener.getLogger()); sftp.mkdirs(javaDir, 0755); JDKInstaller jdk = new JDKInstaller("jdk-6u16-oth-JPR@CDS-CDS_Developer",true); URL bundle = jdk.locate(listener, p, cpu); listener.getLogger().println("Downloading JDK6u16"); Util.copyStreamAndClose(bundle.openStream(),new BufferedOutputStream(sftp.writeToFile(bundleFile),32*1024)); sftp.chmod(bundleFile,0755); jdk.install(new RemoteLauncher(listener,connection),p,new SFTPFileSystem(sftp),listener, javaDir,bundleFile); return javaDir+"/bin/java"; } /** * Starts the slave process. * * @param computer The computer. * @param listener The listener. * @param java The full path name of the java executable to use. * @param workingDirectory The working directory from which to start the java process. * * @throws IOException If something goes wrong. */ private void startSlave(SlaveComputer computer, final TaskListener listener, String java, String workingDirectory) throws IOException { final Session session = connection.openSession(); String cmd = "cd '" + workingDirectory + "' && " + java + " " + getJvmOptions() + " -jar slave.jar"; listener.getLogger().println(Messages.SSHLauncher_StartingSlaveProcess(getTimestamp(), cmd)); session.execCommand(cmd); final StreamGobbler out = new StreamGobbler(session.getStdout()); final StreamGobbler err = new StreamGobbler(session.getStderr()); // capture error information from stderr. this will terminate itself // when the process is killed. new StreamCopyThread("stderr copier for remote agent on " + computer.getDisplayName(), err, listener.getLogger()).start(); try { computer.setChannel(out, session.getStdin(), listener.getLogger(), new Channel.Listener() { @Override public void onClosed(Channel channel, IOException cause) { if (cause != null) { cause.printStackTrace(listener.error(hudson.model.Messages.Slave_Terminated(getTimestamp()))); } try { session.close(); } catch (Throwable t) { t.printStackTrace(listener.error(Messages.SSHLauncher_ErrorWhileClosingConnection())); } try { out.close(); } catch (Throwable t) { t.printStackTrace(listener.error(Messages.SSHLauncher_ErrorWhileClosingConnection())); } try { err.close(); } catch (Throwable t) { t.printStackTrace(listener.error(Messages.SSHLauncher_ErrorWhileClosingConnection())); } } }); } catch (InterruptedException e) { session.close(); throw new IOException2(Messages.SSHLauncher_AbortedDuringConnectionOpen(), e); } } /** * Method copies the slave jar to the remote system. * * @param listener The listener. * @param workingDirectory The directory into whihc the slave jar will be copied. * * @throws IOException If something goes wrong. */ private void copySlaveJar(TaskListener listener, String workingDirectory) throws IOException, InterruptedException { String fileName = workingDirectory + "/slave.jar"; listener.getLogger().println(Messages.SSHLauncher_StartingSFTPClient(getTimestamp())); SFTPClient sftpClient = null; try { sftpClient = new SFTPClient(connection); try { SFTPv3FileAttributes fileAttributes = sftpClient._stat(workingDirectory); if (fileAttributes==null) { listener.getLogger().println(Messages.SSHLauncher_RemoteFSDoesNotExist(getTimestamp(), workingDirectory)); sftpClient.mkdirs(workingDirectory, 0700); } else if (fileAttributes.isRegularFile()) { throw new IOException(Messages.SSHLauncher_RemoteFSIsAFile(workingDirectory)); } try { // try to delete the file in case the slave we are copying is shorter than the slave // that is already there sftpClient.rm(fileName); } catch (IOException e) { // the file did not exist... so no need to delete it! } listener.getLogger().println(Messages.SSHLauncher_CopyingSlaveJar(getTimestamp())); try { CountingOutputStream os = new CountingOutputStream(sftpClient.writeToFile(fileName)); Util.copyStreamAndClose( Hudson.getInstance().servletContext.getResourceAsStream("/WEB-INF/slave.jar"), os); listener.getLogger().println(Messages.SSHLauncher_CopiedXXXBytes(getTimestamp(), os.getByteCount())); } catch (Exception e) { throw new IOException2(Messages.SSHLauncher_ErrorCopyingSlaveJarTo(fileName), e); } } catch (Exception e) { throw new IOException2(Messages.SSHLauncher_ErrorCopyingSlaveJar(), e); } } catch (IOException e) { if (sftpClient == null) { // lets try to recover if the slave doesn't have an SFTP service copySlaveJarUsingSCP(listener, workingDirectory); } else { throw e; } } finally { if (sftpClient != null) { sftpClient.close(); } } } /** * Method copies the slave jar to the remote system using scp. * * @param listener The listener. * @param workingDirectory The directory into which the slave jar will be copied. * * @throws IOException If something goes wrong. * @throws InterruptedException If something goes wrong. */ private void copySlaveJarUsingSCP(TaskListener listener, String workingDirectory) throws IOException, InterruptedException { listener.getLogger().println(Messages.SSHLauncher_StartingSCPClient(getTimestamp())); SCPClient scp = new SCPClient(connection); try { // check if the working directory exists if (connection.exec("test -d " + workingDirectory ,listener.getLogger())!=0) { listener.getLogger().println(Messages.SSHLauncher_RemoteFSDoesNotExist(getTimestamp(), workingDirectory)); // working directory doesn't exist, lets make it. if (connection.exec("mkdir -p " + workingDirectory, listener.getLogger())!=0) { listener.getLogger().println("Failed to create "+workingDirectory); } } // delete the slave jar as we do with SFTP connection.exec("rm " + workingDirectory + "/slave.jar", new NullStream()); // SCP it to the slave. hudson.Util.ByteArrayOutputStream2 doesn't work for this. It pads the byte array. InputStream is = Hudson.getInstance().servletContext.getResourceAsStream("/WEB-INF/slave.jar"); listener.getLogger().println(Messages.SSHLauncher_CopyingSlaveJar(getTimestamp())); scp.put(IOUtils.toByteArray(is), "slave.jar", workingDirectory, "0644"); } catch (IOException e) { throw new IOException2(Messages.SSHLauncher_ErrorCopyingSlaveJar(), e); } } private void reportEnvironment(TaskListener listener) throws IOException, InterruptedException { listener.getLogger().println(Messages._SSHLauncher_RemoteUserEnvironment(getTimestamp())); connection.exec("set",listener.getLogger()); } private String checkJavaVersion(TaskListener listener, String javaCommand) throws IOException, InterruptedException { listener.getLogger().println(Messages.SSHLauncher_CheckingDefaultJava(getTimestamp(),javaCommand)); StringWriter output = new StringWriter(); // record output from Java ByteArrayOutputStream out = new ByteArrayOutputStream(); connection.exec(javaCommand + " "+getJvmOptions() + " -version",out); BufferedReader r = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(out.toByteArray()))); final String result = checkJavaVersion(listener.getLogger(), javaCommand, r, output); if(null == result) { listener.getLogger().println(Messages.SSHLauncher_UknownJavaVersion(javaCommand)); listener.getLogger().println(output); throw new IOException(Messages.SSHLauncher_UknownJavaVersion(javaCommand)); } else { return result; } } /** * Given the output of "java -version" in <code>r</code>, determine if this * version of Java is supported. This method has default visiblity for testing. * * @param logger * where to log the output * @param javaCommand * the command executed, used for logging * @param r * the output of "java -version" * @param output * copy the data from <code>r</code> into this output buffer */ static String checkJavaVersion(final PrintStream logger, String javaCommand, final BufferedReader r, final StringWriter output) throws IOException { String line; while (null != (line = r.readLine())) { output.write(line); output.write("\n"); line = line.toLowerCase(); if (line.startsWith("java version \"") || line.startsWith("openjdk version \"")) { final String versionStr = line.substring( line.indexOf('\"') + 1, line.lastIndexOf('\"')); logger.println(Messages.SSHLauncher_JavaVersionResult( getTimestamp(), javaCommand, versionStr)); // parse as a number and we should be OK as all we care about is up through the first dot. try { final Number version = NumberFormat.getNumberInstance(Locale.US).parse(versionStr); if(version.doubleValue() < 1.5) { throw new IOException(Messages .SSHLauncher_NoJavaFound(line)); } } catch(final ParseException e) { throw new IOException(Messages.SSHLauncher_NoJavaFound(line)); } return javaCommand; } } return null; } private void openConnection(TaskListener listener) throws IOException { listener.getLogger().println(Messages.SSHLauncher_OpeningSSHConnection(getTimestamp(), host + ":" + port)); connection.connect(); String username = this.username; if(fixEmpty(username)==null) { username = System.getProperty("user.name"); LOGGER.fine("Defaulting the user name to "+username); } - String pass = getPassword(); + String pass = Util.fixNull(getPassword()); boolean isAuthenticated = false; if(fixEmpty(privatekey)==null && fixEmpty(pass)==null) { // check the default key locations if no authentication method is explicitly configured. File home = new File(System.getProperty("user.home")); for (String keyName : Arrays.asList("id_rsa","id_dsa","identity")) { File key = new File(home,".ssh/"+keyName); if (key.exists()) { listener.getLogger() .println(Messages.SSHLauncher_AuthenticatingPublicKey(getTimestamp(), username, key)); isAuthenticated = connection.authenticateWithPublicKey(username, key, null); } if (isAuthenticated) break; } } if (!isAuthenticated && fixEmpty(privatekey)!=null) { File key = new File(privatekey); if (key.exists()) { listener.getLogger() .println(Messages.SSHLauncher_AuthenticatingPublicKey(getTimestamp(), username, privatekey)); if (PuTTYKey.isPuTTYKeyFile(key)) { LOGGER.fine(key+" is a PuTTY key file"); String openSshKey = new PuTTYKey(key, pass).toOpenSSH(); isAuthenticated = connection.authenticateWithPublicKey(username, openSshKey.toCharArray(), pass); } else { isAuthenticated = connection.authenticateWithPublicKey(username, key, pass); } } } - if (!isAuthenticated && pass!=null) { + if (!isAuthenticated) { listener.getLogger() .println(Messages.SSHLauncher_AuthenticatingUserPass(getTimestamp(), username, "******")); isAuthenticated = connection.authenticateWithPassword(username, pass); } if (isAuthenticated && connection.isAuthenticationComplete()) { listener.getLogger().println(Messages.SSHLauncher_AuthenticationSuccessful(getTimestamp())); } else { listener.getLogger().println(Messages.SSHLauncher_AuthenticationFailed(getTimestamp())); connection.close(); connection = null; listener.getLogger().println(Messages.SSHLauncher_ConnectionClosed(getTimestamp())); throw new AbortException(Messages.SSHLauncher_AuthenticationFailedException()); } } /** * {@inheritDoc} */ @Override public synchronized void afterDisconnect(SlaveComputer slaveComputer, TaskListener listener) { String workingDirectory = getWorkingDirectory(slaveComputer); String fileName = workingDirectory + "/slave.jar"; if (connection != null) { SFTPv3Client sftpClient = null; try { sftpClient = new SFTPv3Client(connection); sftpClient.rm(fileName); } catch (Exception e) { e.printStackTrace(listener.error(Messages.SSHLauncher_ErrorDeletingFile(getTimestamp()))); } finally { if (sftpClient != null) { sftpClient.close(); } } connection.close(); PluginImpl.unregister(connection); connection = null; listener.getLogger().println(Messages.SSHLauncher_ConnectionClosed(getTimestamp())); } super.afterDisconnect(slaveComputer, listener); } /** * Getter for property 'host'. * * @return Value for property 'host'. */ public String getHost() { return host; } /** * Getter for property 'port'. * * @return Value for property 'port'. */ public int getPort() { return port; } /** * Getter for property 'username'. * * @return Value for property 'username'. */ public String getUsername() { return username; } /** * Getter for property 'password'. * * @return Value for property 'password'. */ public String getPassword() { return password!=null ? password.toString() : null; } /** * Getter for property 'privatekey'. * * @return Value for property 'privatekey'. */ public String getPrivatekey() { return privatekey; } @Extension public static class DescriptorImpl extends Descriptor<ComputerLauncher> { // TODO move the authentication storage to descriptor... see SubversionSCM.java // TODO add support for key files /** * {@inheritDoc} */ public String getDisplayName() { return Messages.SSHLauncher_DescriptorDisplayName(); } } @Extension public static class DefaultJavaProvider extends JavaProvider { @Override public List<String> getJavas(SlaveComputer computer, TaskListener listener, Connection connection) { List<String> javas = new ArrayList<String>(Arrays.asList( "java", "/usr/bin/java", "/usr/java/default/bin/java", "/usr/java/latest/bin/java", "/usr/local/bin/java", "/usr/local/java/bin/java", getWorkingDirectory(computer)+"/jdk/bin/java")); // this is where we attempt to auto-install DescribableList<NodeProperty<?>,NodePropertyDescriptor> list = computer.getNode().getNodeProperties(); if (list != null) { Descriptor jdk = Hudson.getInstance().getDescriptorByType(JDK.DescriptorImpl.class); for (NodeProperty prop : list) { if (prop instanceof EnvironmentVariablesNodeProperty) { EnvVars env = ((EnvironmentVariablesNodeProperty)prop).getEnvVars(); if (env != null && env.containsKey("JAVA_HOME")) javas.add(env.get("JAVA_HOME") + "/bin/java"); } else if (prop instanceof ToolLocationNodeProperty) { for (ToolLocation tool : ((ToolLocationNodeProperty)prop).getLocations()) if (tool.getType() == jdk) javas.add(tool.getHome() + "/bin/java"); } } } return javas; } } private static final Logger LOGGER = Logger.getLogger(SSHLauncher.class.getName()); // static { // com.trilead.ssh2.log.Logger.enabled = true; // com.trilead.ssh2.log.Logger.logger = new DebugLogger() { // public void log(int level, String className, String message) { // System.out.println(className+"\n"+message); // } // }; // } }
false
true
private void openConnection(TaskListener listener) throws IOException { listener.getLogger().println(Messages.SSHLauncher_OpeningSSHConnection(getTimestamp(), host + ":" + port)); connection.connect(); String username = this.username; if(fixEmpty(username)==null) { username = System.getProperty("user.name"); LOGGER.fine("Defaulting the user name to "+username); } String pass = getPassword(); boolean isAuthenticated = false; if(fixEmpty(privatekey)==null && fixEmpty(pass)==null) { // check the default key locations if no authentication method is explicitly configured. File home = new File(System.getProperty("user.home")); for (String keyName : Arrays.asList("id_rsa","id_dsa","identity")) { File key = new File(home,".ssh/"+keyName); if (key.exists()) { listener.getLogger() .println(Messages.SSHLauncher_AuthenticatingPublicKey(getTimestamp(), username, key)); isAuthenticated = connection.authenticateWithPublicKey(username, key, null); } if (isAuthenticated) break; } } if (!isAuthenticated && fixEmpty(privatekey)!=null) { File key = new File(privatekey); if (key.exists()) { listener.getLogger() .println(Messages.SSHLauncher_AuthenticatingPublicKey(getTimestamp(), username, privatekey)); if (PuTTYKey.isPuTTYKeyFile(key)) { LOGGER.fine(key+" is a PuTTY key file"); String openSshKey = new PuTTYKey(key, pass).toOpenSSH(); isAuthenticated = connection.authenticateWithPublicKey(username, openSshKey.toCharArray(), pass); } else { isAuthenticated = connection.authenticateWithPublicKey(username, key, pass); } } } if (!isAuthenticated && pass!=null) { listener.getLogger() .println(Messages.SSHLauncher_AuthenticatingUserPass(getTimestamp(), username, "******")); isAuthenticated = connection.authenticateWithPassword(username, pass); } if (isAuthenticated && connection.isAuthenticationComplete()) { listener.getLogger().println(Messages.SSHLauncher_AuthenticationSuccessful(getTimestamp())); } else { listener.getLogger().println(Messages.SSHLauncher_AuthenticationFailed(getTimestamp())); connection.close(); connection = null; listener.getLogger().println(Messages.SSHLauncher_ConnectionClosed(getTimestamp())); throw new AbortException(Messages.SSHLauncher_AuthenticationFailedException()); } }
private void openConnection(TaskListener listener) throws IOException { listener.getLogger().println(Messages.SSHLauncher_OpeningSSHConnection(getTimestamp(), host + ":" + port)); connection.connect(); String username = this.username; if(fixEmpty(username)==null) { username = System.getProperty("user.name"); LOGGER.fine("Defaulting the user name to "+username); } String pass = Util.fixNull(getPassword()); boolean isAuthenticated = false; if(fixEmpty(privatekey)==null && fixEmpty(pass)==null) { // check the default key locations if no authentication method is explicitly configured. File home = new File(System.getProperty("user.home")); for (String keyName : Arrays.asList("id_rsa","id_dsa","identity")) { File key = new File(home,".ssh/"+keyName); if (key.exists()) { listener.getLogger() .println(Messages.SSHLauncher_AuthenticatingPublicKey(getTimestamp(), username, key)); isAuthenticated = connection.authenticateWithPublicKey(username, key, null); } if (isAuthenticated) break; } } if (!isAuthenticated && fixEmpty(privatekey)!=null) { File key = new File(privatekey); if (key.exists()) { listener.getLogger() .println(Messages.SSHLauncher_AuthenticatingPublicKey(getTimestamp(), username, privatekey)); if (PuTTYKey.isPuTTYKeyFile(key)) { LOGGER.fine(key+" is a PuTTY key file"); String openSshKey = new PuTTYKey(key, pass).toOpenSSH(); isAuthenticated = connection.authenticateWithPublicKey(username, openSshKey.toCharArray(), pass); } else { isAuthenticated = connection.authenticateWithPublicKey(username, key, pass); } } } if (!isAuthenticated) { listener.getLogger() .println(Messages.SSHLauncher_AuthenticatingUserPass(getTimestamp(), username, "******")); isAuthenticated = connection.authenticateWithPassword(username, pass); } if (isAuthenticated && connection.isAuthenticationComplete()) { listener.getLogger().println(Messages.SSHLauncher_AuthenticationSuccessful(getTimestamp())); } else { listener.getLogger().println(Messages.SSHLauncher_AuthenticationFailed(getTimestamp())); connection.close(); connection = null; listener.getLogger().println(Messages.SSHLauncher_ConnectionClosed(getTimestamp())); throw new AbortException(Messages.SSHLauncher_AuthenticationFailedException()); } }
diff --git a/bundles/org.eclipse.equinox.p2.ui.importexport/src/org/eclipse/equinox/internal/p2/importexport/internal/wizard/ImportWizard.java b/bundles/org.eclipse.equinox.p2.ui.importexport/src/org/eclipse/equinox/internal/p2/importexport/internal/wizard/ImportWizard.java index fa8b88ac8..f059fef8e 100644 --- a/bundles/org.eclipse.equinox.p2.ui.importexport/src/org/eclipse/equinox/internal/p2/importexport/internal/wizard/ImportWizard.java +++ b/bundles/org.eclipse.equinox.p2.ui.importexport/src/org/eclipse/equinox/internal/p2/importexport/internal/wizard/ImportWizard.java @@ -1,147 +1,147 @@ /******************************************************************************* * Copyright (c) 2011 WindRiver 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: * WindRiver Corporation - initial API and implementation * IBM Corporation - Ongoing development *******************************************************************************/ package org.eclipse.equinox.internal.p2.importexport.internal.wizard; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collection; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.importexport.internal.*; import org.eclipse.equinox.internal.p2.ui.ProvUI; import org.eclipse.equinox.internal.p2.ui.ProvUIMessages; import org.eclipse.equinox.internal.p2.ui.dialogs.ISelectableIUsPage; import org.eclipse.equinox.internal.p2.ui.dialogs.InstallWizard; import org.eclipse.equinox.internal.p2.ui.model.IUElementListRoot; import org.eclipse.equinox.p2.engine.ProvisioningContext; import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.operations.InstallOperation; import org.eclipse.equinox.p2.operations.ProvisioningSession; import org.eclipse.equinox.p2.ui.LoadMetadataRepositoryJob; import org.eclipse.equinox.p2.ui.ProvisioningUI; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.operation.IRunnableContext; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IImportWizard; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.statushandlers.StatusManager; public class ImportWizard extends InstallWizard implements IImportWizard { public ImportWizard() { this(ProvisioningUI.getDefaultUI(), null, null, null); } public ImportWizard(ProvisioningUI ui, InstallOperation operation, Collection<IInstallableUnit> initialSelections, LoadMetadataRepositoryJob preloadJob) { super(ui, operation, initialSelections, preloadJob); IDialogSettings workbenchSettings = ImportExportActivator.getDefault().getDialogSettings(); String sectionName = "ImportWizard"; //$NON-NLS-1$ IDialogSettings section = workbenchSettings.getSection(sectionName); if (section == null) { section = workbenchSettings.addNewSection(sectionName); } setDialogSettings(section); } public void init(IWorkbench workbench, IStructuredSelection selection) { setWindowTitle(Messages.ImportWizard_WINDOWTITLE); setDefaultPageImageDescriptor(ImageDescriptor.createFromURL(Platform.getBundle(Constants.Bundle_ID).getEntry("icons/install_wiz.gif"))); //$NON-NLS-1$ setNeedsProgressMonitor(true); } @Override protected ISelectableIUsPage createMainPage(IUElementListRoot input, Object[] selections) { return new ImportPage(ui, this); } @Override protected ProvisioningContext getProvisioningContext() { return ((ImportPage) mainPage).getProvisioningContext(); } /** * Recompute the provisioning plan based on the items in the IUElementListRoot and the given provisioning context. * Report progress using the specified runnable context. This method may be called before the page is created. * * @param runnableContext */ @Override public void recomputePlan(IRunnableContext runnableContext) { if (((ImportPage) mainPage).hasUnloadedRepo()) { try { runnableContext.run(true, true, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InterruptedException { final SubMonitor sub = SubMonitor.convert(monitor, 1000); ((ImportPage) mainPage).recompute(sub.newChild(800)); if (sub.isCanceled()) throw new InterruptedException(); Display.getDefault().syncExec(new Runnable() { public void run() { ProvisioningContext context = getProvisioningContext(); initializeResolutionModelElements(getOperationSelections()); if (planSelections.length == 0) { - operation = new InstallOperation(new ProvisioningSession(((ImportPage) mainPage).agent), new ArrayList<IInstallableUnit>()) { + operation = new InstallOperation(new ProvisioningSession(AbstractPage.agent), new ArrayList<IInstallableUnit>()) { protected void computeProfileChangeRequest(MultiStatus status, IProgressMonitor monitor) { monitor.done(); }; public IStatus getResolutionResult() { if (sub.isCanceled()) return Status.CANCEL_STATUS; return new Status(IStatus.ERROR, Constants.Bundle_ID, Messages.ImportWizard_CannotQuerySelection); } }; } else { operation = getProfileChangeOperation(planSelections); operation.setProvisioningContext(context); } } }); if (sub.isCanceled()) throw new InterruptedException(); if (operation.resolveModal(sub.newChild(200)).getSeverity() == IStatus.CANCEL) throw new InterruptedException(); Display.getDefault().asyncExec(new Runnable() { public void run() { planChanged(); } }); } }); } catch (InterruptedException e) { operation = new InstallOperation(new ProvisioningSession(AbstractPage.agent), new ArrayList<IInstallableUnit>()) { public IStatus getResolutionResult() { return Status.CANCEL_STATUS; } }; } catch (InvocationTargetException e) { ProvUI.handleException(e.getCause(), null, StatusManager.SHOW | StatusManager.LOG); unableToResolve(null); } } else super.recomputePlan(runnableContext); } void unableToResolve(String message) { IStatus couldNotResolveStatus; if (message != null) { couldNotResolveStatus = new Status(IStatus.ERROR, Constants.Bundle_ID, message, null); } else { couldNotResolveStatus = new Status(IStatus.ERROR, Constants.Bundle_ID, ProvUIMessages.ProvisioningOperationWizard_UnexpectedFailureToResolve, null); } StatusManager.getManager().handle(couldNotResolveStatus, StatusManager.LOG); } }
true
true
public void recomputePlan(IRunnableContext runnableContext) { if (((ImportPage) mainPage).hasUnloadedRepo()) { try { runnableContext.run(true, true, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InterruptedException { final SubMonitor sub = SubMonitor.convert(monitor, 1000); ((ImportPage) mainPage).recompute(sub.newChild(800)); if (sub.isCanceled()) throw new InterruptedException(); Display.getDefault().syncExec(new Runnable() { public void run() { ProvisioningContext context = getProvisioningContext(); initializeResolutionModelElements(getOperationSelections()); if (planSelections.length == 0) { operation = new InstallOperation(new ProvisioningSession(((ImportPage) mainPage).agent), new ArrayList<IInstallableUnit>()) { protected void computeProfileChangeRequest(MultiStatus status, IProgressMonitor monitor) { monitor.done(); }; public IStatus getResolutionResult() { if (sub.isCanceled()) return Status.CANCEL_STATUS; return new Status(IStatus.ERROR, Constants.Bundle_ID, Messages.ImportWizard_CannotQuerySelection); } }; } else { operation = getProfileChangeOperation(planSelections); operation.setProvisioningContext(context); } } }); if (sub.isCanceled()) throw new InterruptedException(); if (operation.resolveModal(sub.newChild(200)).getSeverity() == IStatus.CANCEL) throw new InterruptedException(); Display.getDefault().asyncExec(new Runnable() { public void run() { planChanged(); } }); } }); } catch (InterruptedException e) { operation = new InstallOperation(new ProvisioningSession(AbstractPage.agent), new ArrayList<IInstallableUnit>()) { public IStatus getResolutionResult() { return Status.CANCEL_STATUS; } }; } catch (InvocationTargetException e) { ProvUI.handleException(e.getCause(), null, StatusManager.SHOW | StatusManager.LOG); unableToResolve(null); } } else super.recomputePlan(runnableContext); }
public void recomputePlan(IRunnableContext runnableContext) { if (((ImportPage) mainPage).hasUnloadedRepo()) { try { runnableContext.run(true, true, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InterruptedException { final SubMonitor sub = SubMonitor.convert(monitor, 1000); ((ImportPage) mainPage).recompute(sub.newChild(800)); if (sub.isCanceled()) throw new InterruptedException(); Display.getDefault().syncExec(new Runnable() { public void run() { ProvisioningContext context = getProvisioningContext(); initializeResolutionModelElements(getOperationSelections()); if (planSelections.length == 0) { operation = new InstallOperation(new ProvisioningSession(AbstractPage.agent), new ArrayList<IInstallableUnit>()) { protected void computeProfileChangeRequest(MultiStatus status, IProgressMonitor monitor) { monitor.done(); }; public IStatus getResolutionResult() { if (sub.isCanceled()) return Status.CANCEL_STATUS; return new Status(IStatus.ERROR, Constants.Bundle_ID, Messages.ImportWizard_CannotQuerySelection); } }; } else { operation = getProfileChangeOperation(planSelections); operation.setProvisioningContext(context); } } }); if (sub.isCanceled()) throw new InterruptedException(); if (operation.resolveModal(sub.newChild(200)).getSeverity() == IStatus.CANCEL) throw new InterruptedException(); Display.getDefault().asyncExec(new Runnable() { public void run() { planChanged(); } }); } }); } catch (InterruptedException e) { operation = new InstallOperation(new ProvisioningSession(AbstractPage.agent), new ArrayList<IInstallableUnit>()) { public IStatus getResolutionResult() { return Status.CANCEL_STATUS; } }; } catch (InvocationTargetException e) { ProvUI.handleException(e.getCause(), null, StatusManager.SHOW | StatusManager.LOG); unableToResolve(null); } } else super.recomputePlan(runnableContext); }
diff --git a/src/main/java/hex/gbm/DTree.java b/src/main/java/hex/gbm/DTree.java index 30c03970d..a21a49a69 100644 --- a/src/main/java/hex/gbm/DTree.java +++ b/src/main/java/hex/gbm/DTree.java @@ -1,745 +1,745 @@ package hex.gbm; import hex.ConfusionMatrix; import java.util.Arrays; import java.util.Random; import water.*; import water.api.DocGen; import water.api.Request.API; import water.fvec.Chunk; import water.fvec.Frame; import water.util.Log; /** A Decision Tree, laid over a Frame of Vecs, and built distributed. This class defines an explicit Tree structure, as a collection of {@code DTree} {@code Node}s. The Nodes are numbered with a unique {@code _nid}. Users need to maintain their own mapping from their data to a {@code _nid}, where the obvious technique is to have a Vec of {@code _nid}s (ints), one per each element of the data Vecs. Each {@code Node} has a {@code DHistogram}, describing summary data about the rows. The DHistogram requires a pass over the data to be filled in, and we expect to fill in all rows for Nodes at the same depth at the same time. i.e., a single pass over the data will fill in all leaf Nodes' DHistograms at once. @author Cliff Click */ class DTree extends Iced { final String[] _names; // Column names final int _ncols; // Active training columns final char _nbins; // Max number of bins to split over final char _nclass; // #classes, or 1 for regression trees final int _min_rows; // Fewest allowed rows in any split private Node[] _ns; // All the nodes in the tree. Node 0 is the root. int _len; // Resizable array DTree( String[] names, int ncols, char nbins, char nclass, int min_rows ) { _names = names; _ncols = ncols; _nbins=nbins; _nclass=nclass; _min_rows = min_rows; _ns = new Node[1]; } public final Node root() { return _ns[0]; } // One-time local init after wire transfer void init_tree( ) { for( int j=0; j<_len; j++ ) _ns[j]._tree = this; } // Return Node i public final Node node( int i ) { if( i >= _len ) throw new ArrayIndexOutOfBoundsException(i); return _ns[i]; } public final UndecidedNode undecided( int i ) { return (UndecidedNode)node(i); } public final DecidedNode decided( int i ) { return ( DecidedNode)node(i); } // Get a new node index, growing innards on demand private int newIdx() { if( _len == _ns.length ) _ns = Arrays.copyOf(_ns,_len<<1); return _len++; } // Return a deterministic chunk-local RNG. Can be kinda expensive. // Override this in, e.g. Random Forest algos, to get a per-chunk RNG public Random rngForChunk( int cidx ) { throw H2O.fail(); } // -------------------------------------------------------------------------- // Abstract node flavor static abstract class Node extends Iced { transient DTree _tree; // Make transient, lest we clone the whole tree final int _pid; // Parent node id, root has no parent and uses -1 final int _nid; // My node-ID, 0 is root Node( DTree tree, int pid, int nid ) { _tree = tree; _pid=pid; tree._ns[_nid=nid] = this; } Node( DTree tree, int pid ) { this(tree,pid,tree.newIdx()); } // Recursively print the decision-line from tree root to this child. StringBuilder printLine(StringBuilder sb ) { if( _pid==-1 ) return sb.append("[root]"); DecidedNode parent = _tree.decided(_pid); parent.printLine(sb).append(" to "); return parent.printChild(sb,_nid); } abstract protected StringBuilder toString2(StringBuilder sb, int depth); abstract protected AutoBuffer compress(AutoBuffer ab); abstract protected int size(); } // -------------------------------------------------------------------------- // Records a column, a bin to split at within the column, and the MSE. static class Split extends Iced { final int _col, _bin; // Column to split, bin where being split final boolean _equal; // Split is < or == ? final double _se0, _se1; // Squared error of each subsplit final long _n0, _n1; // Rows in each final split Split( int col, int bin, boolean equal, double se0, double se1, long n0, long n1 ) { _col = col; _bin = bin; _equal = equal; _n0 = n0; _n1 = n1; _se0 = se0; _se1 = se1; } public final double se() { return _se0+_se1; } // Split-at dividing point. Don't use the step*bin+bmin, due to roundoff // error we can have that point be slightly higher or lower than the bin // min/max - which would allow values outside the stated bin-range into the // split sub-bins. Always go for a value which splits the nearest two // elements. float splat(DHistogram hs[]) { DBinHistogram h = ((DBinHistogram)hs[_col]); assert _bin > 0 && _bin < h._nbins; if( _equal ) { assert h._bins[_bin]!=0 && h._mins[_bin]==h._maxs[_bin]; return h._mins[_bin]; } int x=_bin-1; while( x >= 0 && h._bins[x]==0 ) x--; int n=_bin; while( n < h._bins.length && h._bins[n]==0 ) n++; if( x < 0 ) return h._mins[n]; if( n >= h._bins.length ) return h._maxs[x]; return (h._maxs[x]+h._mins[n])/2; } // Split a DBinHistogram. Return null if there is no point in splitting // this bin further (such as there's fewer than min_row elements, or zero // error in the response column). Return an array of DBinHistograms (one // per column), which are bounded by the split bin-limits. If the column // has constant data, or was not being tracked by a prior DBinHistogram // (for being constant data from a prior split), then that column will be // null in the returned array. public DBinHistogram[] split( int splat, char nbins, int min_rows, DHistogram hs[] ) { long n = splat==0 ? _n0 : _n1; if( n < min_rows || n <= 1 ) return null; // Too few elements double se = splat==0 ? _se0 : _se1; if( se <= 1e-30 ) return null; // No point in splitting a perfect prediction // Build a next-gen split point from the splitting bin int cnt=0; // Count of possible splits DBinHistogram nhists[] = new DBinHistogram[hs.length]; // A new histogram set for( int j=0; j<hs.length; j++ ) { // For every column in the new split DHistogram h = hs[j]; // old histogram of column if( h == null ) continue; // Column was not being tracked? // min & max come from the original column data, since splitting on an // unrelated column will not change the j'th columns min/max. float min = h._min, max = h._max; // Tighter bounds on the column getting split: exactly each new // DBinHistogram's bound are the bins' min & max. if( _col==j ) { if( _equal ) { // Equality split; no change on unequals-side if( splat == 1 ) max=min = h.mins(_bin); // but know exact bounds on equals-side } else { // Less-than split if( splat == 0 ) max = h.maxs(_bin-1); // Max from next-smallest bin else min = h.mins(_bin ); // Min from this bin } } if( min == max ) continue; // This column will not split again if( min > max ) continue; // Happens for all-NA subsplits nhists[j] = new DBinHistogram(h._name,nbins,h._isInt,min,max,n); cnt++; // At least some chance of splitting } return cnt == 0 ? null : nhists; } public static StringBuilder ary2str( StringBuilder sb, int w, long xs[] ) { sb.append('['); for( long x : xs ) UndecidedNode.p(sb,x,w).append(","); return sb.append(']'); } public static StringBuilder ary2str( StringBuilder sb, int w, float xs[] ) { sb.append('['); for( float x : xs ) UndecidedNode.p(sb,x,w).append(","); return sb.append(']'); } public static StringBuilder ary2str( StringBuilder sb, int w, double xs[] ) { sb.append('['); for( double x : xs ) UndecidedNode.p(sb,(float)x,w).append(","); return sb.append(']'); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"+_col+"/"); UndecidedNode.p(sb,_bin,2); sb.append(", se0=").append(_se0); sb.append(", se1=").append(_se1); sb.append(", n0=" ).append(_n0 ); sb.append(", n1=" ).append(_n1 ); return sb.append("}").toString(); } } // -------------------------------------------------------------------------- // An UndecidedNode: Has a DHistogram which is filled in (in parallel with other // histograms) in a single pass over the data. Does not contain any // split-decision. static abstract class UndecidedNode extends Node { DHistogram _hs[]; // DHistograms per column int _scoreCols[]; // A list of columns to score; could be null for all UndecidedNode( DTree tree, int pid, DBinHistogram hs[] ) { super(tree,pid,tree.newIdx()); _hs=hs; assert hs.length==tree._ncols; _scoreCols = scoreCols(hs); } // Pick a random selection of columns to compute best score. // Can return null for 'all columns'. abstract int[] scoreCols( DHistogram[] hs ); // Make the parent of this Node use a -1 NID to prevent the split that this // node otherwise induces. Happens if we find out too-late that we have a // perfect prediction here, and we want to turn into a leaf. void do_not_split( ) { if( _pid == -1 ) return; DecidedNode dn = _tree.decided(_pid); for( int i=0; i<dn._nids.length; i++ ) if( dn._nids[i]==_nid ) { dn._nids[i] = -1; return; } throw H2O.fail(); } @Override public String toString() { final int nclass = _tree._nclass; final String colPad=" "; final int cntW=4, mmmW=4, menW=5, varW=5; final int colW=cntW+1+mmmW+1+mmmW+1+menW+1+varW; StringBuilder sb = new StringBuilder(); sb.append("Nid# ").append(_nid).append(", "); printLine(sb).append("\n"); if( _hs == null ) return sb.append("_hs==null").toString(); final int ncols = _hs.length; for( int j=0; j<ncols; j++ ) if( _hs[j] != null ) p(sb,_hs[j]._name+String.format(", %4.1f",_hs[j]._min),colW).append(colPad); sb.append('\n'); for( int j=0; j<ncols; j++ ) { if( _hs[j] == null ) continue; p(sb,"cnt" ,cntW).append('/'); p(sb,"min" ,mmmW).append('/'); p(sb,"max" ,mmmW).append('/'); p(sb,"mean",menW).append('/'); p(sb,"var" ,varW).append(colPad); } sb.append('\n'); // Max bins int nbins=0; for( int j=0; j<ncols; j++ ) if( _hs[j] != null && _hs[j].nbins() > nbins ) nbins = _hs[j].nbins(); for( int i=0; i<nbins; i++ ) { for( int j=0; j<ncols; j++ ) { DHistogram h = _hs[j]; if( h == null ) continue; if( i < h.nbins() ) { p(sb, h.bins(i),cntW).append('/'); p(sb, h.mins(i),mmmW).append('/'); p(sb, h.maxs(i),mmmW).append('/'); p(sb, h.mean(i),menW).append('/'); p(sb, h.var (i),varW).append(colPad); } else { p(sb,"",colW).append(colPad); } } sb.append('\n'); } sb.append("Nid# ").append(_nid); return sb.toString(); } static private StringBuilder p(StringBuilder sb, String s, int w) { return sb.append(Log.fixedLength(s,w)); } static private StringBuilder p(StringBuilder sb, long l, int w) { return p(sb,Long.toString(l),w); } static private StringBuilder p(StringBuilder sb, double d, int w) { String s = Double.isNaN(d) ? "NaN" : ((d==Float.MAX_VALUE || d==-Float.MAX_VALUE || d==Double.MAX_VALUE || d==-Double.MAX_VALUE) ? " -" : (d==0?" 0":Double.toString(d))); if( s.length() <= w ) return p(sb,s,w); s = String.format("% 4.2f",d); if( s.length() > w ) s = String.format("% 4.1f",d); if( s.length() > w ) s = String.format("%4.0f",d); return p(sb,s,w); } @Override public StringBuilder toString2(StringBuilder sb, int depth) { for( int d=0; d<depth; d++ ) sb.append(" "); return sb.append("Undecided\n"); } @Override protected AutoBuffer compress(AutoBuffer ab) { throw H2O.fail(); } @Override protected int size() { throw H2O.fail(); } } // -------------------------------------------------------------------------- // Internal tree nodes which split into several children over a single // column. Includes a split-decision: which child does this Row belong to? // Does not contain a histogram describing how the decision was made. static abstract class DecidedNode<UDN extends UndecidedNode> extends Node { final Split _split; // Split: col, equal/notequal/less/greater, nrows, MSE final float _splat; // Split At point: lower bin-edge of split // _equals\_nids[] \ 0 1 // ----------------+---------- // F | < >= // T | != == final int _nids[]; // Children NIDS for the split transient byte _nodeType; // Complex encoding: see the compressed struct comments transient int _size = 0; // Compressed byte size of this subtree // Make a correctly flavored Undecided abstract UDN makeUndecidedNode(DBinHistogram[] nhists ); // Pick the best column from the given histograms abstract Split bestCol( UDN udn ); DecidedNode( UDN n ) { super(n._tree,n._pid,n._nid); // Replace Undecided with this DecidedNode _nids = new int[2]; // Split into 2 subsets _split = bestCol(n); // Best split-point for this tree if( _split._col == -1 ) { // No good split? // Happens because the predictor columns cannot split the responses - // which might be because all predictor columns are now constant, or // because all responses are now constant. _splat = Float.NaN; Arrays.fill(_nids,-1); return; } _splat = _split.splat(n._hs); // Split-at value final char nclass = _tree._nclass; final char nbins = _tree._nbins; final int min_rows = _tree._min_rows; for( int b=0; b<2; b++ ) { // For all split-points // Setup for children splits DBinHistogram nhists[] = _split.split(b,nbins,min_rows,n._hs); assert nhists==null || nhists.length==_tree._ncols; _nids[b] = nhists == null ? -1 : makeUndecidedNode(nhists)._nid; } } // Bin #. public int bin( Chunk chks[], int row ) { if( chks[_split._col].isNA0(row) ) // Missing data? return 0; // NAs always to bin 0 float d = (float)chks[_split._col].at0(row); // Value to split on for this row // Note that during *scoring* (as opposed to training), we can be exposed // to data which is outside the bin limits. return _split._equal ? (d != _splat ? 0 : 1) : (d < _splat ? 0 : 1); } public int ns( Chunk chks[], int row ) { return _nids[bin(chks,row)]; } @Override public String toString() { if( _split._col == -1 ) return "Decided has col = -1"; int col = _split._col; if( _split._equal ) return _tree._names[col]+" != "+_splat+"\n"+ _tree._names[col]+" == "+_splat+"\n"; return _tree._names[col]+" < "+_splat+"\n"+ _splat+" <="+_tree._names[col]+"\n"; } StringBuilder printChild( StringBuilder sb, int nid ) { int i = _nids[0]==nid ? 0 : 1; assert _nids[i]==nid : "No child nid "+nid+"? " +Arrays.toString(_nids); sb.append("[").append(_tree._names[_split._col]); sb.append(_split._equal ? (i==0 ? " != " : " == ") : (i==0 ? " < " : " >= ")); sb.append(_splat).append("]"); return sb; } @Override public StringBuilder toString2(StringBuilder sb, int depth) { for( int i=0; i<_nids.length; i++ ) { for( int d=0; d<depth; d++ ) sb.append(" "); sb.append(_nid).append(" "); if( _split._col < 0 ) sb.append("init"); else { sb.append(_tree._names[_split._col]); sb.append(_split._equal ? (i==0 ? " != " : " == ") : (i==0 ? " < " : " >= ")); sb.append(_splat).append("\n"); } if( _nids[i] >= 0 && _nids[i] < _tree._len ) _tree.node(_nids[i]).toString2(sb,depth+1); } return sb; } // Size of this subtree; sets _nodeType also @Override public final int size(){ if( _size != 0 ) return _size; // Cached size assert _nodeType == 0:"unexpected node type: " + _nodeType; if( _split._equal ) _nodeType |= (byte)4; int res = 7; // 1B node type + flags, 2B colId, 4B float split val Node left = _tree.node(_nids[0]); int lsz = left.size(); res += lsz; if( left instanceof LeafNode ) _nodeType |= (byte)(24 << 0*2); else { int slen = lsz < 256 ? 1 : (lsz < 65535 ? 2 : 3); _nodeType |= slen; // Set the size-skip bits res += slen; } Node rite = _tree.node(_nids[1]); if( rite instanceof LeafNode ) _nodeType |= (byte)(24 << 1*2); res += rite.size(); assert (_nodeType&0x1B) != 27; assert res != 0; return (_size = res); } // Compress this tree into the AutoBuffer @Override public AutoBuffer compress(AutoBuffer ab) { int pos = ab.position(); if( _nodeType == 0 ) size(); // Sets _nodeType & _size both ab.put1(_nodeType); // Includes left-child skip-size bits assert _split._col != -1; // Not a broken root non-decision? ab.put2((short)_split._col); ab.put4f(_splat); Node left = _tree.node(_nids[0]); if( (_nodeType&3) > 0 ) { // Size bits are optional for leaves int sz = left.size(); if(sz < 256) ab.put1( sz); else if (sz < 65535) ab.put2((short)sz); else ab.put3( sz); } // now write the subtree in left.compress(ab); Node rite = _tree.node(_nids[1]); rite.compress(ab); assert _size == ab.position()-pos:"reported size = " + _size + " , real size = " + (ab.position()-pos); return ab; } } static abstract class LeafNode extends Node { double _pred; LeafNode( DTree tree, int pid ) { super(tree,pid); } LeafNode( DTree tree, int pid, int nid ) { super(tree,pid,nid); } @Override public String toString() { return "Leaf#"+_nid+" = "+_pred; } @Override public final StringBuilder toString2(StringBuilder sb, int depth) { for( int d=0; d<depth; d++ ) sb.append(" "); sb.append(_nid).append(" "); return sb.append("pred=").append(_pred).append("\n"); } } // -------------------------------------------------------------------------- public static abstract class TreeModel extends Model { static final int API_WEAVER = 1; // This file has auto-gen'd doc & json fields static public DocGen.FieldDoc[] DOC_FIELDS; // Initialized from Auto-Gen code. @API(help="Expected max trees") public final int N; @API(help="MSE rate as trees are added") public final double [] errs; @API(help="Min class - to zero-bias the CM") public final int ymin; @API(help="Actual trees built (probably < N)") public final CompressedTree [/*N*/][/*nclass*/] treeBits; // For classification models, we'll do a Confusion Matrix right in the // model (for now - really should be seperate). @API(help="Confusion Matrix computed on training dataset, cm[actual][predicted]") public final long cm[][]; public TreeModel(Key key, Key dataKey, String names[], String domains[][], int ntrees, int ymin) { super(key,dataKey,names,domains); this.N = ntrees; this.errs = new double[0]; this.ymin = ymin; this.cm = null; treeBits = new CompressedTree[0][]; } public TreeModel(TreeModel prior, DTree[] trees, double err, long [][] cm) { super(prior._selfKey,prior._dataKey,prior._names,prior._domains); this.N = prior.N; this.ymin = prior.ymin; this.cm = cm; errs = Arrays.copyOf(prior.errs,prior.errs.length+1); errs[errs.length-1] = err; assert trees.length == nclasses()-ymin : "Trees="+trees.length+" nclasses()="+nclasses()+" ymin="+ymin; treeBits = Arrays.copyOf(prior.treeBits,prior.treeBits.length+1); CompressedTree ts[] = treeBits[treeBits.length-1] = new CompressedTree[trees.length]; for( int c=0; c<trees.length; c++ ) if( trees[c] != null ) ts[c] = trees[c].compress(); } // Number of trees actually in the model (instead of expected/planned) public int numTrees() { return treeBits.length; } @Override public ConfusionMatrix cm() { return cm == null ? null : new ConfusionMatrix(cm); } @Override protected float[] score0(double data[], float preds[]) { Arrays.fill(preds,0); for( CompressedTree ts[] : treeBits ) for( int c=0; c<ts.length; c++ ) if( ts[c] != null ) preds[c+ymin] += ts[c].score(data); return preds; } public void generateHTML(String title, StringBuilder sb) { DocGen.HTML.title(sb,title); DocGen.HTML.paragraph(sb,"Model Key: "+_selfKey); DocGen.HTML.paragraph(sb,water.api.Predict.link(_selfKey,"Predict!")); String[] domain = _domains[_domains.length-1]; // Domain of response col // Top row of CM if( cm != null && nclasses() > 1 ) { assert ymin+cm.length==domain.length; DocGen.HTML.section(sb,"Confusion Matrix"); DocGen.HTML.arrayHead(sb); sb.append("<tr class='warning'>"); sb.append("<th>Actual / Predicted</th>"); // Row header for( int i=0; i<cm.length; i++ ) sb.append("<th>").append(domain[i+ymin]).append("</th>"); sb.append("<th>Error</th>"); sb.append("</tr>"); // Main CM Body long tsum=0, terr=0; // Total observations & errors for( int i=0; i<cm.length; i++ ) { // Actual loop sb.append("<tr>"); sb.append("<th>").append(domain[i+ymin]).append("</th>");// Row header long sum=0, err=0; // Per-class observations & errors for( int j=0; j<cm[i].length; j++ ) { // Predicted loop sb.append(i==j ? "<td style='background-color:LightGreen'>":"<td>"); sb.append(cm[i][j]).append("</td>"); sum += cm[i][j]; // Per-class observations if( i != j ) err += cm[i][j]; // and errors } sb.append(String.format("<th>%5.3f = %d / %d</th>", (double)err/sum, err, sum)); tsum += sum; terr += err; // Bump totals } sb.append("</tr>"); // Last row of CM sb.append("<tr>"); sb.append("<th>Totals</th>");// Row header for( int j=0; j<cm.length; j++ ) { // Predicted loop long sum=0; for( int i=0; i<cm.length; i++ ) sum += cm[i][j]; sb.append("<td>").append(sum).append("</td>"); } sb.append(String.format("<th>%5.3f = %d / %d</th>", (double)terr/tsum, terr, tsum)); sb.append("</tr>"); DocGen.HTML.arrayTail(sb); } if( errs != null ) { DocGen.HTML.section(sb,"Mean Squared Error by Tree"); DocGen.HTML.arrayHead(sb); sb.append("<tr><th>Trees</th>"); - for( int i=0; i<errs.length; i++ ) + for( int i=errs.length-1; i>=0; i-- ) sb.append("<td>").append(i).append("</td>"); sb.append("</tr>"); sb.append("<tr><th class='warning'>MSE</th>"); - for( int i=0; i<errs.length; i++ ) + for( int i=errs.length-1; i>=0; i-- ) sb.append(String.format("<td>%5.3f</td>",errs[i])); sb.append("</tr>"); DocGen.HTML.arrayTail(sb); } } // -------------------------------------------------------------------------- // Highly compressed tree encoding: // tree: 1B nodeType, 2B colId, 4B splitVal, left-tree-size, left, right // nodeType: (from lsb): // 2 bits ( 1,2) skip-tree-size-size, // 1 bit ( 4) operator flag (0 --> <, 1 --> == ), // 1 bit ( 8) left leaf flag, // 1 bit (16) left leaf type flag, (unused) // 1 bit (32) right leaf flag, // 1 bit (64) right leaf type flag (unused) // left, right: tree | prediction // prediction: 4 bytes of float public static class CompressedTree extends Iced { final byte [] _bits; final int _nclass; public CompressedTree( byte [] bits, int nclass ) { _bits = bits; _nclass = nclass; } float score( final double row[] ) { AutoBuffer ab = new AutoBuffer(_bits); while(true) { int nodeType = ab.get1(); int colId = ab.get2(); if( colId == 65535 ) return scoreLeaf(ab); float splitVal = ab.get4f(); boolean equal = ((nodeType&4)==4); // Compute the amount to skip. int lmask = nodeType & 0x1B; int rmask = (nodeType & 0x60) >> 2; int skip = 0; switch(lmask) { case 1: skip = ab.get1(); break; case 2: skip = ab.get2(); break; case 3: skip = ab.get3(); break; case 8: skip = _nclass < 256?1:2; break; // Small leaf case 24: skip = 4; break; // skip the prediction default: assert false:"illegal lmask value " + lmask+" at "+ab.position()+" in bitpile "+Arrays.toString(_bits); } if( !Double.isNaN(row[colId]) ) // NaNs always go to bin 0 if( ( equal && ((float)row[colId]) == splitVal) || (!equal && ((float)row[colId]) >= splitVal) ) { ab.position(ab.position()+skip); // Skip right subtree lmask = rmask; // And set the leaf bits into common place } if( (lmask&8)==8 ) return scoreLeaf(ab); } } private float scoreLeaf( AutoBuffer ab ) { return ab.get4f(); } } /** Abstract visitor class for serialized trees.*/ public static abstract class TreeVisitor<T extends Exception> { // Override these methods to get walker behavior. protected void pre ( int col, float fcmp, boolean equal ) throws T { } protected void mid ( int col, float fcmp, boolean equal ) throws T { } protected void post( int col, float fcmp, boolean equal ) throws T { } protected void leaf( float pred ) throws T { } long result( ) { return 0; } // Override to return simple results protected final TreeModel _tm; protected final CompressedTree _ct; private final AutoBuffer _ts; protected int _depth; public TreeVisitor( TreeModel tm, CompressedTree ct ) { _tm = tm; _ts = new AutoBuffer((_ct=ct)._bits); } // Call either the single-class leaf or the full-prediction leaf private final void leaf2( int mask ) throws T { assert (mask& 8)== 8; // Is a leaf assert (mask&16)==16; // No longer do small leaf leaf(_ts.get4f()); } public final void visit() throws T { int nodeType = _ts.get1(); int col = _ts.get2(); float fcmp = _ts.get4f(); if( col==65535 ) { leaf2(nodeType); return; } boolean equal = ((nodeType&4)==4); // Compute the amount to skip. int lmask = nodeType & 0x1B; int rmask = (nodeType & 0x60) >> 2; int skip = 0; switch(lmask) { case 1: skip = _ts.get1(); break; case 2: skip = _ts.get2(); break; case 3: skip = _ts.get3(); break; case 8: skip = _ct._nclass < 256?1:2; break; // Small leaf case 24: skip = _ct._nclass*4; break; // skip the p-distribution default: assert false:"illegal lmask value " + lmask; } pre (col,fcmp,equal); // Pre-walk _depth++; if( (lmask & 0x8)==8 ) leaf2(lmask); else visit(); mid (col,fcmp,equal); // Mid-walk if( (rmask & 0x8)==8 ) leaf2(rmask); else visit(); _depth--; post(col,fcmp,equal); } } StringBuilder toString(final String res, CompressedTree ct, final StringBuilder sb ) { new TreeVisitor<RuntimeException>(this,ct) { @Override protected void pre( int col, float fcmp, boolean equal ) { for( int i=0; i<_depth; i++ ) sb.append(" "); sb.append(_names[col]).append(equal?"==":"< ").append(fcmp).append('\n'); } @Override protected void leaf( float pred ) { for( int i=0; i<_depth; i++ ) sb.append(" "); sb.append(res).append("=").append(pred).append(";\n"); } }.visit(); return sb; } // Convert Tree model to Java @Override protected void toJavaPredictBody( final SB sb ) { String[] cnames = classNames(); sb.indent(2).p("java.util.Arrays.fill(preds,0f);\n"); for( int i=0; i < treeBits.length; i++ ) { CompressedTree cts[] = treeBits[i]; for( int c=0; c<cts.length; c++ ) { if( cts[c] == null ) continue; sb.indent(2).p("// Tree ").p(i); if( cnames != null ) sb.p(", class=").p(cnames[c+ymin]); sb.p("\n"); sb.indent(2).p("preds[").p(c+ymin+1).p("] +="); final int x=c; new TreeVisitor<RuntimeException>(this,cts[c]) { byte _bits[] = new byte[100]; float _fs[] = new float[100]; @Override protected void pre( int col, float fcmp, boolean equal ) { if( _depth > 0 ) { int b = _bits[_depth-1]; assert b > 0 : Arrays.toString(_bits)+"\n"+sb.toString(); if( b==1 ) _bits[_depth-1]=3; if( b==1 || b==2 ) sb.p('\n').indent(_depth+3).p("?"); if( b==2 ) sb.p(' ').p(_fs[_depth]); // Dump the leaf if( b==2 || b==3 ) sb.p('\n').indent(_depth+3).p(":"); } sb.p(" (data[").p(col).p("] ").p(equal?"== ":"< ").p(fcmp); assert _bits[_depth]==0; _bits[_depth]=1; } @Override protected void leaf( float pred ) { assert _bits[_depth-1] > 0 : Arrays.toString(_bits); if( _bits[_depth-1] == 1 ) { // No prior leaf; just memoize this leaf _bits[_depth-1]=2; _fs[_depth-1]=pred; } else { // Else==2 (prior leaf) or 3 (prior tree) if( _bits[_depth-1] == 2 ) sb.p(" ? ").p(_fs[_depth-1]).p(" "); else sb.p('\n').indent(_depth+3); sb.p(": ").p(pred); } } @Override protected void post( int col, float fcmp, boolean equal ) { sb.p(')'); _bits[_depth]=0; } }.visit(); sb.p(";\n"); } } } } // Build a compressed-tree struct public TreeModel.CompressedTree compress() { int sz = root().size(); if( root() instanceof LeafNode ) sz += 3; // Oops - tree-stump AutoBuffer ab = new AutoBuffer(sz); if( root() instanceof LeafNode ) // Oops - tree-stump ab.put1(0).put2((char)65535); // Flag it special so the decompress doesn't look for top-level decision root().compress(ab); // Compress whole tree assert ab.position() == sz; return new TreeModel.CompressedTree(ab.buf(),_nclass); } }
false
true
public void generateHTML(String title, StringBuilder sb) { DocGen.HTML.title(sb,title); DocGen.HTML.paragraph(sb,"Model Key: "+_selfKey); DocGen.HTML.paragraph(sb,water.api.Predict.link(_selfKey,"Predict!")); String[] domain = _domains[_domains.length-1]; // Domain of response col // Top row of CM if( cm != null && nclasses() > 1 ) { assert ymin+cm.length==domain.length; DocGen.HTML.section(sb,"Confusion Matrix"); DocGen.HTML.arrayHead(sb); sb.append("<tr class='warning'>"); sb.append("<th>Actual / Predicted</th>"); // Row header for( int i=0; i<cm.length; i++ ) sb.append("<th>").append(domain[i+ymin]).append("</th>"); sb.append("<th>Error</th>"); sb.append("</tr>"); // Main CM Body long tsum=0, terr=0; // Total observations & errors for( int i=0; i<cm.length; i++ ) { // Actual loop sb.append("<tr>"); sb.append("<th>").append(domain[i+ymin]).append("</th>");// Row header long sum=0, err=0; // Per-class observations & errors for( int j=0; j<cm[i].length; j++ ) { // Predicted loop sb.append(i==j ? "<td style='background-color:LightGreen'>":"<td>"); sb.append(cm[i][j]).append("</td>"); sum += cm[i][j]; // Per-class observations if( i != j ) err += cm[i][j]; // and errors } sb.append(String.format("<th>%5.3f = %d / %d</th>", (double)err/sum, err, sum)); tsum += sum; terr += err; // Bump totals } sb.append("</tr>"); // Last row of CM sb.append("<tr>"); sb.append("<th>Totals</th>");// Row header for( int j=0; j<cm.length; j++ ) { // Predicted loop long sum=0; for( int i=0; i<cm.length; i++ ) sum += cm[i][j]; sb.append("<td>").append(sum).append("</td>"); } sb.append(String.format("<th>%5.3f = %d / %d</th>", (double)terr/tsum, terr, tsum)); sb.append("</tr>"); DocGen.HTML.arrayTail(sb); } if( errs != null ) { DocGen.HTML.section(sb,"Mean Squared Error by Tree"); DocGen.HTML.arrayHead(sb); sb.append("<tr><th>Trees</th>"); for( int i=0; i<errs.length; i++ ) sb.append("<td>").append(i).append("</td>"); sb.append("</tr>"); sb.append("<tr><th class='warning'>MSE</th>"); for( int i=0; i<errs.length; i++ ) sb.append(String.format("<td>%5.3f</td>",errs[i])); sb.append("</tr>"); DocGen.HTML.arrayTail(sb); } }
public void generateHTML(String title, StringBuilder sb) { DocGen.HTML.title(sb,title); DocGen.HTML.paragraph(sb,"Model Key: "+_selfKey); DocGen.HTML.paragraph(sb,water.api.Predict.link(_selfKey,"Predict!")); String[] domain = _domains[_domains.length-1]; // Domain of response col // Top row of CM if( cm != null && nclasses() > 1 ) { assert ymin+cm.length==domain.length; DocGen.HTML.section(sb,"Confusion Matrix"); DocGen.HTML.arrayHead(sb); sb.append("<tr class='warning'>"); sb.append("<th>Actual / Predicted</th>"); // Row header for( int i=0; i<cm.length; i++ ) sb.append("<th>").append(domain[i+ymin]).append("</th>"); sb.append("<th>Error</th>"); sb.append("</tr>"); // Main CM Body long tsum=0, terr=0; // Total observations & errors for( int i=0; i<cm.length; i++ ) { // Actual loop sb.append("<tr>"); sb.append("<th>").append(domain[i+ymin]).append("</th>");// Row header long sum=0, err=0; // Per-class observations & errors for( int j=0; j<cm[i].length; j++ ) { // Predicted loop sb.append(i==j ? "<td style='background-color:LightGreen'>":"<td>"); sb.append(cm[i][j]).append("</td>"); sum += cm[i][j]; // Per-class observations if( i != j ) err += cm[i][j]; // and errors } sb.append(String.format("<th>%5.3f = %d / %d</th>", (double)err/sum, err, sum)); tsum += sum; terr += err; // Bump totals } sb.append("</tr>"); // Last row of CM sb.append("<tr>"); sb.append("<th>Totals</th>");// Row header for( int j=0; j<cm.length; j++ ) { // Predicted loop long sum=0; for( int i=0; i<cm.length; i++ ) sum += cm[i][j]; sb.append("<td>").append(sum).append("</td>"); } sb.append(String.format("<th>%5.3f = %d / %d</th>", (double)terr/tsum, terr, tsum)); sb.append("</tr>"); DocGen.HTML.arrayTail(sb); } if( errs != null ) { DocGen.HTML.section(sb,"Mean Squared Error by Tree"); DocGen.HTML.arrayHead(sb); sb.append("<tr><th>Trees</th>"); for( int i=errs.length-1; i>=0; i-- ) sb.append("<td>").append(i).append("</td>"); sb.append("</tr>"); sb.append("<tr><th class='warning'>MSE</th>"); for( int i=errs.length-1; i>=0; i-- ) sb.append(String.format("<td>%5.3f</td>",errs[i])); sb.append("</tr>"); DocGen.HTML.arrayTail(sb); } }
diff --git a/src/main/java/com/stripe/net/APIResource.java b/src/main/java/com/stripe/net/APIResource.java index 03d2a0b7..9b723b25 100644 --- a/src/main/java/com/stripe/net/APIResource.java +++ b/src/main/java/com/stripe/net/APIResource.java @@ -1,358 +1,358 @@ package com.stripe.net; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import javax.net.ssl.HttpsURLConnection; import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.stripe.Stripe; import com.stripe.exception.APIConnectionException; import com.stripe.exception.APIException; import com.stripe.exception.AuthenticationException; import com.stripe.exception.CardException; import com.stripe.exception.InvalidRequestException; import com.stripe.exception.StripeException; import com.stripe.model.EventData; import com.stripe.model.EventDataDeserializer; import com.stripe.model.StripeObject; public abstract class APIResource extends StripeObject { public static final Gson gson = new GsonBuilder(). setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES). registerTypeAdapter(EventData.class, new EventDataDeserializer()). create(); private static String className(Class<?> clazz) { return clazz.getSimpleName().toLowerCase().replace("$",""); } protected static String singleClassURL(Class<?> clazz) { return String.format("%s/%s", Stripe.API_BASE, className(clazz)); } protected static String classURL(Class<?> clazz) { return String.format("%ss", singleClassURL(clazz)); } protected static String instanceURL(Class<?> clazz, String id) { return String.format("%s/%s", classURL(clazz), id); } public static final String CHARSET = "UTF-8"; private static final String DNS_CACHE_TTL_PROPERTY_NAME = "networkaddress.cache.ttl"; protected enum RequestMethod { GET, POST, DELETE } private static String urlEncodePair(String k, String v) throws UnsupportedEncodingException { return String.format("%s=%s", URLEncoder.encode(k, CHARSET), URLEncoder.encode(v, CHARSET)); } static Map<String, String> getHeaders(String apiKey) { Map<String, String> headers = new HashMap<String, String>(); headers.put("Accept-Charset", CHARSET); headers.put("User-Agent", String.format("Stripe/v1 JavaBindings/%s", Stripe.VERSION)); if (apiKey == null) apiKey = Stripe.apiKey; headers.put("Authorization", String.format("Bearer %s", apiKey)); //debug headers String[] propertyNames = {"os.name", "os.version", "os.arch", "java.version", "java.vendor", "java.vm.version", "java.vm.vendor"}; Map<String, String> propertyMap = new HashMap<String, String>(); for(String propertyName: propertyNames) { propertyMap.put(propertyName, System.getProperty(propertyName)); } propertyMap.put("bindings.version", Stripe.VERSION); propertyMap.put("lang", "Java"); propertyMap.put("publisher", "Stripe"); headers.put("X-Stripe-Client-User-Agent", gson.toJson(propertyMap)); return headers; } private static HttpsURLConnection createStripeConnection(String url, String apiKey) throws IOException { URL stripeURL = new URL(url); HttpsURLConnection conn = (HttpsURLConnection) stripeURL.openConnection(); //enforce SSL URLs conn.setConnectTimeout(30000); // 30 seconds conn.setReadTimeout(80000); // 80 seconds conn.setUseCaches(false); for(Map.Entry<String, String> header: getHeaders(apiKey).entrySet()) { conn.setRequestProperty(header.getKey(), header.getValue()); } return conn; } private static HttpsURLConnection createGetConnection(String url, String query, String apiKey) throws IOException { String getURL = String.format("%s?%s", url, query); HttpsURLConnection conn = createStripeConnection(getURL, apiKey); conn.setRequestMethod("GET"); return conn; } private static HttpsURLConnection createPostConnection(String url, String query, String apiKey) throws IOException { HttpsURLConnection conn = createStripeConnection(url, apiKey); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", String.format("application/x-www-form-urlencoded;charset=%s", CHARSET)); OutputStream output = null; try { output = conn.getOutputStream(); output.write(query.getBytes(CHARSET)); } finally { if (output != null) output.close(); } return conn; } private static HttpsURLConnection createDeleteConnection(String url, String query, String apiKey) throws IOException { String deleteUrl = String.format("%s?%s", url, query); HttpsURLConnection conn = createStripeConnection(deleteUrl, apiKey); conn.setRequestMethod("DELETE"); return conn; } private static String createQuery(Map<String, Object> params) throws UnsupportedEncodingException { Map<String, String> flatParams = flattenParams(params); StringBuffer queryStringBuffer = new StringBuffer(); for(Map.Entry<String, String> entry: flatParams.entrySet()) { queryStringBuffer.append("&"); queryStringBuffer.append(urlEncodePair(entry.getKey(), entry.getValue())); } if (queryStringBuffer.length() > 0) queryStringBuffer.deleteCharAt(0); return queryStringBuffer.toString(); } private static Map<String, String> flattenParams(Map<String, Object> params) { if (params == null) { return new HashMap<String, String>(); } Map<String, String> flatParams = new HashMap<String, String>(); for(Map.Entry<String, Object> entry: params.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); if(value instanceof Map<?, ?>) { Map<String, Object> flatNestedMap = new HashMap<String, Object>(); Map<?, ?> nestedMap = (Map<?, ?>)value; for(Map.Entry<?, ?> nestedEntry: nestedMap.entrySet()) { flatNestedMap.put(String.format("%s[%s]", key, nestedEntry.getKey()), nestedEntry.getValue()); } flatParams.putAll(flattenParams(flatNestedMap)); } else if (value != null) { flatParams.put(key, value.toString()); } } return flatParams; } //represents Errors returned as JSON private static class ErrorContainer { private APIResource.Error error; } private static class Error { @SuppressWarnings("unused") String type; String message; String code; String param; } private static String getResponseBody(InputStream responseStream) throws IOException { String rBody = new Scanner(responseStream, CHARSET).useDelimiter("\\A").next(); // \A is the beginning of the stream boundary responseStream.close(); return rBody; } private static StripeResponse makeURLConnectionRequest(APIResource.RequestMethod method, String url, String query, String apiKey) throws APIConnectionException { HttpsURLConnection conn = null; try { switch(method) { case GET: conn = createGetConnection(url, query, apiKey); break; case POST: conn = createPostConnection(url, query, apiKey); break; case DELETE: conn = createDeleteConnection(url, query, apiKey); break; default: throw new APIConnectionException(String.format("Unrecognized HTTP method %s. " + "This indicates a bug in the Stripe bindings. Please contact " + "[email protected] for assistance.", method)); } int rCode = conn.getResponseCode(); //triggers the request String rBody = null; if (rCode >= 200 && rCode < 300) { rBody = getResponseBody(conn.getInputStream()); } else { rBody = getResponseBody(conn.getErrorStream()); } return new StripeResponse(rCode, rBody); } catch (IOException e) { throw new APIConnectionException(String.format("Could not connect to Stripe (%s). " + "Please check your internet connection and try again. If this problem persists," + "you should check Stripe's service status at https://twitter.com/stripestatus," + " or let us know at [email protected].", Stripe.API_BASE), e); } finally { if (conn != null) { conn.disconnect(); } } } protected static <T> T request(APIResource.RequestMethod method, String url, Map<String, Object> params, Class<T> clazz, String apiKey) throws StripeException { String originalDNSCacheTTL = null; Boolean allowedToSetTTL = true; try { originalDNSCacheTTL = java.security.Security.getProperty(DNS_CACHE_TTL_PROPERTY_NAME); // disable DNS cache java.security.Security.setProperty(DNS_CACHE_TTL_PROPERTY_NAME, "0"); } catch (SecurityException se) { allowedToSetTTL = false; } try { return _request(method, url, params, clazz, apiKey); } finally { if (allowedToSetTTL) { if (originalDNSCacheTTL == null) { // value unspecified by implementation java.security.Security.setProperty(DNS_CACHE_TTL_PROPERTY_NAME, "-1"); //cache forever } else { java.security.Security.setProperty(DNS_CACHE_TTL_PROPERTY_NAME, originalDNSCacheTTL); } } } } protected static <T> T _request(APIResource.RequestMethod method, String url, Map<String, Object> params, Class<T> clazz, String apiKey) throws StripeException { if ((Stripe.apiKey == null || Stripe.apiKey.length() == 0) && (apiKey == null || apiKey.length() == 0)) { throw new AuthenticationException("No API key provided. (HINT: set your API key using 'Stripe.apiKey = <API-KEY>'. " + "You can generate API keys from the Stripe web interface. " + "See https://stripe.com/api for details or email [email protected] if you have questions."); } if (apiKey == null) apiKey = Stripe.apiKey; String query; try { query = createQuery(params); } catch (UnsupportedEncodingException e) { throw new InvalidRequestException("Unable to encode parameters to " + CHARSET + ". Please contact [email protected] for assistance.", null, e); } StripeResponse response; try { // HTTPSURLConnection verifies SSL cert by default response = makeURLConnectionRequest(method, url, query, apiKey); } catch (ClassCastException ce) { // appengine doesn't have HTTPSConnection, use URLFetch API String appEngineEnv = System.getProperty("com.google.appengine.runtime.environment", null); if (appEngineEnv != null) { response = makeAppEngineRequest(method, url, query, apiKey); } else { // non-appengine ClassCastException throw ce; } } int rCode = response.responseCode; String rBody = response.responseBody; if (rCode < 200 || rCode >= 300) { handleAPIError(rBody, rCode); } return gson.fromJson(rBody, clazz); } private static void handleAPIError(String rBody, int rCode) throws StripeException { APIResource.Error error = gson.fromJson(rBody, APIResource.ErrorContainer.class).error; switch(rCode) { case 400: throw new InvalidRequestException(error.message, error.param, null); case 404: throw new InvalidRequestException(error.message, error.param, null); case 401: throw new AuthenticationException(error.message); case 402: throw new CardException(error.message, error.code, error.param, null); default: throw new APIException(error.message, null); } } /* * This is slower than usual because of reflection * but avoids having to maintain AppEngine-specific JAR */ private static StripeResponse makeAppEngineRequest(RequestMethod method, String url, String query, String apiKey) throws StripeException { String unknownErrorMessage = "Sorry, an unknown error occurred while trying to use the " + "Google App Engine runtime. Please contact [email protected] for assistance."; try { - if (method == RequestMethod.GET) { url = String.format("%s?%s", url, query); } + if (method == RequestMethod.GET || method == RequestMethod.DELETE) { url = String.format("%s?%s", url, query); } URL fetchURL = new URL(url); Class<?> requestMethodClass = Class.forName("com.google.appengine.api.urlfetch.HTTPMethod"); Object httpMethod = requestMethodClass.getDeclaredField(method.name()).get(null); Class<?> fetchOptionsBuilderClass = Class.forName("com.google.appengine.api.urlfetch.FetchOptions$Builder"); Object fetchOptions = null; try { fetchOptions = fetchOptionsBuilderClass.getDeclaredMethod("validateCertificate").invoke(null); } catch (NoSuchMethodException e) { System.err.println("Warning: this App Engine SDK version does not allow verification of SSL certificates;" + "this exposes you to a MITM attack. Please upgrade your App Engine SDK to >=1.5.0. " + "If you have questions, contact [email protected]."); fetchOptions = fetchOptionsBuilderClass.getDeclaredMethod("withDefaults").invoke(null); } Class<?> fetchOptionsClass = Class.forName("com.google.appengine.api.urlfetch.FetchOptions"); // GAE requests can time out after 60 seconds, so make sure we leave // some time for the application to handle a slow Stripe fetchOptionsClass.getDeclaredMethod("setDeadline", java.lang.Double.class).invoke(fetchOptions, new Double(55)); Class<?> requestClass = Class.forName("com.google.appengine.api.urlfetch.HTTPRequest"); Object request = requestClass.getDeclaredConstructor(URL.class, requestMethodClass, fetchOptionsClass) .newInstance(fetchURL, httpMethod, fetchOptions); if (method == RequestMethod.POST) { requestClass.getDeclaredMethod("setPayload", byte[].class).invoke(request, query.getBytes()); } for(Map.Entry<String, String> header: getHeaders(apiKey).entrySet()) { Class<?> httpHeaderClass = Class.forName("com.google.appengine.api.urlfetch.HTTPHeader"); Object reqHeader = httpHeaderClass.getDeclaredConstructor(String.class, String.class) .newInstance(header.getKey(), header.getValue()); requestClass.getDeclaredMethod("setHeader", httpHeaderClass).invoke(request, reqHeader); } Class<?> urlFetchFactoryClass = Class.forName("com.google.appengine.api.urlfetch.URLFetchServiceFactory"); Object urlFetchService = urlFetchFactoryClass.getDeclaredMethod("getURLFetchService").invoke(null); Method fetchMethod = urlFetchService.getClass().getDeclaredMethod("fetch", requestClass); fetchMethod.setAccessible(true); Object response = fetchMethod.invoke(urlFetchService, request); int responseCode = (Integer) response.getClass().getDeclaredMethod("getResponseCode").invoke(response); String body = new String((byte[]) response.getClass().getDeclaredMethod("getContent").invoke(response), CHARSET); return new StripeResponse(responseCode, body); } catch (InvocationTargetException e) { throw new APIException(unknownErrorMessage, e); } catch (MalformedURLException e) { throw new APIException(unknownErrorMessage, e); } catch (NoSuchFieldException e) { throw new APIException(unknownErrorMessage, e); } catch (SecurityException e) { throw new APIException(unknownErrorMessage, e); } catch (NoSuchMethodException e) { throw new APIException(unknownErrorMessage, e); } catch (ClassNotFoundException e) { throw new APIException(unknownErrorMessage, e); } catch (IllegalArgumentException e) { throw new APIException(unknownErrorMessage, e); } catch (IllegalAccessException e) { throw new APIException(unknownErrorMessage, e); } catch (InstantiationException e) { throw new APIException(unknownErrorMessage, e); } catch (UnsupportedEncodingException e) { throw new APIException(unknownErrorMessage, e); } } }
true
true
private static StripeResponse makeAppEngineRequest(RequestMethod method, String url, String query, String apiKey) throws StripeException { String unknownErrorMessage = "Sorry, an unknown error occurred while trying to use the " + "Google App Engine runtime. Please contact [email protected] for assistance."; try { if (method == RequestMethod.GET) { url = String.format("%s?%s", url, query); } URL fetchURL = new URL(url); Class<?> requestMethodClass = Class.forName("com.google.appengine.api.urlfetch.HTTPMethod"); Object httpMethod = requestMethodClass.getDeclaredField(method.name()).get(null); Class<?> fetchOptionsBuilderClass = Class.forName("com.google.appengine.api.urlfetch.FetchOptions$Builder"); Object fetchOptions = null; try { fetchOptions = fetchOptionsBuilderClass.getDeclaredMethod("validateCertificate").invoke(null); } catch (NoSuchMethodException e) { System.err.println("Warning: this App Engine SDK version does not allow verification of SSL certificates;" + "this exposes you to a MITM attack. Please upgrade your App Engine SDK to >=1.5.0. " + "If you have questions, contact [email protected]."); fetchOptions = fetchOptionsBuilderClass.getDeclaredMethod("withDefaults").invoke(null); } Class<?> fetchOptionsClass = Class.forName("com.google.appengine.api.urlfetch.FetchOptions"); // GAE requests can time out after 60 seconds, so make sure we leave // some time for the application to handle a slow Stripe fetchOptionsClass.getDeclaredMethod("setDeadline", java.lang.Double.class).invoke(fetchOptions, new Double(55)); Class<?> requestClass = Class.forName("com.google.appengine.api.urlfetch.HTTPRequest"); Object request = requestClass.getDeclaredConstructor(URL.class, requestMethodClass, fetchOptionsClass) .newInstance(fetchURL, httpMethod, fetchOptions); if (method == RequestMethod.POST) { requestClass.getDeclaredMethod("setPayload", byte[].class).invoke(request, query.getBytes()); } for(Map.Entry<String, String> header: getHeaders(apiKey).entrySet()) { Class<?> httpHeaderClass = Class.forName("com.google.appengine.api.urlfetch.HTTPHeader"); Object reqHeader = httpHeaderClass.getDeclaredConstructor(String.class, String.class) .newInstance(header.getKey(), header.getValue()); requestClass.getDeclaredMethod("setHeader", httpHeaderClass).invoke(request, reqHeader); } Class<?> urlFetchFactoryClass = Class.forName("com.google.appengine.api.urlfetch.URLFetchServiceFactory"); Object urlFetchService = urlFetchFactoryClass.getDeclaredMethod("getURLFetchService").invoke(null); Method fetchMethod = urlFetchService.getClass().getDeclaredMethod("fetch", requestClass); fetchMethod.setAccessible(true); Object response = fetchMethod.invoke(urlFetchService, request); int responseCode = (Integer) response.getClass().getDeclaredMethod("getResponseCode").invoke(response); String body = new String((byte[]) response.getClass().getDeclaredMethod("getContent").invoke(response), CHARSET); return new StripeResponse(responseCode, body); } catch (InvocationTargetException e) { throw new APIException(unknownErrorMessage, e); } catch (MalformedURLException e) { throw new APIException(unknownErrorMessage, e); } catch (NoSuchFieldException e) { throw new APIException(unknownErrorMessage, e); } catch (SecurityException e) { throw new APIException(unknownErrorMessage, e); } catch (NoSuchMethodException e) { throw new APIException(unknownErrorMessage, e); } catch (ClassNotFoundException e) { throw new APIException(unknownErrorMessage, e); } catch (IllegalArgumentException e) { throw new APIException(unknownErrorMessage, e); } catch (IllegalAccessException e) { throw new APIException(unknownErrorMessage, e); } catch (InstantiationException e) { throw new APIException(unknownErrorMessage, e); } catch (UnsupportedEncodingException e) { throw new APIException(unknownErrorMessage, e); } }
private static StripeResponse makeAppEngineRequest(RequestMethod method, String url, String query, String apiKey) throws StripeException { String unknownErrorMessage = "Sorry, an unknown error occurred while trying to use the " + "Google App Engine runtime. Please contact [email protected] for assistance."; try { if (method == RequestMethod.GET || method == RequestMethod.DELETE) { url = String.format("%s?%s", url, query); } URL fetchURL = new URL(url); Class<?> requestMethodClass = Class.forName("com.google.appengine.api.urlfetch.HTTPMethod"); Object httpMethod = requestMethodClass.getDeclaredField(method.name()).get(null); Class<?> fetchOptionsBuilderClass = Class.forName("com.google.appengine.api.urlfetch.FetchOptions$Builder"); Object fetchOptions = null; try { fetchOptions = fetchOptionsBuilderClass.getDeclaredMethod("validateCertificate").invoke(null); } catch (NoSuchMethodException e) { System.err.println("Warning: this App Engine SDK version does not allow verification of SSL certificates;" + "this exposes you to a MITM attack. Please upgrade your App Engine SDK to >=1.5.0. " + "If you have questions, contact [email protected]."); fetchOptions = fetchOptionsBuilderClass.getDeclaredMethod("withDefaults").invoke(null); } Class<?> fetchOptionsClass = Class.forName("com.google.appengine.api.urlfetch.FetchOptions"); // GAE requests can time out after 60 seconds, so make sure we leave // some time for the application to handle a slow Stripe fetchOptionsClass.getDeclaredMethod("setDeadline", java.lang.Double.class).invoke(fetchOptions, new Double(55)); Class<?> requestClass = Class.forName("com.google.appengine.api.urlfetch.HTTPRequest"); Object request = requestClass.getDeclaredConstructor(URL.class, requestMethodClass, fetchOptionsClass) .newInstance(fetchURL, httpMethod, fetchOptions); if (method == RequestMethod.POST) { requestClass.getDeclaredMethod("setPayload", byte[].class).invoke(request, query.getBytes()); } for(Map.Entry<String, String> header: getHeaders(apiKey).entrySet()) { Class<?> httpHeaderClass = Class.forName("com.google.appengine.api.urlfetch.HTTPHeader"); Object reqHeader = httpHeaderClass.getDeclaredConstructor(String.class, String.class) .newInstance(header.getKey(), header.getValue()); requestClass.getDeclaredMethod("setHeader", httpHeaderClass).invoke(request, reqHeader); } Class<?> urlFetchFactoryClass = Class.forName("com.google.appengine.api.urlfetch.URLFetchServiceFactory"); Object urlFetchService = urlFetchFactoryClass.getDeclaredMethod("getURLFetchService").invoke(null); Method fetchMethod = urlFetchService.getClass().getDeclaredMethod("fetch", requestClass); fetchMethod.setAccessible(true); Object response = fetchMethod.invoke(urlFetchService, request); int responseCode = (Integer) response.getClass().getDeclaredMethod("getResponseCode").invoke(response); String body = new String((byte[]) response.getClass().getDeclaredMethod("getContent").invoke(response), CHARSET); return new StripeResponse(responseCode, body); } catch (InvocationTargetException e) { throw new APIException(unknownErrorMessage, e); } catch (MalformedURLException e) { throw new APIException(unknownErrorMessage, e); } catch (NoSuchFieldException e) { throw new APIException(unknownErrorMessage, e); } catch (SecurityException e) { throw new APIException(unknownErrorMessage, e); } catch (NoSuchMethodException e) { throw new APIException(unknownErrorMessage, e); } catch (ClassNotFoundException e) { throw new APIException(unknownErrorMessage, e); } catch (IllegalArgumentException e) { throw new APIException(unknownErrorMessage, e); } catch (IllegalAccessException e) { throw new APIException(unknownErrorMessage, e); } catch (InstantiationException e) { throw new APIException(unknownErrorMessage, e); } catch (UnsupportedEncodingException e) { throw new APIException(unknownErrorMessage, e); } }
diff --git a/src/main/java/com/geoxp/oss/servlet/GetSecretServlet.java b/src/main/java/com/geoxp/oss/servlet/GetSecretServlet.java index 5605d1f..6de1621 100644 --- a/src/main/java/com/geoxp/oss/servlet/GetSecretServlet.java +++ b/src/main/java/com/geoxp/oss/servlet/GetSecretServlet.java @@ -1,110 +1,110 @@ package com.geoxp.oss.servlet; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.security.PublicKey; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.bouncycastle.util.encoders.Base64; import org.bouncycastle.util.encoders.Hex; import com.geoxp.oss.CryptoHelper; import com.geoxp.oss.OSS; import com.geoxp.oss.OSS.OSSToken; import com.geoxp.oss.OSSException; import com.google.inject.Singleton; @Singleton public class GetSecretServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // // Extract token // String token = req.getParameter("token"); if (null == token) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing 'token'."); } // // Decode token // byte[] tokendata = Base64.decode(token); // // Extract OSS Token // OSSToken osstoken = null; try { osstoken = OSS.checkToken(tokendata); } catch (OSSException osse) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, osse.getMessage()); return; } // // Extract secretname and RSA pub key from secret // byte[] secretname = CryptoHelper.decodeNetworkString(osstoken.getSecret(), 0); byte[] rsapubblob = CryptoHelper.decodeNetworkString(osstoken.getSecret(), secretname.length + 4); // // Retrieve secret // byte[] secret = null; try { secret = OSS.getKeyStore().getSecret(new String(secretname, "UTF-8"), new String(Hex.encode(CryptoHelper.sshKeyBlobFingerprint(osstoken.getKeyblob())))); } catch (OSSException e) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); return; } // // Unwrap secret // secret = CryptoHelper.unwrapAES(OSS.getMasterSecret(), secret); if (null == secret) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Secret integrity failed."); return; } // // Wrap secret with a temporary AES key // byte[] wrappingkey = new byte[32]; CryptoHelper.getSecureRandom().nextBytes(wrappingkey); secret = CryptoHelper.wrapAES(wrappingkey, secret); // // Seal wrapping key with provided RSA pub key // PublicKey rsapub = CryptoHelper.sshKeyBlobToPublicKey(rsapubblob); - byte[] sealedwrappingkey = CryptoHelper.encryptRSA(rsapub, secret); + byte[] sealedwrappingkey = CryptoHelper.encryptRSA(rsapub, wrappingkey); ByteArrayOutputStream baos = new ByteArrayOutputStream(); baos.write(CryptoHelper.encodeNetworkString(secret)); baos.write(CryptoHelper.encodeNetworkString(sealedwrappingkey)); resp.setStatus(HttpServletResponse.SC_OK); resp.getWriter().println(new String(Base64.encode(baos.toByteArray()), "UTF-8")); } }
true
true
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // // Extract token // String token = req.getParameter("token"); if (null == token) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing 'token'."); } // // Decode token // byte[] tokendata = Base64.decode(token); // // Extract OSS Token // OSSToken osstoken = null; try { osstoken = OSS.checkToken(tokendata); } catch (OSSException osse) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, osse.getMessage()); return; } // // Extract secretname and RSA pub key from secret // byte[] secretname = CryptoHelper.decodeNetworkString(osstoken.getSecret(), 0); byte[] rsapubblob = CryptoHelper.decodeNetworkString(osstoken.getSecret(), secretname.length + 4); // // Retrieve secret // byte[] secret = null; try { secret = OSS.getKeyStore().getSecret(new String(secretname, "UTF-8"), new String(Hex.encode(CryptoHelper.sshKeyBlobFingerprint(osstoken.getKeyblob())))); } catch (OSSException e) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); return; } // // Unwrap secret // secret = CryptoHelper.unwrapAES(OSS.getMasterSecret(), secret); if (null == secret) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Secret integrity failed."); return; } // // Wrap secret with a temporary AES key // byte[] wrappingkey = new byte[32]; CryptoHelper.getSecureRandom().nextBytes(wrappingkey); secret = CryptoHelper.wrapAES(wrappingkey, secret); // // Seal wrapping key with provided RSA pub key // PublicKey rsapub = CryptoHelper.sshKeyBlobToPublicKey(rsapubblob); byte[] sealedwrappingkey = CryptoHelper.encryptRSA(rsapub, secret); ByteArrayOutputStream baos = new ByteArrayOutputStream(); baos.write(CryptoHelper.encodeNetworkString(secret)); baos.write(CryptoHelper.encodeNetworkString(sealedwrappingkey)); resp.setStatus(HttpServletResponse.SC_OK); resp.getWriter().println(new String(Base64.encode(baos.toByteArray()), "UTF-8")); }
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // // Extract token // String token = req.getParameter("token"); if (null == token) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing 'token'."); } // // Decode token // byte[] tokendata = Base64.decode(token); // // Extract OSS Token // OSSToken osstoken = null; try { osstoken = OSS.checkToken(tokendata); } catch (OSSException osse) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, osse.getMessage()); return; } // // Extract secretname and RSA pub key from secret // byte[] secretname = CryptoHelper.decodeNetworkString(osstoken.getSecret(), 0); byte[] rsapubblob = CryptoHelper.decodeNetworkString(osstoken.getSecret(), secretname.length + 4); // // Retrieve secret // byte[] secret = null; try { secret = OSS.getKeyStore().getSecret(new String(secretname, "UTF-8"), new String(Hex.encode(CryptoHelper.sshKeyBlobFingerprint(osstoken.getKeyblob())))); } catch (OSSException e) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); return; } // // Unwrap secret // secret = CryptoHelper.unwrapAES(OSS.getMasterSecret(), secret); if (null == secret) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Secret integrity failed."); return; } // // Wrap secret with a temporary AES key // byte[] wrappingkey = new byte[32]; CryptoHelper.getSecureRandom().nextBytes(wrappingkey); secret = CryptoHelper.wrapAES(wrappingkey, secret); // // Seal wrapping key with provided RSA pub key // PublicKey rsapub = CryptoHelper.sshKeyBlobToPublicKey(rsapubblob); byte[] sealedwrappingkey = CryptoHelper.encryptRSA(rsapub, wrappingkey); ByteArrayOutputStream baos = new ByteArrayOutputStream(); baos.write(CryptoHelper.encodeNetworkString(secret)); baos.write(CryptoHelper.encodeNetworkString(sealedwrappingkey)); resp.setStatus(HttpServletResponse.SC_OK); resp.getWriter().println(new String(Base64.encode(baos.toByteArray()), "UTF-8")); }
diff --git a/src/main/java/pl/agh/enrollme/repository/TermDAO.java b/src/main/java/pl/agh/enrollme/repository/TermDAO.java index 32b0cc7..b754722 100644 --- a/src/main/java/pl/agh/enrollme/repository/TermDAO.java +++ b/src/main/java/pl/agh/enrollme/repository/TermDAO.java @@ -1,35 +1,35 @@ package pl.agh.enrollme.repository; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import pl.agh.enrollme.model.Subject; import pl.agh.enrollme.model.Term; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import java.util.List; /** * Author: Piotr Turek */ @Repository public class TermDAO extends GenericDAO<Term> implements ITermDAO { @PersistenceContext private EntityManager em; public TermDAO() { super(Term.class); } @Override @Transactional public List<Term> getTermsBySubject(Subject subject) { - final TypedQuery<Term> query = em.createQuery("Select t from Term t", - Term.class); + final TypedQuery<Term> query = em.createQuery("Select t from Term t where t.termId.subject = :subject", + Term.class).setParameter("subject", subject); return query.getResultList(); } }
true
true
public List<Term> getTermsBySubject(Subject subject) { final TypedQuery<Term> query = em.createQuery("Select t from Term t", Term.class); return query.getResultList(); }
public List<Term> getTermsBySubject(Subject subject) { final TypedQuery<Term> query = em.createQuery("Select t from Term t where t.termId.subject = :subject", Term.class).setParameter("subject", subject); return query.getResultList(); }
diff --git a/org.whole.langs.legacy.op/src/org/whole/lang/xsd/codebase/AnnotatedXmlSchemaToModelsAndMappingQuery.java b/org.whole.langs.legacy.op/src/org/whole/lang/xsd/codebase/AnnotatedXmlSchemaToModelsAndMappingQuery.java index 797246f95..7827fb0ef 100755 --- a/org.whole.langs.legacy.op/src/org/whole/lang/xsd/codebase/AnnotatedXmlSchemaToModelsAndMappingQuery.java +++ b/org.whole.langs.legacy.op/src/org/whole/lang/xsd/codebase/AnnotatedXmlSchemaToModelsAndMappingQuery.java @@ -1,3949 +1,3984 @@ package org.whole.lang.xsd.codebase; import org.whole.lang.builders.IBuilderOperation; import org.whole.lang.templates.AbstractTemplateFactory; public class AnnotatedXmlSchemaToModelsAndMappingQuery extends AbstractTemplateFactory<org.whole.lang.queries.model.Block> { public void apply(IBuilderOperation op) { org.whole.lang.queries.builders.IQueriesBuilder b0 = (org.whole.lang.queries.builders.IQueriesBuilder) op.wGetBuilder(org.whole.lang.queries.reflect.QueriesLanguageKit.URI); b0.Block_(67); b0.Filter_(); b0.StringLiteral("http://www.w3.org/2001/XMLSchema"); b0.VariableTest("XML_SCHEMA_NS_URI"); b0._Filter(); b0.Filter_(); b0.Choose_(2); b0.Filter_(); b0.FeatureStep("targetNamespace"); b0.KindTest("IMPL"); b0._Filter(); b0.StringLiteral(""); b0._Choose(); b0.VariableTest("TARGET_NS_URI"); b0._Filter(); b0.Filter_(); b0.Union_(); b0.Expressions_(0); b0._Expressions(); org.whole.lang.commons.builders.ICommonsBuilder b1 = (org.whole.lang.commons.builders.ICommonsBuilder) op.wGetBuilder(org.whole.lang.commons.reflect.CommonsLanguageKit.URI); b1.Resolver(); b0._Union(); b0.VariableTest("mappedBuiltInTypes"); b0._Filter(); b0.Filter_(); b0.Union_(); b0.Expressions_(0); b0._Expressions(); b1.Resolver(); b0._Union(); b0.VariableTest("mappedCustomDataTypes"); b0._Filter(); b0.QueryDeclaration_(); b0.Name("getUriPart"); b1.Resolver(); b1.SameStageFragment_(); org.whole.lang.workflows.builders.IWorkflowsBuilder b2 = (org.whole.lang.workflows.builders.IWorkflowsBuilder) op.wGetBuilder(org.whole.lang.workflows.reflect.WorkflowsLanguageKit.URI); b2.InvokeJavaInstanceMethod_(); b2.Text("get uri part"); b1.Resolver(); b2.Variable("self"); b1.Resolver(); b2.StringLiteral("java.lang.String"); b2.StringLiteral("replaceFirst(java.lang.String, java.lang.String)"); b2.Expressions_(2); b2.StringLiteral(":[^:]+$"); b2.StringLiteral(""); b2._Expressions(); b2._InvokeJavaInstanceMethod(); b1._SameStageFragment(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getBasePart"); b1.Resolver(); b1.SameStageFragment_(); b2.InvokeJavaInstanceMethod_(); b2.Text("get base part"); b1.Resolver(); b2.Variable("self"); b1.Resolver(); b2.StringLiteral("java.lang.String"); b2.StringLiteral("replaceFirst(java.lang.String, java.lang.String)"); b2.Expressions_(2); b2.StringLiteral(".+:"); b2.StringLiteral(""); b2._Expressions(); b2._InvokeJavaInstanceMethod(); b1._SameStageFragment(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("matchesUriInQName"); b0.Names_(1); b0.Name("uri"); b0._Names(); b0.Filter_(); b0.SelfStep(); b0.ExpressionTest_(); b0.Equals_(); b0.Singleton_(); b0.Call_(); b0.Name("getUriPart"); b1.Resolver(); b0._Call(); b0._Singleton(); b0.VariableRefStep("uri"); b0._Equals(); b0._ExpressionTest(); b0._Filter(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("isLocalQName"); b1.Resolver(); b0.Call_(); b0.Name("matchesUriInQName"); b0.Expressions_(1); b0.VariableRefStep("TARGET_NS_URI"); b0._Expressions(); b0._Call(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("isSchemaQName"); b1.Resolver(); b0.Call_(); b0.Name("matchesUriInQName"); b0.Expressions_(1); b0.VariableRefStep("XML_SCHEMA_NS_URI"); b0._Expressions(); b0._Call(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("isImportedQName"); b1.Resolver(); b0.Filter_(); b0.SelfStep(); b0.Not_(); b0.Or_(2); b0.ExpressionTest_(); b0.Call_(); b0.Name("isLocalQName"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0.ExpressionTest_(); b0.Call_(); b0.Name("isSchemaQName"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0._Or(); b0._Not(); b0._Filter(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("toType"); b0.Names_(3); b0.Name("entity"); b0.Name("type"); b0.Name("ed"); b0._Names(); b1.SameStageFragment_(); b2.Sequence_(); b2.Text("sequence"); b2.FlowObjects_(2); b2.InvokeJavaClassMethod_(); b2.Text("convert type to entity descriptor"); b2.Variable("ed"); b1.Resolver(); b2.StringLiteral("org.whole.lang.commons.parsers.CommonsDataTypePersistenceParser"); b2.StringLiteral("getEntityDescriptor(java.lang.String)"); b2.Expressions_(1); b2.Variable("type"); b2._Expressions(); b2._InvokeJavaClassMethod(); b2.InvokeJavaClassMethod_(); b2.Text("convert entity"); b1.Resolver(); b1.Resolver(); b2.StringLiteral("org.whole.lang.util.EntityUtils"); b2.StringLiteral("convert(org.whole.lang.model.IEntity, org.whole.lang.reflect.EntityDescriptor)"); b2.Expressions_(2); b2.Variable("entity"); b2.Variable("ed"); b2._Expressions(); b2._InvokeJavaClassMethod(); b2._FlowObjects(); b2._Sequence(); b1._SameStageFragment(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("addBuiltInModelDeclatration"); b0.Names_(2); b0.Name("entityType"); b0.Name("builtInType"); b0._Names(); b0.Block_(3); b0.QueryDeclaration_(); b0.Name("createBuiltInModelDeclaration"); b0.Names_(3); b0.Name("builtInComponentType"); b0.Name("componentType"); b0.Name("dataType"); b0._Names(); b0.Choose_(2); b0.Select_(); b1.StageUpFragment_(); org.whole.lang.models.builders.IModelsBuilder b3 = (org.whole.lang.models.builders.IModelsBuilder) op.wGetBuilder(org.whole.lang.models.reflect.ModelsLanguageKit.URI); b3.CompositeEntity_(); b3.EntityModifiers_(0); b3._EntityModifiers(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("entityType"); b1.Quantifier("!"); b1._Variable(); b3.Types_(0); b3._Types(); b3.ComponentModifiers_(1); b3.ComponentModifier("ordered"); b3._ComponentModifiers(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#Type"); b1.VarName("componentType"); b1.Quantifier("!"); b1._Variable(); b3._CompositeEntity(); b1._StageUpFragment(); b0.Filter_(); b0.SelfStep(); b0.ExpressionTest_(); b1.SameStageFragment_(); b2.InvokeJavaClassMethod_(); b2.Text("is list derived?"); b1.Resolver(); b1.Resolver(); b2.StringLiteral("org.whole.lang.xsd.parsers.SchemaDataTypes"); b2.StringLiteral("isListDerived(java.lang.String)"); b2.Expressions_(1); b2.Variable("builtInType"); b2._Expressions(); b2._InvokeJavaClassMethod(); b1._SameStageFragment(); b0._ExpressionTest(); b0._Filter(); b0.Sequence_(2); b0.Filter_(); b1.SameStageFragment_(); b2.Sequence_(); b2.Text("calculate component type"); b2.FlowObjects_(2); b2.InvokeJavaClassMethod_(); b2.Text("get built in component type"); b2.Variable("builtInComponentType"); b1.Resolver(); b2.StringLiteral("org.whole.lang.xsd.parsers.SchemaDataTypes"); b2.StringLiteral("getBuiltInComponentType(java.lang.String)"); b2.Expressions_(1); b2.Variable("builtInType"); b2._Expressions(); b2._InvokeJavaClassMethod(); b2.InvokeJavaClassMethod_(); b2.Text("get component type"); b1.Resolver(); b1.Resolver(); b2.StringLiteral("org.whole.lang.xsd.parsers.SchemaDataTypes"); b2.StringLiteral("getEntityNameFromBuiltIn(java.lang.String)"); b2.Expressions_(1); b2.Variable("builtInComponentType"); b2._Expressions(); b2._InvokeJavaClassMethod(); b2._FlowObjects(); b2._Sequence(); b1._SameStageFragment(); b0.VariableTest("componentType"); b0._Filter(); b0.Call_(); b0.Name("addBuiltInModelDeclatration"); b0.Expressions_(1); b0.VariableRefStep("componentType"); b0._Expressions(); b0._Call(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0.Select_(); b1.StageUpFragment_(); b3.DataEntity_(); b3.EntityModifiers_(0); b3._EntityModifiers(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("entityType"); b1.Quantifier("!"); b1._Variable(); b3.Types_(0); b3._Types(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#DataType"); b1.VarName("dataType"); b1.Quantifier("!"); b1._Variable(); b3._DataEntity(); b1._StageUpFragment(); b0.SelfStep(); b0.Filter_(); b1.SameStageFragment_(); b2.InvokeJavaClassMethod_(); b2.Text("get data type"); b1.Resolver(); b1.Resolver(); b2.StringLiteral("org.whole.lang.xsd.parsers.SchemaDataTypes"); b2.StringLiteral("getDataType(java.lang.String)"); b2.Expressions_(1); b2.Variable("builtInType"); b2._Expressions(); b2._InvokeJavaClassMethod(); b1._SameStageFragment(); b0.VariableTest("dataType"); b0._Filter(); b0.TemplateNames(); b0._Select(); b0._Choose(); b0._QueryDeclaration(); b0.If_(); b0.And_(2); b0.ExpressionTest_(); b1.SameStageFragment_(); b2.InvokeJavaClassMethod_(); b2.Text("is schema built in?"); b1.Resolver(); b1.Resolver(); b2.StringLiteral("org.whole.lang.xsd.parsers.SchemaDataTypes"); b2.StringLiteral("isBuiltInEntityName(java.lang.String)"); b2.Expressions_(1); b2.Variable("entityType"); b2._Expressions(); b2._InvokeJavaClassMethod(); b1._SameStageFragment(); b0._ExpressionTest(); b0.Not_(); b0.ExpressionTest_(); b0.Path_(3); b0.VariableRefStep("mappedBuiltInTypes"); b0.ChildStep(); b0.Filter_(); b0.FeatureStep("name"); b0.VariableTest("entityType"); b0._Filter(); b0._Path(); b0._ExpressionTest(); b0._Not(); b0._And(); b0.Block_(4); b0.Filter_(); b1.SameStageFragment_(); b2.InvokeJavaClassMethod_(); b2.Text("get built in type"); b1.Resolver(); b1.Resolver(); b2.StringLiteral("org.whole.lang.xsd.parsers.SchemaDataTypes"); b2.StringLiteral("getBuiltInFromEntityName(java.lang.String)"); b2.Expressions_(1); b2.Variable("entityType"); b2._Expressions(); b2._InvokeJavaClassMethod(); b1._SameStageFragment(); b0.VariableTest("builtInType"); b0._Filter(); b0.PointwiseInsert_(); b0.Placement("INTO"); b0.VariableRefStep("mappedBuiltInTypes"); b0.Call_(); b0.Name("createBuiltInModelDeclaration"); b1.Resolver(); b0._Call(); b0._PointwiseInsert(); b0.PointwiseInsert_(); b0.Placement("INTO"); b0.VariableRefStep("mappedCustomDataTypes"); b0.Call_(); b0.Name("getCustomDataType"); b0.Expressions_(2); b0.VariableRefStep("entityType"); b0.VariableRefStep("builtInType"); b0._Expressions(); b0._Call(); b0._PointwiseInsert(); b0.SelfStep(); b0._Block(); b0._If(); b0.SelfStep(); b0._Block(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getCustomDataType"); b0.Names_(2); b0.Name("entityType"); b0.Name("builtInType"); b0._Names(); b0.If_(); b0.ExpressionTest_(); b0.Singleton_(); b1.SameStageFragment_(); b2.InvokeJavaClassMethod_(); b2.Text("has custom data type?"); b1.Resolver(); b1.Resolver(); b2.StringLiteral("org.whole.lang.xsd.parsers.SchemaDataTypes"); b2.StringLiteral("hasCustomDataType(java.lang.String)"); b2.Expressions_(1); b2.Variable("builtInType"); b2._Expressions(); b2._InvokeJavaClassMethod(); b1._SameStageFragment(); b0._Singleton(); b0._ExpressionTest(); b1.StageUpFragment_(); org.whole.lang.xsd.mapping.builders.IMappingBuilder b4 = (org.whole.lang.xsd.mapping.builders.IMappingBuilder) op.wGetBuilder(org.whole.lang.xsd.mapping.reflect.MappingLanguageKit.URI); b4.CustomDataType_(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("entityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#BuiltInType"); b1.VarName("builtInType"); b1.Quantifier("!"); b1._Variable(); b4._CustomDataType(); b1._StageUpFragment(); b0._If(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getName"); b1.Resolver(); b0.Path_(2); b0.Choose_(3); b0.If_(); b0.Or_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#QName"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#Name"); b0._Or(); b0.SelfStep(); b0._If(); b0.If_(); b0.SubtypeTest("http://www.w3.org/2001/XMLSchema#Reference"); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#ref"); b0._If(); b0.Do_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#name"); b0._Do(); b0._Choose(); b0.Choose_(2); b0.Filter_(); b0.SelfStep(); b0.And_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#QName"); b0.Not_(); b0.ExpressionTest_(); b0.Call_(); b0.Name("isLocalQName"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0._Not(); b0._And(); b0._Filter(); b0.Call_(); b0.Name("getBasePart"); b1.Resolver(); b0._Call(); b0._Choose(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getComponent"); b0.Names_(3); b0.Name("uri"); b0.Name("components"); b0.Name("name"); b0._Names(); b0.Block_(3); b0.Path_(2); b1.SameStageFragment_(); b2.Sequence_(); b2.Text("retrive target schmea"); b2.FlowObjects_(2); b2.InvokeJavaClassMethod_(); b2.Text("get XsdRegistry instance"); b2.Variable("schemaRegistry"); b1.Resolver(); b2.StringLiteral("org.whole.lang.xsd.resources.XsdRegistry"); b2.StringLiteral("instance()"); b1.Resolver(); b2._InvokeJavaClassMethod(); b2.InvokeJavaInstanceMethod_(); b2.Text("get xml schema"); b1.Resolver(); b2.Variable("schemaRegistry"); b1.Resolver(); b2.StringLiteral("org.whole.lang.xsd.resources.XsdRegistry"); b2.StringLiteral("getSchemaFor(java.lang.String)"); b2.Expressions_(1); b1.SameStageFragment_(); b0.Call_(); b0.Name("getUriPart"); b1.Resolver(); b0._Call(); b1._SameStageFragment(); b2._Expressions(); b2._InvokeJavaInstanceMethod(); b2._FlowObjects(); b2._Sequence(); b1._SameStageFragment(); b0.Filter_(); b0.FeatureStep("components"); b0.VariableTest("components"); b0._Filter(); b0._Path(); b0.Filter_(); b0.Call_(); b0.Name("toType"); b0.Expressions_(2); b0.Call_(); b0.Name("getBasePart"); b1.Resolver(); b0._Call(); b0.Addition_(); b0.VariableRefStep("XML_SCHEMA_NS_URI"); b0.StringLiteral("#Name"); b0._Addition(); b0._Expressions(); b0._Call(); b0.VariableTest("name"); b0._Filter(); b0.Choose_(5); b0.Path_(3); b0.Filter_(); b0.ParentStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ElementRef"); b0._Filter(); b0.VariableRefStep("components"); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.ExpressionTest_(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#name"); b0.VariableTest("name"); b0._Filter(); b0._ExpressionTest(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ElementDecl"); b0._And(); b0._Filter(); b0._Path(); b0.Path_(3); b0.Filter_(); b0.ParentStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeUseRef"); b0._Filter(); b0.VariableRefStep("components"); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.ExpressionTest_(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#name"); b0.VariableTest("name"); b0._Filter(); b0._ExpressionTest(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeDecl"); b0._And(); b0._Filter(); b0._Path(); b0.Path_(3); b0.Filter_(); b0.ParentStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeGroupRef"); b0._Filter(); b0.VariableRefStep("components"); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.ExpressionTest_(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#name"); b0.VariableTest("name"); b0._Filter(); b0._ExpressionTest(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeGroupDef"); b0._And(); b0._Filter(); b0._Path(); b0.Path_(3); b0.Filter_(); b0.ParentStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ModelGroupRef"); b0._Filter(); b0.VariableRefStep("components"); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.ExpressionTest_(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#name"); b0.VariableTest("name"); b0._Filter(); b0._ExpressionTest(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ModelGroupDef"); b0._And(); b0._Filter(); b0._Path(); b0.Path_(2); b0.VariableRefStep("components"); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.ExpressionTest_(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#name"); b0.VariableTest("name"); b0._Filter(); b0._ExpressionTest(); b0.SubtypeTest("http://www.w3.org/2001/XMLSchema#TypeDef"); b0._And(); b0._Filter(); b0._Path(); b0._Choose(); b0._Block(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getSuperSimpleExtension"); b1.Resolver(); b0.Choose_(2); b0.If_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleExtension"); b0.SelfStep(); b0._If(); b0.Path_(5); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#base"); b0.KindTest("IMPL"); b0._Filter(); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#content"); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#derivation"); b0.Call_(); b0.Name("getSuperSimpleExtension"); b1.Resolver(); b0._Call(); b0._Path(); b0._Choose(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getSimpleBaseType"); b1.Resolver(); b0.Choose_(2); b0.Path_(2); b0.FeatureStep("content"); b0.Choose_(2); b0.Path_(3); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleContent"); b0._Filter(); b0.FeatureStep("derivation"); b0.FeatureStep("base"); b0._Path(); b0.FeatureStep("base"); b0._Choose(); b0._Path(); b0.Path_(3); b0.Filter_(); b0.SelfStep(); b0.And_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleRestriction"); b0.ExpressionTest_(); b0.Path_(2); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#facets"); b0.ChildStep(); b0._Path(); b0._ExpressionTest(); b0._And(); b0._Filter(); b0.Call_(); b0.Name("getSuperSimpleExtension"); b1.Resolver(); b0._Call(); b0.FeatureStep("base"); b0._Path(); b0._Choose(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getBaseType"); b1.Resolver(); b0.Block_(2); b0.QueryDeclaration_(); b0.Name("getComplexBaseType"); b1.Resolver(); b0.Path_(3); b0.Filter_(); b0.FeatureStep("content"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ComplexContent"); b0._Filter(); b0.FeatureStep("derivation"); b0.FeatureStep("base"); b0._Path(); b0._QueryDeclaration(); b0.Choose_(2); b0.Call_(); b0.Name("getComplexBaseType"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getSimpleBaseType"); b1.Resolver(); b0._Call(); b0._Choose(); b0._Block(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getExtensionBaseDataType"); b0.Names_(1); b0.Name("extension"); b0._Names(); b0.Block_(2); b0.Filter_(); b0.SelfStep(); b0.VariableTest("extension"); b0._Filter(); b0.Path_(2); b0.FeatureStep("base"); b0.Choose_(2); b0.Path_(2); b0.Call_(); b0.Name("isSchemaQName"); b1.Resolver(); b0._Call(); b0.VariableRefStep("extension"); b0._Path(); b0.Path_(3); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.FeatureStep("content"); b0.Choose_(2); b0.Path_(3); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleContent"); b0._Filter(); b0.FeatureStep("derivation"); b0.Call_(); b0.Name("getExtensionBaseDataType"); b1.Resolver(); b0._Call(); b0._Path(); b0.VariableRefStep("extension"); b0._Choose(); b0._Path(); b0._Choose(); b0._Path(); b0._Block(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getBuiltInType"); b1.Resolver(); b0.Path_(2); b0.Call_(); b0.Name("getSimpleBaseType"); b1.Resolver(); b0._Call(); b0.Choose_(2); b0.Path_(2); b0.Call_(); b0.Name("isSchemaQName"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getBasePart"); b1.Resolver(); b0._Call(); b0._Path(); b0.Path_(2); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getBuiltInType"); b1.Resolver(); b0._Call(); b0._Path(); b0._Choose(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getAppInfo"); b0.Names_(1); b0.Name("annotated"); b0._Names(); b0.Block_(2); b0.Filter_(); b0.SelfStep(); b0.VariableTest("annotated"); b0._Filter(); b0.Path_(7); b0.VariableRefStep("annotated"); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#annotation"); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#list"); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#Appinfo"); b0.ExpressionTest_(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#source"); b0.ExpressionTest_(); b1.StageUpFragment_(); org.whole.lang.xsd.builders.IXsdBuilder b5 = (org.whole.lang.xsd.builders.IXsdBuilder) op.wGetBuilder(org.whole.lang.xsd.reflect.XsdLanguageKit.URI); b5.AnyURI("http://lang.whole.org/Models"); b1._StageUpFragment(); b0._ExpressionTest(); b0._Filter(); b0._ExpressionTest(); b0._And(); b0._Filter(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#content"); b0.Filter_(); b0.ChildStep(); - b0.SubtypeTest("http://lang.whole.org/Commons#Fragment");//WAS KindTest("FRAGMENT") + b0.SubtypeTest("http://lang.whole.org/Commons#Fragment"); b0._Filter(); b0.Filter_(); b0.FeatureStep("http://lang.whole.org/Commons#rootEntity"); b0.LanguageTest("http://lang.whole.org/Models"); b0._Filter(); b0._Path(); b0._Block(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("findAppInfo"); b1.Resolver(); b0.Path_(2); b0.Choose_(4); b0.Path_(4); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ModelGroupRef"); b0._Filter(); b0.FeatureStep("ref"); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.FeatureStep("modelGroup"); b0._Path(); b0.Path_(2); b0.FeatureStep("ref"); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0._Path(); b0.Path_(2); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ModelGroupDef"); b0._Filter(); b0.FeatureStep("modelGroup"); b0._Path(); b0.SelfStep(); b0._Choose(); b0.Call_(); b0.Name("getAppInfo"); b1.Resolver(); b0._Call(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("findAppInfoFeature"); b1.Resolver(); b0.Path_(2); b0.Call_(); b0.Name("findAppInfo"); b1.Resolver(); b0._Call(); b0.FeatureStep("name"); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("findAppInfoType"); b1.Resolver(); b0.Path_(2); b0.Call_(); b0.Name("findAppInfo"); b1.Resolver(); b0._Call(); b0.Choose_(2); b0.If_(); b0.TypeTest("http://lang.whole.org/Models#Feature"); b0.FeatureStep("type"); b0._If(); b0.SelfStep(); b0._Choose(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("findImportedAppInfoType"); b0.Names_(3); b0.Name("prefix"); b0.Name("uri"); b0.Name("schemaRegistry"); b0._Names(); b0.Addition_(); b0.Singleton_(); b0.Call_(); b0.Name("getUriPart"); b1.Resolver(); b0._Call(); b0._Singleton(); b0.Addition_(); b0.StringLiteral("#"); b0.Singleton_(); b0.Path_(3); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getAppInfo"); b1.Resolver(); b0._Call(); b0.Choose_(2); b0.FeatureStep("name"); b0.SelfStep(); b0._Choose(); b0._Path(); b0._Singleton(); b0._Addition(); b0._Addition(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("addAppInfo"); b0.Names_(1); b0.Name("contents"); b0._Names(); b0.Block_(2); b0.If_(); b0.ExpressionTest_(); b0.Path_(1); b0.VariableRefStep("contents"); b0._Path(); b0._ExpressionTest(); b0.PointwiseInsert_(); b0.Placement("INTO"); b0.Path_(2); b0.Choose_(2); b0.PointwiseUpdate_(); b0.Filter_(); b0.FeatureStep("annotation"); b0.KindTest("RESOLVER"); b0._Filter(); b1.StageUpFragment_(); b5.Annotation_(); b1.Resolver(); b1.Resolver(); b1.Resolver(); b5.AnnotationList_(0); b5._AnnotationList(); b5._Annotation(); b1._StageUpFragment(); b0._PointwiseUpdate(); b0.FeatureStep("annotation"); b0._Choose(); b0.FeatureStep("list"); b0._Path(); b1.StageUpFragment_(); b5.Appinfo_(); b1.Resolver(); b1.Resolver(); b1.Resolver(); b1.Resolver(); b5.AnnotationContents_(1); b1.SameStageFragment_(); b1.Variable_(); b1.VarType("http://lang.whole.org/Commons#Any"); b1.VarName("contents"); b1.Quantifier("!"); b1._Variable(); b1._SameStageFragment(); b5._AnnotationContents(); b5._Appinfo(); b1._StageUpFragment(); b0._PointwiseInsert(); b0._If(); b0.SelfStep(); b0._Block(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("cloneMappings"); b0.Names_(6); b0.Name("targetContextType"); b0.Name("sourceRef"); b0.Name("sourceContextType"); b0.Name("clonedMapping"); b0.Name("strategyRegistry"); b0.Name("lk"); b0._Names(); b0.Choose_(2); b0.If_(); b0.ExpressionTest_(); b0.Path_(2); b0.VariableRefStep("sourceRef"); b0.Call_(); b0.Name("isLocalQName"); b1.Resolver(); b0._Call(); b0._Path(); b0._ExpressionTest(); b0.Sequence_(2); b0.Path_(3); b0.VariableRefStep("sourceRef"); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("sourceContextType"); b0._Filter(); b0._Path(); b0.For_(); b0.Path_(3); b0.VariableRefStep("mappingStrategy"); b0.FeatureStep("http://xsd.lang.whole.org/Mapping#mappings"); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.SubtypeTest("http://xsd.lang.whole.org/Mapping#ContextMapping"); b0.ExpressionTest_(); b0.Equals_(); b0.Singleton_(); b0.FeatureStep("http://xsd.lang.whole.org/Mapping#contextEntityType"); b0._Singleton(); b0.VariableRefStep("sourceContextType"); b0._Equals(); b0._ExpressionTest(); b0._And(); b0._Filter(); b0._Path(); b0.Sequence_(3); b0.Filter_(); b1.SameStageFragment_(); b2.InvokeJavaClassMethod_(); b2.Text("clone mapping"); b1.Resolver(); b1.Resolver(); b2.StringLiteral("org.whole.lang.util.EntityUtils"); b2.StringLiteral("clone(org.whole.lang.model.IEntity)"); b2.Expressions_(1); b2.Variable("self"); b2._Expressions(); b2._InvokeJavaClassMethod(); b1._SameStageFragment(); b0.VariableTest("clonedMapping"); b0._Filter(); b0.PointwiseUpdate_(); b0.Path_(2); b0.VariableRefStep("clonedMapping"); b0.FeatureStep("http://xsd.lang.whole.org/Mapping#contextEntityType"); b0._Path(); b0.VariableRefStep("targetContextType"); b0._PointwiseUpdate(); b0.PointwiseInsert_(); b0.Placement("INTO"); b0.Path_(2); b0.VariableRefStep("mappingStrategy"); b0.FeatureStep("http://xsd.lang.whole.org/Mapping#mappings"); b0._Path(); b0.VariableRefStep("clonedMapping"); b0._PointwiseInsert(); b0._Sequence(); b0._For(); b0._Sequence(); b0._If(); b0.Do_(); b1.Resolver(); b0._Do(); b0._Choose(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getType"); b1.Resolver(); b0.Choose_(2); b0.Filter_(); b0.FeatureStep("simpleType"); b0.KindTest("IMPL"); b0._Filter(); b0.Filter_(); b0.FeatureStep("type"); b0.KindTest("IMPL"); b0._Filter(); b0._Choose(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getTypeDef"); b1.Resolver(); b0.Choose_(3); b0.Path_(2); b0.Call_(); b0.Name("getType"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0._Path(); b0.Filter_(); b0.FeatureStep("simpleTypeDef"); b0.KindTest("IMPL"); b0._Filter(); b0.Filter_(); b0.FeatureStep("typeDef"); b0.KindTest("IMPL"); b0._Filter(); b0._Choose(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getParticlesContainer"); b1.Resolver(); b0.Choose_(2); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ModelGroupDef"); b0._Filter(); b0.Path_(2); b0.FeatureStep("content"); b0.Choose_(2); b0.Path_(3); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ComplexContent"); b0._Filter(); b0.FeatureStep("derivation"); b0.FeatureStep("content"); b0._Path(); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#DeclaredContent"); b0._Filter(); b0._Choose(); b0._Path(); b0._Choose(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getDescendantParticles"); b1.Resolver(); b0.Path_(1); b0.Sequence_(2); b0.SelfStep(); b0.If_(); b0.SubtypeTest("http://www.w3.org/2001/XMLSchema#ModelGroupWithParticles"); b0.Path_(3); b0.FeatureStep("particles"); b0.ChildStep(); b0.Call_(); b0.Name("getDescendantParticles"); b1.Resolver(); b0._Call(); b0._Path(); b0._If(); b0._Sequence(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getComponentParticles"); b1.Resolver(); b0.Path_(3); b0.Call_(); b0.Name("getParticlesContainer"); b1.Resolver(); b0._Call(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#modelGroup"); b0.Call_(); b0.Name("getDescendantParticles"); b1.Resolver(); b0._Call(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getComponentChildParticles"); b1.Resolver(); b0.Path_(3); b0.Call_(); b0.Name("getParticlesContainer"); b1.Resolver(); b0._Call(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#modelGroup"); b0.Call_(); b0.Name("getChildParticles"); b1.Resolver(); b0._Call(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getChildParticles"); b1.Resolver(); b0.Path_(2); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#particles"); b0.ChildStep(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getLocalParticles"); b1.Resolver(); b0.Path_(2); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#particles"); b0.Filter_(); b0.ChildStep(); b0.Not_(); b0.SubtypeTest("http://www.w3.org/2001/XMLSchema#Reference"); b0._Not(); b0._Filter(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getReferencedParticles"); b1.Resolver(); b0.Path_(2); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#particles"); b0.Filter_(); b0.ChildStep(); b0.SubtypeTest("http://www.w3.org/2001/XMLSchema#Reference"); b0._Filter(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getComponentModelGroupWithParticles"); b1.Resolver(); b0.Filter_(); b0.Call_(); b0.Name("getComponentParticles"); b1.Resolver(); b0._Call(); b0.And_(2); b0.SubtypeTest("http://www.w3.org/2001/XMLSchema#ModelGroupWithParticles"); b0.KindTest("IMPL"); b0._And(); b0._Filter(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getBaseParticles"); b1.Resolver(); b0.Sequence_(2); b0.Path_(5); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#content"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ComplexContent"); b0._Filter(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#derivation"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ComplexExtension"); b0._Filter(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#base"); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getBaseParticles"); b1.Resolver(); b0._Call(); b0._Path(); b0.Path_(2); b0.Call_(); b0.Name("getParticlesContainer"); b1.Resolver(); b0._Call(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#modelGroup"); b0.KindTest("IMPL"); b0._Filter(); b0._Path(); b0._Sequence(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getAttributesContainer"); b1.Resolver(); b0.Path_(2); b0.FeatureStep("content"); b0.Choose_(3); b0.Path_(3); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ComplexContent"); b0._Filter(); b0.FeatureStep("derivation"); b0.FeatureStep("content"); b0._Path(); b0.Path_(2); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleContent"); b0._Filter(); b0.FeatureStep("derivation"); b0._Path(); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#DeclaredContent"); b0._Filter(); b0._Choose(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getAttributesGroupChildren"); b1.Resolver(); b0.Path_(5); b0.FeatureStep("ref"); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.FeatureStep("attributeUses"); b0.ChildStep(); b0.Choose_(2); b0.Path_(2); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeGroupRef"); b0._Filter(); b0.Call_(); b0.Name("getAttributesGroupChildren"); b1.Resolver(); b0._Call(); b0._Path(); b0.Filter_(); b0.SelfStep(); b0.Not_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeGroupRef"); b0._Not(); b0._Filter(); b0._Choose(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getLocalAttributes"); b1.Resolver(); b0.Path_(3); b0.Call_(); b0.Name("getAttributesContainer"); b1.Resolver(); b0._Call(); b0.FeatureStep("attributeUses"); b0.Filter_(); b0.ChildStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeUseDecl"); b0._Filter(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getReferencedAttributes"); b1.Resolver(); b0.Path_(4); b0.Call_(); b0.Name("getAttributesContainer"); b1.Resolver(); b0._Call(); b0.FeatureStep("attributeUses"); b0.Filter_(); b0.ChildStep(); b0.Not_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeUseDecl"); b0._Not(); b0._Filter(); b0.Choose_(2); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeUseRef"); b0._Filter(); b0.Call_(); b0.Name("getAttributesGroupChildren"); b1.Resolver(); b0._Call(); b0._Choose(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getDeclaredAttributes"); b1.Resolver(); b0.Sequence_(2); b0.Call_(); b0.Name("getReferencedAttributes"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getLocalAttributes"); b1.Resolver(); b0._Call(); b0._Sequence(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getInheritedAttributes"); b0.Names_(1); b0.Name("excluded"); b0._Names(); b0.Path_(3); b0.Call_(); b0.Name("getBaseType"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getAttributes"); b0.Expressions_(1); b0.VariableRefStep("excluded"); b0._Expressions(); b0._Call(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getAttributes"); b0.Names_(2); b0.Name("excluded"); b0.Name("declared"); b0._Names(); b0.Block_(3); b0.Filter_(); b0.Union_(); b0.Expressions_(0); b0._Expressions(); b1.Resolver(); b0._Union(); b0.VariableTest("excluded"); b0._Filter(); b0.Filter_(); b0.Except_(); b0.Expressions_(2); b0.Call_(); b0.Name("getDeclaredAttributes"); b1.Resolver(); b0._Call(); b0.Path_(2); b0.VariableRefStep("excluded"); b0.ChildStep(); b0._Path(); b0._Expressions(); b0.IdentityComparator_(); b0.FeatureStep("name"); b0._IdentityComparator(); b0._Except(); b0.VariableTest("declared"); b0._Filter(); b0.Sequence_(2); b0.CartesianInsert_(); b0.Placement("INTO"); b0.VariableRefStep("excluded"); b0.Path_(2); b0.VariableRefStep("declared"); b0.ChildStep(); b0._Path(); b0._CartesianInsert(); b0.Call_(); b0.Name("getInheritedAttributes"); b0.Expressions_(1); b0.VariableRefStep("excluded"); b0._Expressions(); b0._Call(); b0._Sequence(); b0._Block(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getAttributesGroupWildcards"); b1.Resolver(); b0.Path_(3); b0.FeatureStep("ref"); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.Sequence_(2); b0.Filter_(); b0.FeatureStep("anyAttribute"); b0.KindTest("IMPL"); b0._Filter(); b0.Path_(3); b0.FeatureStep("attributeUses"); b0.Filter_(); b0.ChildStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeGroupRef"); b0._Filter(); b0.Call_(); b0.Name("getAttributesGroupWildcards"); b1.Resolver(); b0._Call(); b0._Path(); b0._Sequence(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getLocalWildcardAttribute"); b1.Resolver(); b0.Path_(2); b0.Call_(); b0.Name("getAttributesContainer"); b1.Resolver(); b0._Call(); b0.Filter_(); b0.FeatureStep("anyAttribute"); b0.KindTest("IMPL"); b0._Filter(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getDeclaredWildcardAttribute"); b1.Resolver(); b0.Path_(2); b0.Call_(); b0.Name("getAttributesContainer"); b1.Resolver(); b0._Call(); b0.Sequence_(2); b0.Filter_(); b0.FeatureStep("anyAttribute"); b0.KindTest("IMPL"); b0._Filter(); b0.Path_(3); b0.FeatureStep("attributeUses"); b0.Filter_(); b0.ChildStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeGroupRef"); b0._Filter(); b0.Call_(); b0.Name("getAttributesGroupWildcards"); b1.Resolver(); b0._Call(); b0._Path(); b0._Sequence(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getInheritedWildcardAttribute"); b1.Resolver(); b0.Path_(3); b0.Call_(); b0.Name("getBaseType"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getWildcardAttribute"); b1.Resolver(); b0._Call(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getWildcardAttribute"); b1.Resolver(); b0.Block_(2); b1.StageUpFragment_(); org.whole.lang.text.builders.ITextBuilder b6 = (org.whole.lang.text.builders.ITextBuilder) op.wGetBuilder(org.whole.lang.text.reflect.TextLanguageKit.URI); b6.Document_(2); b6.Row_(1); b6.Text("1. Implement wildcard namespaceSpecs intersection/union algorithms"); b6._Row(); b6.Row_(1); b6.Text("(currently the first anyAttribute in hierarchy is returned)"); b6._Row(); b6._Document(); b1._StageUpFragment(); b0.Filter_(); b0.Sequence_(2); b0.Call_(); b0.Name("getDeclaredWildcardAttribute"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getInheritedWildcardAttribute"); b1.Resolver(); b0._Call(); b0._Sequence(); b0.IndexTest_(); b0.IntLiteral(0); b0._IndexTest(); b0._Filter(); b0._Block(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("hasAttributes"); b1.Resolver(); b0.Filter_(); b0.Sequence_(2); b0.Call_(); b0.Name("getAttributes"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getWildcardAttribute"); b1.Resolver(); b0._Call(); b0._Sequence(); b0.IndexTest_(); b0.IntLiteral(0); b0._IndexTest(); b0._Filter(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("needsFeatureDeclarations"); b1.Resolver(); b0.Choose_(2); b0.Path_(2); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#content"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleContent"); b0._Filter(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#derivation"); b0.And_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleRestriction"); b0.Not_(); b0.ExpressionTest_(); b0.Path_(2); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#facets"); b0.ChildStep(); b0._Path(); b0._ExpressionTest(); b0._Not(); b0._And(); b0._Filter(); b0._Path(); b0.Path_(2); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#content"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ComplexContent"); b0._Filter(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#derivation"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ComplexRestriction"); b0._Filter(); b0._Path(); b0._Choose(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("isChoiceModelGroupDef"); b1.Resolver(); b0.Filter_(); b0.SelfStep(); b0.And_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ModelGroupDef"); b0.ExpressionTest_(); b0.Filter_(); b0.Call_(); b0.Name("getComponentModelGroupWithParticles"); b1.Resolver(); b0._Call(); b0.And_(2); b0.IndexTest_(); b0.IntLiteral(0); b0._IndexTest(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#Choice"); b0._And(); b0._Filter(); b0._ExpressionTest(); b0._And(); b0._Filter(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("isChoiceModelGroupRef"); b1.Resolver(); b0.Path_(3); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ModelGroupRef"); b0._Filter(); b0.FeatureStep("ref"); b0.Filter_(); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.ExpressionTest_(); b0.Call_(); b0.Name("isChoiceModelGroupDef"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0._Filter(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("hasImportedType"); b1.Resolver(); b0.Filter_(); b0.Choose_(3); b0.Path_(2); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ElementDecl"); b0._Filter(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#type"); b0._Path(); b0.Path_(2); b0.Filter_(); b0.SelfStep(); b0.SubtypeTest("http://www.w3.org/2001/XMLSchema#AttributeDecl"); b0._Filter(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#simpleType"); b0._Path(); b0.Path_(2); b0.Filter_(); b0.SelfStep(); b0.And_(2); b0.SubtypeTest("http://www.w3.org/2001/XMLSchema#Reference"); b0.Not_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeGroupRef"); b0._Not(); b0._And(); b0._Filter(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#ref"); b0._Path(); b0._Choose(); b0.And_(2); b0.KindTest("IMPL"); b0.ExpressionTest_(); b0.Call_(); b0.Name("isImportedQName"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0._And(); b0._Filter(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("allChoiceSubstitutions"); b1.Resolver(); b0.Path_(2); b0.Call_(); b0.Name("getChildParticles"); b1.Resolver(); b0._Call(); b0.Choose_(2); b0.Path_(4); b0.Filter_(); b0.SelfStep(); b0.ExpressionTest_(); b0.Call_(); b0.Name("isChoiceModelGroupRef"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0._Filter(); b0.FeatureStep("ref"); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("allChoiceModelGroupDefSubstitutions"); b1.Resolver(); b0._Call(); b0._Path(); b0.SelfStep(); b0._Choose(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("allChoiceModelGroupDefSubstitutions"); b1.Resolver(); b0.Path_(2); b0.Filter_(); b0.Call_(); b0.Name("getComponentModelGroupWithParticles"); b1.Resolver(); b0._Call(); b0.IndexTest_(); b0.IntLiteral(0); b0._IndexTest(); b0._Filter(); b0.Call_(); b0.Name("allChoiceSubstitutions"); b1.Resolver(); b0._Call(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("mapsToCompositeEntity"); b1.Resolver(); b0.Choose_(2); b0.If_(); b0.And_(3); b0.TypeTest("http://www.w3.org/2001/XMLSchema#Sequence"); b0.Not_(); b0.ExpressionTest_(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#maxOccurs"); b0.ExpressionTest_(); b1.StageUpFragment_(); b5.Bounded(1); b1._StageUpFragment(); b0._ExpressionTest(); b0._Filter(); b0._ExpressionTest(); b0._Not(); b0.Not_(); b0.ExpressionTest_(); b0.Filter_(); b0.ParentStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ModelGroupDef"); b0._Filter(); b0._ExpressionTest(); b0._Not(); b0._And(); b0.BooleanLiteral(true); b0._If(); b0.Do_(); b0.BooleanLiteral(false); b0._Do(); b0._Choose(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("mapToModelDeclaration"); b0.Names_(7); b0.Name("eType"); b0.Name("cType"); b0.Name("features"); b0.Name("fName"); b0.Name("fType"); b0.Name("fModifier"); b0.Name("attributeFeatures"); b0._Names(); b0.Choose_(7); b0.If_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ElementDecl"); b0.Block_(2); b0.Call_(); b0.Name("addBuiltInModelDeclatration"); b0.Expressions_(1); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0._Expressions(); b0._Call(); b0.Path_(2); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#typeDef"); b0.Call_(); b0.Name("mapToModelDeclaration"); b1.Resolver(); b0._Call(); b0._Path(); b0._Block(); b0._If(); b0.If_(); b0.SubtypeTest("http://www.w3.org/2001/XMLSchema#AttributeDecl"); b0.Block_(2); b0.Call_(); b0.Name("addBuiltInModelDeclatration"); b0.Expressions_(1); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0._Expressions(); b0._Call(); b0.Path_(2); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#simpleTypeDef"); b0.Call_(); b0.Name("mapToModelDeclaration"); b1.Resolver(); b0._Call(); b0._Path(); b0._Block(); b0._If(); b0.If_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ComplexTypeDef"); b0.Sequence_(2); b0.Path_(2); b0.Sequence_(3); b0.Path_(2); b0.Call_(); b0.Name("getParticlesContainer"); b1.Resolver(); b0._Call(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#modelGroup"); b0._Path(); b0.Path_(3); b0.Filter_(); b0.SelfStep(); b0.Not_(); b0.ExpressionTest_(); b0.Call_(); b0.Name("needsFeatureDeclarations"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0._Not(); b0._Filter(); b0.Call_(); b0.Name("getDeclaredAttributes"); b1.Resolver(); b0._Call(); b0.Filter_(); b0.SelfStep(); b0.Not_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeUseRef"); b0._Not(); b0._Filter(); b0._Path(); b0.Path_(2); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#content"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleContent"); b0._Filter(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#derivation"); b0.And_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleRestriction"); b0.ExpressionTest_(); b0.Path_(2); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#facets"); b0.ChildStep(); b0._Path(); b0._ExpressionTest(); b0._And(); b0._Filter(); b0._Path(); b0._Sequence(); b0.Call_(); b0.Name("mapToModelDeclaration"); b1.Resolver(); b0._Call(); b0._Path(); b0.Select_(); b1.StageUpFragment_(); b3.SimpleEntity_(); b3.EntityModifiers_(0); b3._EntityModifiers(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("eType"); b1.Quantifier("!"); b1._Variable(); b3.Types_(0); b3._Types(); b3.Features_(2); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#Feature"); b1.VarName("attributeFeatures"); b1.Quantifier("*"); b1._Variable(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#Feature"); b1.VarName("features"); b1.Quantifier("*"); b1._Variable(); b3._Features(); b3._SimpleEntity(); b1._StageUpFragment(); b0.SelfStep(); b0.Sequence_(3); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("eType"); b0._Filter(); b0.Choose_(3); b0.Select_(); b0.Filter_(); b1.StageUpFragment_(); b3.Feature_(); b3.FeatureModifiers_(0); b3._FeatureModifiers(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("fType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("fName"); b1.Quantifier("!"); b1._Variable(); b1.Resolver(); b3._Feature(); b1._StageUpFragment(); b0.VariableTest("features"); b0._Filter(); b0.Path_(2); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#content"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleContent"); b0._Filter(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#derivation"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleExtension"); b0._Filter(); b0._Path(); b0.Sequence_(3); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("fType"); b0._Filter(); b0.Call_(); b0.Name("addBuiltInModelDeclatration"); b0.Expressions_(1); b0.VariableRefStep("fType"); b0._Expressions(); b0._Call(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoFeature"); b1.Resolver(); b0._Call(); b0.VariableTest("fName"); b0._Filter(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0.Select_(); b0.Filter_(); b1.StageUpFragment_(); b3.Feature_(); b3.FeatureModifiers_(0); b3._FeatureModifiers(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("fType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("fName"); b1.Quantifier("!"); b1._Variable(); b1.Resolver(); b3._Feature(); b1._StageUpFragment(); b0.VariableTest("features"); b0._Filter(); b0.Path_(2); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#content"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleContent"); b0._Filter(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#derivation"); b0.And_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleRestriction"); b0.ExpressionTest_(); b0.Path_(2); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#facets"); b0.ChildStep(); b0._Path(); b0._ExpressionTest(); b0._And(); b0._Filter(); b0._Path(); b0.Sequence_(2); b0.Path_(2); b0.Call_(); b0.Name("findAppInfo"); b1.Resolver(); b0._Call(); b0.Filter_(); b0.FeatureStep("http://lang.whole.org/Models#name"); b0.VariableTest("fType"); b0._Filter(); b0._Path(); b0.Path_(2); b0.Call_(); b0.Name("getSuperSimpleExtension"); b1.Resolver(); b0._Call(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoFeature"); b1.Resolver(); b0._Call(); b0.VariableTest("fName"); b0._Filter(); b0._Path(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0.Select_(); b0.Filter_(); b1.StageUpFragment_(); b3.Feature_(); b3.FeatureModifiers_(1); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#FeatureModifier"); b1.VarName("fModifier"); b1.Quantifier("*"); b1._Variable(); b3._FeatureModifiers(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("fType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("fName"); b1.Quantifier("!"); b1._Variable(); b1.Resolver(); b3._Feature(); b1._StageUpFragment(); b0.VariableTest("features"); b0._Filter(); b0.Path_(1); b0.Call_(); b0.Name("getBaseParticles"); b1.Resolver(); b0._Call(); b0._Path(); b0.Sequence_(3); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("fType"); b0._Filter(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoFeature"); b1.Resolver(); b0._Call(); b0.VariableTest("fName"); b0._Filter(); b0.If_(); b0.ExpressionTest_(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#minOccurs"); b0.ExpressionTest_(); b1.StageUpFragment_(); b5.Bounded(0); b1._StageUpFragment(); b0._ExpressionTest(); b0._Filter(); b0._ExpressionTest(); b0.Filter_(); b1.StageUpFragment_(); b3.FeatureModifier("optional"); b1._StageUpFragment(); b0.VariableTest("fModifier"); b0._Filter(); b0._If(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0._Choose(); b0.Select_(); b0.Filter_(); b1.StageUpFragment_(); b3.Feature_(); b3.FeatureModifiers_(1); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#FeatureModifier"); b1.VarName("fModifier"); b1.Quantifier("*"); b1._Variable(); b3._FeatureModifiers(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("fType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("fName"); b1.Quantifier("!"); b1._Variable(); b1.Resolver(); b3._Feature(); b1._StageUpFragment(); b0.VariableTest("attributeFeatures"); b0._Filter(); b0.Path_(2); b0.Filter_(); b0.SelfStep(); b0.Not_(); b0.ExpressionTest_(); b0.Call_(); b0.Name("needsFeatureDeclarations"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0._Not(); b0._Filter(); b0.Call_(); b0.Name("getDeclaredAttributes"); b1.Resolver(); b0._Call(); b0._Path(); b0.Sequence_(2); b0.Path_(2); b0.Choose_(2); b0.Path_(3); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeUseRef"); b0._Filter(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#ref"); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0._Path(); b0.SelfStep(); b0._Choose(); b0.Sequence_(2); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("fType"); b0._Filter(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoFeature"); b1.Resolver(); b0._Call(); b0.VariableTest("fName"); b0._Filter(); b0._Sequence(); b0._Path(); b0.If_(); b0.ExpressionTest_(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#use"); b0.ExpressionTest_(); b1.StageUpFragment_(); b5.Use("optional"); b1._StageUpFragment(); b0._ExpressionTest(); b0._Filter(); b0._ExpressionTest(); b0.Filter_(); b1.StageUpFragment_(); b3.FeatureModifier("optional"); b1._StageUpFragment(); b0.VariableTest("fModifier"); b0._Filter(); b0._If(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0._Sequence(); b0._If(); b0.If_(); b0.Or_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#Sequence"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#All"); b0._Or(); b0.Sequence_(2); b0.Path_(2); b0.Call_(); b0.Name("getChildParticles"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("mapToModelDeclaration"); b1.Resolver(); b0._Call(); b0._Path(); b0.Choose_(2); b0.If_(); b0.ExpressionTest_(); b0.Singleton_(); b0.Call_(); b0.Name("mapsToCompositeEntity"); b1.Resolver(); b0._Call(); b0._Singleton(); b0._ExpressionTest(); b0.Select_(); b1.StageUpFragment_(); b3.CompositeEntity_(); b3.EntityModifiers_(0); b3._EntityModifiers(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("eType"); b1.Quantifier("!"); b1._Variable(); b3.Types_(0); b3._Types(); b3.ComponentModifiers_(1); b3.ComponentModifier("ordered"); b3._ComponentModifiers(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("cType"); b1.Quantifier("?"); b1._Variable(); b3._CompositeEntity(); b1._StageUpFragment(); b0.SelfStep(); b0.Sequence_(2); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("eType"); b0._Filter(); b0.Path_(2); b0.Call_(); b0.Name("getChildParticles"); b1.Resolver(); b0._Call(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("cType"); b0._Filter(); b0._Path(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0._If(); b0.Select_(); b1.StageUpFragment_(); b3.SimpleEntity_(); b3.EntityModifiers_(0); b3._EntityModifiers(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("eType"); b1.Quantifier("!"); b1._Variable(); b3.Types_(0); b3._Types(); b3.Features_(1); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#Feature"); b1.VarName("features"); b1.Quantifier("*"); b1._Variable(); b3._Features(); b3._SimpleEntity(); b1._StageUpFragment(); b0.SelfStep(); b0.Sequence_(2); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("eType"); b0._Filter(); b0.Select_(); b0.Filter_(); b1.StageUpFragment_(); b3.Feature_(); b3.FeatureModifiers_(1); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#FeatureModifier"); b1.VarName("fModifier"); b1.Quantifier("*"); b1._Variable(); b3._FeatureModifiers(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("fType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("fName"); b1.Quantifier("!"); b1._Variable(); b1.Resolver(); b3._Feature(); b1._StageUpFragment(); b0.VariableTest("features"); b0._Filter(); b0.Call_(); b0.Name("getChildParticles"); b1.Resolver(); b0._Call(); b0.Sequence_(3); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("fType"); b0._Filter(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoFeature"); b1.Resolver(); b0._Call(); b0.VariableTest("fName"); b0._Filter(); b0.If_(); b0.ExpressionTest_(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#minOccurs"); b0.ExpressionTest_(); b1.StageUpFragment_(); b5.Bounded(0); b1._StageUpFragment(); b0._ExpressionTest(); b0._Filter(); b0._ExpressionTest(); b0.Filter_(); b1.StageUpFragment_(); b3.FeatureModifier("optional"); b1._StageUpFragment(); b0.VariableTest("fModifier"); b0._Filter(); b0._If(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0._Choose(); b0._Sequence(); b0._If(); b0.If_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#Choice"); b0.Sequence_(2); b0.Select_(); b1.StageUpFragment_(); b3.SimpleEntity_(); b3.EntityModifiers_(1); b3.EntityModifier("abstract"); b3._EntityModifiers(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("eType"); b1.Quantifier("!"); b1._Variable(); b3.Types_(0); b3._Types(); b3.Features_(0); b3._Features(); b3._SimpleEntity(); b1._StageUpFragment(); b0.SelfStep(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("eType"); b0._Filter(); b0.TemplateNames(); b0._Select(); b0.Path_(2); b0.Call_(); b0.Name("getChildParticles"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("mapToModelDeclaration"); b1.Resolver(); b0._Call(); b0._Path(); b0._Sequence(); b0._If(); b0.If_(); b0.Or_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleTypeDef"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleRestriction"); b0._Or(); b0.Block_(2); b0.PointwiseInsert_(); b0.Placement("INTO"); b0.VariableRefStep("mappedCustomDataTypes"); b0.Call_(); b0.Name("mapToDataType"); b1.Resolver(); b0._Call(); b0._PointwiseInsert(); b0.Call_(); b0.Name("findAppInfo"); b1.Resolver(); b0._Call(); b0._Block(); b0._If(); b0.If_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ModelGroupDef"); b0.Path_(2); b0.Call_(); b0.Name("getComponentChildParticles"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("mapToModelDeclaration"); b1.Resolver(); b0._Call(); b0._Path(); b0._If(); b0._Choose(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("mapToMapping"); b0.Names_(8); b0.Name("contextStack"); b0.Name("ncname"); b0.Name("entityType"); b0.Name("newContextStack"); b0.Name("context"); b0.Name("previousContext"); b0.Name("contextEntityType"); b0.Name("featureType"); b0._Names(); b0.Choose_(12); b0.If_(); b0.And_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ElementDecl"); b0.Not_(); b0.ExpressionTest_(); b0.Path_(1); b0.VariableRefStep("contextStack"); b0._Path(); b0._ExpressionTest(); b0._Not(); b0._And(); b0.Sequence_(2); b0.Select_(); b1.StageUpFragment_(); b4.RootMapping_(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#NCName"); b1.VarName("ncname"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("entityType"); b1.Quantifier("!"); b1._Variable(); b4._RootMapping(); b1._StageUpFragment(); b0.SelfStep(); b0.Sequence_(2); b0.Filter_(); b0.FeatureStep("name"); b0.VariableTest("ncname"); b0._Filter(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("entityType"); b0._Filter(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0.Path_(2); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#typeDef"); b0.Call_(); b0.Name("mapToMapping"); b1.Resolver(); b0._Call(); b0._Path(); b0._Sequence(); b0._If(); b0.If_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ComplexTypeDef"); b0.Block_(2); b0.Filter_(); b0.Union_(); b0.Expressions_(1); b0.SelfStep(); b0._Expressions(); b1.Resolver(); b0._Union(); b0.VariableTest("newContextStack"); b0._Filter(); b0.Path_(2); b0.Sequence_(2); b0.Choose_(2); b0.Path_(1); b0.Call_(); b0.Name("getBaseParticles"); b1.Resolver(); b0._Call(); b0._Path(); b0.Path_(2); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#content"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleContent"); b0._Filter(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#derivation"); b0.Or_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleExtension"); b0.And_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleRestriction"); b0.ExpressionTest_(); b0.Path_(2); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#facets"); b0.ChildStep(); b0._Path(); b0._ExpressionTest(); b0._And(); b0._Or(); b0._Filter(); b0._Path(); b0._Choose(); b0.Path_(3); b0.Filter_(); b0.SelfStep(); b0.Not_(); b0.ExpressionTest_(); b0.Call_(); b0.Name("needsFeatureDeclarations"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0._Not(); b0._Filter(); b0.Sequence_(2); b0.Call_(); b0.Name("getInheritedAttributes"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getDeclaredAttributes"); b1.Resolver(); b0._Call(); b0._Sequence(); b0.Choose_(2); b0.Path_(3); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeUseRef"); b0._Filter(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#ref"); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0._Path(); b0.SelfStep(); b0._Choose(); b0._Path(); b0._Sequence(); b0.Call_(); b0.Name("mapToMapping"); b0.Expressions_(1); b0.VariableRefStep("newContextStack"); b0._Expressions(); b0._Call(); b0._Path(); b0._Block(); b0._If(); b0.If_(); b0.Or_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ElementRef"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ElementDecl"); b0._Or(); b0.Block_(2); b0.Filter_(); b0.Call_(); b0.Name("getName"); b1.Resolver(); b0._Call(); b0.VariableTest("ncname"); b0._Filter(); b0.Sequence_(3); b0.Select_(); b1.StageUpFragment_(); b4.StructuralMapping_(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("contextEntityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#NCName"); b1.VarName("ncname"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("entityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("featureType"); b1.Quantifier("?"); b1._Variable(); b4._StructuralMapping(); b1._StageUpFragment(); b0.Path_(2); b0.VariableRefStep("contextStack"); b0.PointwiseProduct_(2); b0.Filter_(); b0.ChildStep(); b0.VariableTest("previousContext"); b0._Filter(); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.IndexRangeTest_(); b0.IntLiteral(1); b1.Resolver(); b0._IndexRangeTest(); b0.VariableTest("context"); b0._And(); b0._Filter(); b0._PointwiseProduct(); b0._Path(); b0.Sequence_(3); b0.Path_(2); b0.VariableRefStep("context"); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("contextEntityType"); b0._Filter(); b0._Path(); b0.Path_(2); b0.VariableRefStep("previousContext"); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("entityType"); b0._Filter(); b0._Path(); b0.If_(); b0.Not_(); b0.ExpressionTest_(); b0.Singleton_(); b0.Path_(2); b0.VariableRefStep("context"); b0.Call_(); b0.Name("mapsToCompositeEntity"); b1.Resolver(); b0._Call(); b0._Path(); b0._Singleton(); b0._ExpressionTest(); b0._Not(); b0.Path_(2); b0.VariableRefStep("previousContext"); b0.Filter_(); + b0.Choose_(2); + b0.If_(); + b0.And_(2); + b0.ExpressionTest_(); + b0.Path_(2); + b0.ParentStep(); + b0.Filter_(); + b0.ParentStep(); + b0.TypeTest("http://www.w3.org/2001/XMLSchema#Choice"); + b0._Filter(); + b0._Path(); + b0._ExpressionTest(); + b0.ExpressionTest_(); + b0.Singleton_(); + b0.Path_(1); + b0.Call_(); + b0.Name("mapsToCompositeEntity"); + b1.Resolver(); + b0._Call(); + b0._Path(); + b0._Singleton(); + b0._ExpressionTest(); + b0._And(); + b0.Path_(3); + b0.ParentStep(); + b0.ParentStep(); b0.Call_(); b0.Name("findAppInfoFeature"); b1.Resolver(); b0._Call(); + b0._Path(); + b0._If(); + b0.Do_(); + b0.Call_(); + b0.Name("findAppInfoFeature"); + b1.Resolver(); + b0._Call(); + b0._Do(); + b0._Choose(); b0.VariableTest("featureType"); b0._Filter(); b0._Path(); b0._If(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0.Select_(); b1.StageUpFragment_(); b4.ElementMapping_(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("contextEntityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#NCName"); b1.VarName("ncname"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("entityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("featureType"); b1.Quantifier("?"); b1._Variable(); b4._ElementMapping(); b1._StageUpFragment(); b0.SelfStep(); b0.Sequence_(4); b0.Path_(2); b0.VariableRefStep("contextStack"); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.IndexTest_(); b0.IntLiteral(0); b0._IndexTest(); b0.VariableTest("context"); b0._And(); b0._Filter(); b0._Path(); b0.Path_(2); b0.VariableRefStep("context"); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("contextEntityType"); b0._Filter(); b0._Path(); b0.Filter_(); b0.Choose_(3); b0.Path_(2); b0.Filter_(); b0.VariableRefStep("ncname"); b0.And_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#QName"); b0.Not_(); b0.ExpressionTest_(); b0.Call_(); b0.Name("isLocalQNameù"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0._Not(); b0._And(); b0._Filter(); b0.Addition_(); b0.Singleton_(); b0.Call_(); b0.Name("getUriPart"); b1.Resolver(); b0._Call(); b0._Singleton(); b0.Addition_(); b0.StringLiteral("#"); b0.Singleton_(); b0.Path_(3); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getAppInfo"); b1.Resolver(); b0._Call(); b0.FeatureStep("type"); b0._Path(); b0._Singleton(); b0._Addition(); b0._Addition(); b0._Path(); b0.Path_(2); b0.Call_(); b0.Name("hasImportedType"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("findImportedAppInfoType"); b1.Resolver(); b0._Call(); b0._Path(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0._Choose(); b0.VariableTest("entityType"); b0._Filter(); b0.If_(); b0.Not_(); b0.ExpressionTest_(); b0.Singleton_(); b0.Path_(2); b0.VariableRefStep("context"); b0.Call_(); b0.Name("mapsToCompositeEntity"); b1.Resolver(); b0._Call(); b0._Path(); b0._Singleton(); b0._ExpressionTest(); b0._Not(); b0.Filter_(); b0.Choose_(2); b0.Call_(); b0.Name("findAppInfoFeature"); b1.Resolver(); b0._Call(); b0.Path_(3); b0.ParentStep(); b0.ParentStep(); b0.Call_(); b0.Name("findAppInfoFeature"); b1.Resolver(); b0._Call(); b0._Path(); b0._Choose(); b0.VariableTest("featureType"); b0._Filter(); b0._If(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0.Path_(2); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#typeDef"); b0.Call_(); b0.Name("mapToMapping"); b1.Resolver(); b0._Call(); b0._Path(); b0._Sequence(); b0._Block(); b0._If(); b0.If_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#Any"); b0.Sequence_(2); b0.Select_(); b1.StageUpFragment_(); b4.AnyStructuralMapping_(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("contextEntityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("entityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("featureType"); b1.Quantifier("?"); b1._Variable(); b4._AnyStructuralMapping(); b1._StageUpFragment(); b0.Path_(2); b0.VariableRefStep("contextStack"); b0.PointwiseProduct_(2); b0.Filter_(); b0.ChildStep(); b0.VariableTest("previousContext"); b0._Filter(); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.IndexRangeTest_(); b0.IntLiteral(1); b1.Resolver(); b0._IndexRangeTest(); b0.VariableTest("context"); b0._And(); b0._Filter(); b0._PointwiseProduct(); b0._Path(); b0.Sequence_(3); b0.Path_(2); b0.VariableRefStep("context"); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("contextEntityType"); b0._Filter(); b0._Path(); b0.Path_(2); b0.VariableRefStep("previousContext"); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("entityType"); b0._Filter(); b0._Path(); b0.If_(); b0.Not_(); b0.ExpressionTest_(); b0.Singleton_(); b0.Path_(2); b0.VariableRefStep("context"); b0.Call_(); b0.Name("mapsToCompositeEntity"); b1.Resolver(); b0._Call(); b0._Path(); b0._Singleton(); b0._ExpressionTest(); b0._Not(); b0.Path_(2); b0.VariableRefStep("previousContext"); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoFeature"); b1.Resolver(); b0._Call(); b0.VariableTest("featureType"); b0._Filter(); b0._Path(); b0._If(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0.Select_(); b1.StageUpFragment_(); b4.AnyElementMapping_(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("contextEntityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("entityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("featureType"); b1.Quantifier("?"); b1._Variable(); b4._AnyElementMapping(); b1._StageUpFragment(); b0.SelfStep(); b0.Sequence_(4); b0.Path_(2); b0.VariableRefStep("contextStack"); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.IndexTest_(); b0.IntLiteral(0); b0._IndexTest(); b0.VariableTest("context"); b0._And(); b0._Filter(); b0._Path(); b0.Path_(2); b0.VariableRefStep("context"); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("contextEntityType"); b0._Filter(); b0._Path(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("entityType"); b0._Filter(); b0.If_(); b0.Not_(); b0.ExpressionTest_(); b0.Singleton_(); b0.Path_(2); b0.VariableRefStep("context"); b0.Call_(); b0.Name("mapsToCompositeEntity"); b1.Resolver(); b0._Call(); b0._Path(); b0._Singleton(); b0._ExpressionTest(); b0._Not(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoFeature"); b1.Resolver(); b0._Call(); b0.VariableTest("featureType"); b0._Filter(); b0._If(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0._Sequence(); b0._If(); b0.If_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleExtension"); b0.Select_(); b1.StageUpFragment_(); b4.ContentMapping_(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("contextEntityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("entityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("featureType"); b1.Quantifier("!"); b1._Variable(); b4._ContentMapping(); b1._StageUpFragment(); b0.SelfStep(); b0.Sequence_(4); b0.Path_(2); b0.VariableRefStep("contextStack"); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.IndexTest_(); b0.IntLiteral(0); b0._IndexTest(); b0.VariableTest("context"); b0._And(); b0._Filter(); b0._Path(); b0.Path_(2); b0.VariableRefStep("context"); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("contextEntityType"); b0._Filter(); b0._Path(); b0.Path_(2); b0.Call_(); b0.Name("getExtensionBaseDataType"); b1.Resolver(); b0._Call(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("entityType"); b0._Filter(); b0._Path(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoFeature"); b1.Resolver(); b0._Call(); b0.VariableTest("featureType"); b0._Filter(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0._If(); b0.If_(); b0.And_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleRestriction"); b0.ExpressionTest_(); b0.Path_(2); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#facets"); b0.ChildStep(); b0._Path(); b0._ExpressionTest(); b0._And(); b0.Select_(); b1.StageUpFragment_(); b4.ContentMapping_(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("contextEntityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("entityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("featureType"); b1.Quantifier("!"); b1._Variable(); b4._ContentMapping(); b1._StageUpFragment(); b0.SelfStep(); b0.Sequence_(4); b0.Path_(2); b0.VariableRefStep("contextStack"); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.IndexTest_(); b0.IntLiteral(0); b0._IndexTest(); b0.VariableTest("context"); b0._And(); b0._Filter(); b0._Path(); b0.Path_(2); b0.VariableRefStep("context"); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("contextEntityType"); b0._Filter(); b0._Path(); b0.Path_(2); b0.Call_(); b0.Name("findAppInfo"); b1.Resolver(); b0._Call(); b0.Filter_(); b0.FeatureStep("http://lang.whole.org/Models#name"); b0.VariableTest("entityType"); b0._Filter(); b0._Path(); b0.Path_(2); b0.Call_(); b0.Name("getSuperSimpleExtension"); b1.Resolver(); b0._Call(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoFeature"); b1.Resolver(); b0._Call(); b0.VariableTest("featureType"); b0._Filter(); b0._Path(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0._If(); b0.If_(); b0.And_(2); b0.SubtypeTest("http://www.w3.org/2001/XMLSchema#AttributeDecl"); b0.ExpressionTest_(); b0.Path_(1); b0.VariableRefStep("contextStack"); b0._Path(); b0._ExpressionTest(); b0._And(); b0.Select_(); b1.StageUpFragment_(); b4.AttributeMapping_(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("contextEntityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#NCName"); b1.VarName("ncname"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("entityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("featureType"); b1.Quantifier("!"); b1._Variable(); b4._AttributeMapping(); b1._StageUpFragment(); b0.SelfStep(); b0.Sequence_(5); b0.Filter_(); b0.Call_(); b0.Name("getName"); b1.Resolver(); b0._Call(); b0.VariableTest("ncname"); b0._Filter(); b0.Path_(2); b0.VariableRefStep("contextStack"); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.IndexTest_(); b0.IntLiteral(0); b0._IndexTest(); b0.VariableTest("context"); b0._And(); b0._Filter(); b0._Path(); b0.Path_(2); b0.VariableRefStep("context"); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("contextEntityType"); b0._Filter(); b0._Path(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("entityType"); b0._Filter(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoFeature"); b1.Resolver(); b0._Call(); b0.VariableTest("featureType"); b0._Filter(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0._If(); b0.If_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#Sequence"); b0.Block_(2); b0.Filter_(); b0.Choose_(2); b0.If_(); b0.ExpressionTest_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0.Union_(); b0.Expressions_(2); b0.SelfStep(); b0.Path_(2); b0.VariableRefStep("contextStack"); b0.ChildStep(); b0._Path(); b0._Expressions(); b1.Resolver(); b0._Union(); b0._If(); b0.Do_(); b0.VariableRefStep("contextStack"); b0._Do(); b0._Choose(); b0.VariableTest("newContextStack"); b0._Filter(); b0.Path_(2); b0.Call_(); b0.Name("getChildParticles"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("mapToMapping"); b0.Expressions_(1); b0.VariableRefStep("newContextStack"); b0._Expressions(); b0._Call(); b0._Path(); b0._Block(); b0._If(); b0.If_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#All"); b0.Block_(2); b0.Filter_(); b0.Choose_(2); b0.If_(); b0.ExpressionTest_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0.Union_(); b0.Expressions_(2); b0.SelfStep(); b0.Path_(2); b0.VariableRefStep("contextStack"); b0.ChildStep(); b0._Path(); b0._Expressions(); b1.Resolver(); b0._Union(); b0._If(); b0.Do_(); b0.VariableRefStep("contextStack"); b0._Do(); b0._Choose(); b0.VariableTest("newContextStack"); b0._Filter(); b0.Path_(2); b0.Call_(); b0.Name("getChildParticles"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("mapToMapping"); b0.Expressions_(1); b0.VariableRefStep("newContextStack"); b0._Expressions(); b0._Call(); b0._Path(); b0._Block(); b0._If(); b0.If_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#Choice"); b0.Path_(2); b0.Call_(); b0.Name("allChoiceSubstitutions"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("mapToMapping"); b0.Expressions_(1); b0.VariableRefStep("contextStack"); b0._Expressions(); b0._Call(); b0._Path(); b0._If(); b0.If_(); b0.ExpressionTest_(); b0.Call_(); b0.Name("isChoiceModelGroupRef"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0.Path_(4); b0.FeatureStep("ref"); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("allChoiceModelGroupDefSubstitutions"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("mapToMapping"); b0.Expressions_(1); b0.VariableRefStep("contextStack"); b0._Expressions(); b0._Call(); b0._Path(); b0._If(); b0.Do_(); b0.VoidLiteral(); b0._Do(); b0._Choose(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("mapToDataType"); b0.Names_(6); b0.Name("enumerations"); b0.Name("entityType"); b0.Name("index"); b0.Name("enumValues"); b0.Name("enumValue"); b0.Name("value"); b0._Names(); b0.Block_(2); b0.QueryDeclaration_(); b0.Name("mapsToEnumEntity"); b1.Resolver(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfo"); b1.Resolver(); b0._Call(); b0.TypeTest("http://lang.whole.org/Models#EnumEntity"); b0._Filter(); b0._QueryDeclaration(); b0.Choose_(2); b0.Select_(); b1.StageUpFragment_(); b4.EnumDataType_(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("entityType"); b1.Quantifier("!"); b1._Variable(); b4.EnumValues_(1); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#EnumValue"); b1.VarName("enumValues"); b1.Quantifier("+"); b1._Variable(); b4._EnumValues(); b4._EnumDataType(); b1._StageUpFragment(); b0.Path_(2); b0.Filter_(); b0.SelfStep(); b0.And_(2); b0.ExpressionTest_(); b0.Call_(); b0.Name("mapsToEnumEntity"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0.ExpressionTest_(); b0.Path_(2); b0.Choose_(2); b0.Path_(2); b0.Filter_(); b0.SelfStep(); b0.And_(1); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleTypeDef"); b0._And(); b0._Filter(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#content"); b0._Path(); b0.Filter_(); b0.SelfStep(); b0.And_(1); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleRestriction"); b0._And(); b0._Filter(); b0._Choose(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#facets"); b0.VariableTest("enumerations"); b0._Filter(); b0._Path(); b0._ExpressionTest(); b0._And(); b0._Filter(); b0.Filter_(); b0.Call_(); b0.Name("getAppInfo"); b1.Resolver(); b0._Call(); b0.ExpressionTest_(); b0.Filter_(); b0.FeatureStep("name"); b0.VariableTest("entityType"); b0._Filter(); b0._ExpressionTest(); b0._Filter(); b0._Path(); b0.Select_(); b0.Filter_(); b1.StageUpFragment_(); b4.EnumValue_(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#Value"); b1.VarName("enumValue"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#Value"); b1.VarName("value"); b1.Quantifier("!"); b1._Variable(); b4._EnumValue(); b1._StageUpFragment(); b0.VariableTest("enumValues"); b0._Filter(); b0.Path_(2); b0.FeatureStep("values"); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.IndexVariableTest("index"); b0.VariableTest("enumValue"); b0._And(); b0._Filter(); b0._Path(); b0.Path_(3); b0.VariableRefStep("enumerations"); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#Enumeration"); b0.IndexVariableTest("index"); b0._And(); b0._Filter(); b0.Filter_(); b0.FeatureStep("value"); b0.VariableTest("value"); b0._Filter(); b0._Path(); b0.TemplateNames(); b0._Select(); b0.TemplateNames(); b0._Select(); b0.Path_(1); b0.Call_(); b0.Name("getCustomDataType"); b0.Expressions_(2); b0.Path_(2); b0.Call_(); b0.Name("findAppInfo"); b1.Resolver(); b0._Call(); b0.FeatureStep("name"); b0._Path(); b0.Call_(); b0.Name("getBuiltInType"); b1.Resolver(); b0._Call(); b0._Expressions(); b0._Call(); b0._Path(); b0._Choose(); b0._Block(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("addSubtype"); b0.Names_(2); b0.Name("subType"); b0.Name("superType"); b0._Names(); b0.PointwiseInsert_(); b0.Placement("INTO"); b0.Path_(4); b0.VariableRefStep("model"); b0.FeatureStep("http://lang.whole.org/Models#declarations"); b0.Filter_(); b0.ChildStep(); b0.ExpressionTest_(); b0.Filter_(); b0.FeatureStep("http://lang.whole.org/Models#name"); b0.VariableTest("subType"); b0._Filter(); b0._ExpressionTest(); b0._Filter(); b0.Filter_(); b0.FeatureStep("http://lang.whole.org/Models#types"); b0.Not_(); b0.ExpressionTest_(); b0.Filter_(); b0.ChildStep(); b0.VariableTest("superType"); b0._Filter(); b0._ExpressionTest(); b0._Not(); b0._Filter(); b0._Path(); b0.VariableRefStep("superType"); b0._PointwiseInsert(); b0._QueryDeclaration(); b0.Select_(); b0.Tuple_(2); b0.Filter_(); b1.StageUpFragment_(); b3.Model_(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("fileName"); b1.Quantifier("!"); b1._Variable(); b3.TypeRelations_(0); b3._TypeRelations(); b3.ModelDeclarations_(2); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#ModelDeclaration"); b1.VarName("modelDeclarations"); b1.Quantifier("*"); b1._Variable(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#ModelDeclaration"); b1.VarName("builtInModelDeclarations"); b1.Quantifier("*"); b1._Variable(); b3._ModelDeclarations(); b3.Namespace("org.whole.lang.xsi"); b1.Resolver(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#URI"); b1.VarName("languageURI"); b1.Quantifier("!"); b1._Variable(); b3._Model(); b1._StageUpFragment(); b0.VariableTest("model"); b0._Filter(); b0.Filter_(); b1.StageUpFragment_(); b4.MappingStrategy_(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("languageURI"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("fileLocationURI"); b1.Quantifier("!"); b1._Variable(); b4.BooleanType(false); b4.BooleanType(true); b4.BooleanType(false); b1.Resolver(); b1.Resolver(); b4.Mappings_(1); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#Mapping"); b1.VarName("mappings"); b1.Quantifier("*"); b1._Variable(); b4._Mappings(); b4.DataTypes_(1); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#DataType"); b1.VarName("customDataTypes"); b1.Quantifier("*"); b1._Variable(); b4._DataTypes(); b4._MappingStrategy(); b1._StageUpFragment(); b0.VariableTest("mappingStrategy"); b0._Filter(); b0._Tuple(); b0.SelfStep(); b0.Sequence_(4); b0.Filter_(); b0.Choose_(2); b0.If_(); b0.Not_(); b0.ExpressionTest_(); b0.Equals_(); b0.VariableRefStep("TARGET_NS_URI"); b0.StringLiteral(""); b0._Equals(); b0._ExpressionTest(); b0._Not(); b0.VariableRefStep("TARGET_NS_URI"); b0._If(); b0.Do_(); b1.SameStageFragment_(); b2.Sequence_(); b2.Text("sequence"); b2.FlowObjects_(1); b2.InvokeJavaClassMethod_(); b2.Text("calculate internal namespace"); b1.Resolver(); b1.Resolver(); b2.StringLiteral("org.whole.lang.xsd.util.NamespaceUtils"); b2.StringLiteral("calculateInternalNamespace(boolean)"); b1.Resolver(); b2._InvokeJavaClassMethod(); b2._FlowObjects(); b2._Sequence(); b1._SameStageFragment(); b0._Do(); b0._Choose(); b0.VariableTest("languageURI"); b0._Filter(); b0.Path_(3); b0.FeatureStep("components"); b0.ChildStep(); b0.Sequence_(2); b0.Filter_(); b0.Call_(); b0.Name("mapToMapping"); b1.Resolver(); b0._Call(); b0.VariableTest("mappings"); b0._Filter(); b0.Filter_(); b0.Call_(); b0.Name("mapToModelDeclaration"); b1.Resolver(); b0._Call(); b0.VariableTest("modelDeclarations"); b0._Filter(); b0._Sequence(); b0._Path(); b0.Path_(2); b0.VariableRefStep("mappedBuiltInTypes"); b0.Filter_(); b0.ChildStep(); b0.VariableTest("builtInModelDeclarations"); b0._Filter(); b0._Path(); b0.Path_(2); b0.VariableRefStep("mappedCustomDataTypes"); b0.Filter_(); b0.ChildStep(); b0.VariableTest("customDataTypes"); b0._Filter(); b0._Path(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0.Path_(2); b0.Filter_(); b0.DescendantStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#Choice"); b0._Filter(); b0.Block_(2); b0.Filter_(); b0.Choose_(2); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.Path_(2); b0.ParentStep(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0._Path(); b0._Choose(); b0.VariableTest("sType"); b0._Filter(); b0.Path_(3); b0.Call_(); b0.Name("getChildParticles"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("addSubtype"); b0.Expressions_(2); b0.SelfStep(); b0.VariableRefStep("sType"); b0._Expressions(); b0._Call(); b0._Path(); b0._Block(); b0._Path(); b0.Path_(2); b0.Filter_(); b0.DescendantStep(); b0.Or_(2); b0.SubtypeTest("http://www.w3.org/2001/XMLSchema#ComplexDerivation"); b0.And_(3); b0.SubtypeTest("http://www.w3.org/2001/XMLSchema#SimpleDerivation"); b0.ExpressionTest_(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#base"); b0.Not_(); b0.ExpressionTest_(); b0.Call_(); b0.Name("isSchemaQName"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0._Not(); b0._Filter(); b0._ExpressionTest(); b0.Not_(); b0.ExpressionTest_(); b0.Path_(3); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#base"); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfo"); b1.Resolver(); b0._Call(); b0.Or_(2); b0.TypeTest("http://lang.whole.org/Models#DataEntity"); b0.TypeTest("http://lang.whole.org/Models#EnumEntity"); b0._Or(); b0._Filter(); b0._Path(); b0._ExpressionTest(); b0._Not(); b0._And(); b0._Or(); b0._Filter(); b0.Call_(); b0.Name("addSubtype"); b0.Expressions_(2); b0.Path_(3); b0.ParentStep(); b0.ParentStep(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0._Path(); b0.Path_(3); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#base"); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0._Path(); b0._Expressions(); b0._Call(); b0._Path(); b0.Path_(2); b0.Filter_(); b0.DescendantStep(); b0.And_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleRestriction"); b0.Not_(); b0.ExpressionTest_(); b0.Path_(2); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#facets"); b0.ChildStep(); b0._Path(); b0._ExpressionTest(); b0._Not(); b0._And(); b0._Filter(); b0.Call_(); b0.Name("cloneMappings"); b0.Expressions_(2); b0.Path_(3); b0.ParentStep(); b0.ParentStep(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0._Path(); b0.Path_(1); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#base"); b0._Path(); b0._Expressions(); b0._Call(); b0._Path(); b0.Tuple_(2); b0.VariableRefStep("model"); b0.VariableRefStep("mappingStrategy"); b0._Tuple(); b0._Block(); } }
false
true
public void apply(IBuilderOperation op) { org.whole.lang.queries.builders.IQueriesBuilder b0 = (org.whole.lang.queries.builders.IQueriesBuilder) op.wGetBuilder(org.whole.lang.queries.reflect.QueriesLanguageKit.URI); b0.Block_(67); b0.Filter_(); b0.StringLiteral("http://www.w3.org/2001/XMLSchema"); b0.VariableTest("XML_SCHEMA_NS_URI"); b0._Filter(); b0.Filter_(); b0.Choose_(2); b0.Filter_(); b0.FeatureStep("targetNamespace"); b0.KindTest("IMPL"); b0._Filter(); b0.StringLiteral(""); b0._Choose(); b0.VariableTest("TARGET_NS_URI"); b0._Filter(); b0.Filter_(); b0.Union_(); b0.Expressions_(0); b0._Expressions(); org.whole.lang.commons.builders.ICommonsBuilder b1 = (org.whole.lang.commons.builders.ICommonsBuilder) op.wGetBuilder(org.whole.lang.commons.reflect.CommonsLanguageKit.URI); b1.Resolver(); b0._Union(); b0.VariableTest("mappedBuiltInTypes"); b0._Filter(); b0.Filter_(); b0.Union_(); b0.Expressions_(0); b0._Expressions(); b1.Resolver(); b0._Union(); b0.VariableTest("mappedCustomDataTypes"); b0._Filter(); b0.QueryDeclaration_(); b0.Name("getUriPart"); b1.Resolver(); b1.SameStageFragment_(); org.whole.lang.workflows.builders.IWorkflowsBuilder b2 = (org.whole.lang.workflows.builders.IWorkflowsBuilder) op.wGetBuilder(org.whole.lang.workflows.reflect.WorkflowsLanguageKit.URI); b2.InvokeJavaInstanceMethod_(); b2.Text("get uri part"); b1.Resolver(); b2.Variable("self"); b1.Resolver(); b2.StringLiteral("java.lang.String"); b2.StringLiteral("replaceFirst(java.lang.String, java.lang.String)"); b2.Expressions_(2); b2.StringLiteral(":[^:]+$"); b2.StringLiteral(""); b2._Expressions(); b2._InvokeJavaInstanceMethod(); b1._SameStageFragment(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getBasePart"); b1.Resolver(); b1.SameStageFragment_(); b2.InvokeJavaInstanceMethod_(); b2.Text("get base part"); b1.Resolver(); b2.Variable("self"); b1.Resolver(); b2.StringLiteral("java.lang.String"); b2.StringLiteral("replaceFirst(java.lang.String, java.lang.String)"); b2.Expressions_(2); b2.StringLiteral(".+:"); b2.StringLiteral(""); b2._Expressions(); b2._InvokeJavaInstanceMethod(); b1._SameStageFragment(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("matchesUriInQName"); b0.Names_(1); b0.Name("uri"); b0._Names(); b0.Filter_(); b0.SelfStep(); b0.ExpressionTest_(); b0.Equals_(); b0.Singleton_(); b0.Call_(); b0.Name("getUriPart"); b1.Resolver(); b0._Call(); b0._Singleton(); b0.VariableRefStep("uri"); b0._Equals(); b0._ExpressionTest(); b0._Filter(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("isLocalQName"); b1.Resolver(); b0.Call_(); b0.Name("matchesUriInQName"); b0.Expressions_(1); b0.VariableRefStep("TARGET_NS_URI"); b0._Expressions(); b0._Call(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("isSchemaQName"); b1.Resolver(); b0.Call_(); b0.Name("matchesUriInQName"); b0.Expressions_(1); b0.VariableRefStep("XML_SCHEMA_NS_URI"); b0._Expressions(); b0._Call(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("isImportedQName"); b1.Resolver(); b0.Filter_(); b0.SelfStep(); b0.Not_(); b0.Or_(2); b0.ExpressionTest_(); b0.Call_(); b0.Name("isLocalQName"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0.ExpressionTest_(); b0.Call_(); b0.Name("isSchemaQName"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0._Or(); b0._Not(); b0._Filter(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("toType"); b0.Names_(3); b0.Name("entity"); b0.Name("type"); b0.Name("ed"); b0._Names(); b1.SameStageFragment_(); b2.Sequence_(); b2.Text("sequence"); b2.FlowObjects_(2); b2.InvokeJavaClassMethod_(); b2.Text("convert type to entity descriptor"); b2.Variable("ed"); b1.Resolver(); b2.StringLiteral("org.whole.lang.commons.parsers.CommonsDataTypePersistenceParser"); b2.StringLiteral("getEntityDescriptor(java.lang.String)"); b2.Expressions_(1); b2.Variable("type"); b2._Expressions(); b2._InvokeJavaClassMethod(); b2.InvokeJavaClassMethod_(); b2.Text("convert entity"); b1.Resolver(); b1.Resolver(); b2.StringLiteral("org.whole.lang.util.EntityUtils"); b2.StringLiteral("convert(org.whole.lang.model.IEntity, org.whole.lang.reflect.EntityDescriptor)"); b2.Expressions_(2); b2.Variable("entity"); b2.Variable("ed"); b2._Expressions(); b2._InvokeJavaClassMethod(); b2._FlowObjects(); b2._Sequence(); b1._SameStageFragment(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("addBuiltInModelDeclatration"); b0.Names_(2); b0.Name("entityType"); b0.Name("builtInType"); b0._Names(); b0.Block_(3); b0.QueryDeclaration_(); b0.Name("createBuiltInModelDeclaration"); b0.Names_(3); b0.Name("builtInComponentType"); b0.Name("componentType"); b0.Name("dataType"); b0._Names(); b0.Choose_(2); b0.Select_(); b1.StageUpFragment_(); org.whole.lang.models.builders.IModelsBuilder b3 = (org.whole.lang.models.builders.IModelsBuilder) op.wGetBuilder(org.whole.lang.models.reflect.ModelsLanguageKit.URI); b3.CompositeEntity_(); b3.EntityModifiers_(0); b3._EntityModifiers(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("entityType"); b1.Quantifier("!"); b1._Variable(); b3.Types_(0); b3._Types(); b3.ComponentModifiers_(1); b3.ComponentModifier("ordered"); b3._ComponentModifiers(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#Type"); b1.VarName("componentType"); b1.Quantifier("!"); b1._Variable(); b3._CompositeEntity(); b1._StageUpFragment(); b0.Filter_(); b0.SelfStep(); b0.ExpressionTest_(); b1.SameStageFragment_(); b2.InvokeJavaClassMethod_(); b2.Text("is list derived?"); b1.Resolver(); b1.Resolver(); b2.StringLiteral("org.whole.lang.xsd.parsers.SchemaDataTypes"); b2.StringLiteral("isListDerived(java.lang.String)"); b2.Expressions_(1); b2.Variable("builtInType"); b2._Expressions(); b2._InvokeJavaClassMethod(); b1._SameStageFragment(); b0._ExpressionTest(); b0._Filter(); b0.Sequence_(2); b0.Filter_(); b1.SameStageFragment_(); b2.Sequence_(); b2.Text("calculate component type"); b2.FlowObjects_(2); b2.InvokeJavaClassMethod_(); b2.Text("get built in component type"); b2.Variable("builtInComponentType"); b1.Resolver(); b2.StringLiteral("org.whole.lang.xsd.parsers.SchemaDataTypes"); b2.StringLiteral("getBuiltInComponentType(java.lang.String)"); b2.Expressions_(1); b2.Variable("builtInType"); b2._Expressions(); b2._InvokeJavaClassMethod(); b2.InvokeJavaClassMethod_(); b2.Text("get component type"); b1.Resolver(); b1.Resolver(); b2.StringLiteral("org.whole.lang.xsd.parsers.SchemaDataTypes"); b2.StringLiteral("getEntityNameFromBuiltIn(java.lang.String)"); b2.Expressions_(1); b2.Variable("builtInComponentType"); b2._Expressions(); b2._InvokeJavaClassMethod(); b2._FlowObjects(); b2._Sequence(); b1._SameStageFragment(); b0.VariableTest("componentType"); b0._Filter(); b0.Call_(); b0.Name("addBuiltInModelDeclatration"); b0.Expressions_(1); b0.VariableRefStep("componentType"); b0._Expressions(); b0._Call(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0.Select_(); b1.StageUpFragment_(); b3.DataEntity_(); b3.EntityModifiers_(0); b3._EntityModifiers(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("entityType"); b1.Quantifier("!"); b1._Variable(); b3.Types_(0); b3._Types(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#DataType"); b1.VarName("dataType"); b1.Quantifier("!"); b1._Variable(); b3._DataEntity(); b1._StageUpFragment(); b0.SelfStep(); b0.Filter_(); b1.SameStageFragment_(); b2.InvokeJavaClassMethod_(); b2.Text("get data type"); b1.Resolver(); b1.Resolver(); b2.StringLiteral("org.whole.lang.xsd.parsers.SchemaDataTypes"); b2.StringLiteral("getDataType(java.lang.String)"); b2.Expressions_(1); b2.Variable("builtInType"); b2._Expressions(); b2._InvokeJavaClassMethod(); b1._SameStageFragment(); b0.VariableTest("dataType"); b0._Filter(); b0.TemplateNames(); b0._Select(); b0._Choose(); b0._QueryDeclaration(); b0.If_(); b0.And_(2); b0.ExpressionTest_(); b1.SameStageFragment_(); b2.InvokeJavaClassMethod_(); b2.Text("is schema built in?"); b1.Resolver(); b1.Resolver(); b2.StringLiteral("org.whole.lang.xsd.parsers.SchemaDataTypes"); b2.StringLiteral("isBuiltInEntityName(java.lang.String)"); b2.Expressions_(1); b2.Variable("entityType"); b2._Expressions(); b2._InvokeJavaClassMethod(); b1._SameStageFragment(); b0._ExpressionTest(); b0.Not_(); b0.ExpressionTest_(); b0.Path_(3); b0.VariableRefStep("mappedBuiltInTypes"); b0.ChildStep(); b0.Filter_(); b0.FeatureStep("name"); b0.VariableTest("entityType"); b0._Filter(); b0._Path(); b0._ExpressionTest(); b0._Not(); b0._And(); b0.Block_(4); b0.Filter_(); b1.SameStageFragment_(); b2.InvokeJavaClassMethod_(); b2.Text("get built in type"); b1.Resolver(); b1.Resolver(); b2.StringLiteral("org.whole.lang.xsd.parsers.SchemaDataTypes"); b2.StringLiteral("getBuiltInFromEntityName(java.lang.String)"); b2.Expressions_(1); b2.Variable("entityType"); b2._Expressions(); b2._InvokeJavaClassMethod(); b1._SameStageFragment(); b0.VariableTest("builtInType"); b0._Filter(); b0.PointwiseInsert_(); b0.Placement("INTO"); b0.VariableRefStep("mappedBuiltInTypes"); b0.Call_(); b0.Name("createBuiltInModelDeclaration"); b1.Resolver(); b0._Call(); b0._PointwiseInsert(); b0.PointwiseInsert_(); b0.Placement("INTO"); b0.VariableRefStep("mappedCustomDataTypes"); b0.Call_(); b0.Name("getCustomDataType"); b0.Expressions_(2); b0.VariableRefStep("entityType"); b0.VariableRefStep("builtInType"); b0._Expressions(); b0._Call(); b0._PointwiseInsert(); b0.SelfStep(); b0._Block(); b0._If(); b0.SelfStep(); b0._Block(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getCustomDataType"); b0.Names_(2); b0.Name("entityType"); b0.Name("builtInType"); b0._Names(); b0.If_(); b0.ExpressionTest_(); b0.Singleton_(); b1.SameStageFragment_(); b2.InvokeJavaClassMethod_(); b2.Text("has custom data type?"); b1.Resolver(); b1.Resolver(); b2.StringLiteral("org.whole.lang.xsd.parsers.SchemaDataTypes"); b2.StringLiteral("hasCustomDataType(java.lang.String)"); b2.Expressions_(1); b2.Variable("builtInType"); b2._Expressions(); b2._InvokeJavaClassMethod(); b1._SameStageFragment(); b0._Singleton(); b0._ExpressionTest(); b1.StageUpFragment_(); org.whole.lang.xsd.mapping.builders.IMappingBuilder b4 = (org.whole.lang.xsd.mapping.builders.IMappingBuilder) op.wGetBuilder(org.whole.lang.xsd.mapping.reflect.MappingLanguageKit.URI); b4.CustomDataType_(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("entityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#BuiltInType"); b1.VarName("builtInType"); b1.Quantifier("!"); b1._Variable(); b4._CustomDataType(); b1._StageUpFragment(); b0._If(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getName"); b1.Resolver(); b0.Path_(2); b0.Choose_(3); b0.If_(); b0.Or_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#QName"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#Name"); b0._Or(); b0.SelfStep(); b0._If(); b0.If_(); b0.SubtypeTest("http://www.w3.org/2001/XMLSchema#Reference"); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#ref"); b0._If(); b0.Do_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#name"); b0._Do(); b0._Choose(); b0.Choose_(2); b0.Filter_(); b0.SelfStep(); b0.And_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#QName"); b0.Not_(); b0.ExpressionTest_(); b0.Call_(); b0.Name("isLocalQName"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0._Not(); b0._And(); b0._Filter(); b0.Call_(); b0.Name("getBasePart"); b1.Resolver(); b0._Call(); b0._Choose(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getComponent"); b0.Names_(3); b0.Name("uri"); b0.Name("components"); b0.Name("name"); b0._Names(); b0.Block_(3); b0.Path_(2); b1.SameStageFragment_(); b2.Sequence_(); b2.Text("retrive target schmea"); b2.FlowObjects_(2); b2.InvokeJavaClassMethod_(); b2.Text("get XsdRegistry instance"); b2.Variable("schemaRegistry"); b1.Resolver(); b2.StringLiteral("org.whole.lang.xsd.resources.XsdRegistry"); b2.StringLiteral("instance()"); b1.Resolver(); b2._InvokeJavaClassMethod(); b2.InvokeJavaInstanceMethod_(); b2.Text("get xml schema"); b1.Resolver(); b2.Variable("schemaRegistry"); b1.Resolver(); b2.StringLiteral("org.whole.lang.xsd.resources.XsdRegistry"); b2.StringLiteral("getSchemaFor(java.lang.String)"); b2.Expressions_(1); b1.SameStageFragment_(); b0.Call_(); b0.Name("getUriPart"); b1.Resolver(); b0._Call(); b1._SameStageFragment(); b2._Expressions(); b2._InvokeJavaInstanceMethod(); b2._FlowObjects(); b2._Sequence(); b1._SameStageFragment(); b0.Filter_(); b0.FeatureStep("components"); b0.VariableTest("components"); b0._Filter(); b0._Path(); b0.Filter_(); b0.Call_(); b0.Name("toType"); b0.Expressions_(2); b0.Call_(); b0.Name("getBasePart"); b1.Resolver(); b0._Call(); b0.Addition_(); b0.VariableRefStep("XML_SCHEMA_NS_URI"); b0.StringLiteral("#Name"); b0._Addition(); b0._Expressions(); b0._Call(); b0.VariableTest("name"); b0._Filter(); b0.Choose_(5); b0.Path_(3); b0.Filter_(); b0.ParentStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ElementRef"); b0._Filter(); b0.VariableRefStep("components"); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.ExpressionTest_(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#name"); b0.VariableTest("name"); b0._Filter(); b0._ExpressionTest(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ElementDecl"); b0._And(); b0._Filter(); b0._Path(); b0.Path_(3); b0.Filter_(); b0.ParentStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeUseRef"); b0._Filter(); b0.VariableRefStep("components"); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.ExpressionTest_(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#name"); b0.VariableTest("name"); b0._Filter(); b0._ExpressionTest(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeDecl"); b0._And(); b0._Filter(); b0._Path(); b0.Path_(3); b0.Filter_(); b0.ParentStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeGroupRef"); b0._Filter(); b0.VariableRefStep("components"); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.ExpressionTest_(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#name"); b0.VariableTest("name"); b0._Filter(); b0._ExpressionTest(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeGroupDef"); b0._And(); b0._Filter(); b0._Path(); b0.Path_(3); b0.Filter_(); b0.ParentStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ModelGroupRef"); b0._Filter(); b0.VariableRefStep("components"); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.ExpressionTest_(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#name"); b0.VariableTest("name"); b0._Filter(); b0._ExpressionTest(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ModelGroupDef"); b0._And(); b0._Filter(); b0._Path(); b0.Path_(2); b0.VariableRefStep("components"); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.ExpressionTest_(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#name"); b0.VariableTest("name"); b0._Filter(); b0._ExpressionTest(); b0.SubtypeTest("http://www.w3.org/2001/XMLSchema#TypeDef"); b0._And(); b0._Filter(); b0._Path(); b0._Choose(); b0._Block(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getSuperSimpleExtension"); b1.Resolver(); b0.Choose_(2); b0.If_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleExtension"); b0.SelfStep(); b0._If(); b0.Path_(5); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#base"); b0.KindTest("IMPL"); b0._Filter(); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#content"); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#derivation"); b0.Call_(); b0.Name("getSuperSimpleExtension"); b1.Resolver(); b0._Call(); b0._Path(); b0._Choose(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getSimpleBaseType"); b1.Resolver(); b0.Choose_(2); b0.Path_(2); b0.FeatureStep("content"); b0.Choose_(2); b0.Path_(3); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleContent"); b0._Filter(); b0.FeatureStep("derivation"); b0.FeatureStep("base"); b0._Path(); b0.FeatureStep("base"); b0._Choose(); b0._Path(); b0.Path_(3); b0.Filter_(); b0.SelfStep(); b0.And_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleRestriction"); b0.ExpressionTest_(); b0.Path_(2); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#facets"); b0.ChildStep(); b0._Path(); b0._ExpressionTest(); b0._And(); b0._Filter(); b0.Call_(); b0.Name("getSuperSimpleExtension"); b1.Resolver(); b0._Call(); b0.FeatureStep("base"); b0._Path(); b0._Choose(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getBaseType"); b1.Resolver(); b0.Block_(2); b0.QueryDeclaration_(); b0.Name("getComplexBaseType"); b1.Resolver(); b0.Path_(3); b0.Filter_(); b0.FeatureStep("content"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ComplexContent"); b0._Filter(); b0.FeatureStep("derivation"); b0.FeatureStep("base"); b0._Path(); b0._QueryDeclaration(); b0.Choose_(2); b0.Call_(); b0.Name("getComplexBaseType"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getSimpleBaseType"); b1.Resolver(); b0._Call(); b0._Choose(); b0._Block(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getExtensionBaseDataType"); b0.Names_(1); b0.Name("extension"); b0._Names(); b0.Block_(2); b0.Filter_(); b0.SelfStep(); b0.VariableTest("extension"); b0._Filter(); b0.Path_(2); b0.FeatureStep("base"); b0.Choose_(2); b0.Path_(2); b0.Call_(); b0.Name("isSchemaQName"); b1.Resolver(); b0._Call(); b0.VariableRefStep("extension"); b0._Path(); b0.Path_(3); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.FeatureStep("content"); b0.Choose_(2); b0.Path_(3); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleContent"); b0._Filter(); b0.FeatureStep("derivation"); b0.Call_(); b0.Name("getExtensionBaseDataType"); b1.Resolver(); b0._Call(); b0._Path(); b0.VariableRefStep("extension"); b0._Choose(); b0._Path(); b0._Choose(); b0._Path(); b0._Block(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getBuiltInType"); b1.Resolver(); b0.Path_(2); b0.Call_(); b0.Name("getSimpleBaseType"); b1.Resolver(); b0._Call(); b0.Choose_(2); b0.Path_(2); b0.Call_(); b0.Name("isSchemaQName"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getBasePart"); b1.Resolver(); b0._Call(); b0._Path(); b0.Path_(2); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getBuiltInType"); b1.Resolver(); b0._Call(); b0._Path(); b0._Choose(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getAppInfo"); b0.Names_(1); b0.Name("annotated"); b0._Names(); b0.Block_(2); b0.Filter_(); b0.SelfStep(); b0.VariableTest("annotated"); b0._Filter(); b0.Path_(7); b0.VariableRefStep("annotated"); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#annotation"); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#list"); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#Appinfo"); b0.ExpressionTest_(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#source"); b0.ExpressionTest_(); b1.StageUpFragment_(); org.whole.lang.xsd.builders.IXsdBuilder b5 = (org.whole.lang.xsd.builders.IXsdBuilder) op.wGetBuilder(org.whole.lang.xsd.reflect.XsdLanguageKit.URI); b5.AnyURI("http://lang.whole.org/Models"); b1._StageUpFragment(); b0._ExpressionTest(); b0._Filter(); b0._ExpressionTest(); b0._And(); b0._Filter(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#content"); b0.Filter_(); b0.ChildStep(); b0.SubtypeTest("http://lang.whole.org/Commons#Fragment");//WAS KindTest("FRAGMENT") b0._Filter(); b0.Filter_(); b0.FeatureStep("http://lang.whole.org/Commons#rootEntity"); b0.LanguageTest("http://lang.whole.org/Models"); b0._Filter(); b0._Path(); b0._Block(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("findAppInfo"); b1.Resolver(); b0.Path_(2); b0.Choose_(4); b0.Path_(4); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ModelGroupRef"); b0._Filter(); b0.FeatureStep("ref"); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.FeatureStep("modelGroup"); b0._Path(); b0.Path_(2); b0.FeatureStep("ref"); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0._Path(); b0.Path_(2); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ModelGroupDef"); b0._Filter(); b0.FeatureStep("modelGroup"); b0._Path(); b0.SelfStep(); b0._Choose(); b0.Call_(); b0.Name("getAppInfo"); b1.Resolver(); b0._Call(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("findAppInfoFeature"); b1.Resolver(); b0.Path_(2); b0.Call_(); b0.Name("findAppInfo"); b1.Resolver(); b0._Call(); b0.FeatureStep("name"); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("findAppInfoType"); b1.Resolver(); b0.Path_(2); b0.Call_(); b0.Name("findAppInfo"); b1.Resolver(); b0._Call(); b0.Choose_(2); b0.If_(); b0.TypeTest("http://lang.whole.org/Models#Feature"); b0.FeatureStep("type"); b0._If(); b0.SelfStep(); b0._Choose(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("findImportedAppInfoType"); b0.Names_(3); b0.Name("prefix"); b0.Name("uri"); b0.Name("schemaRegistry"); b0._Names(); b0.Addition_(); b0.Singleton_(); b0.Call_(); b0.Name("getUriPart"); b1.Resolver(); b0._Call(); b0._Singleton(); b0.Addition_(); b0.StringLiteral("#"); b0.Singleton_(); b0.Path_(3); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getAppInfo"); b1.Resolver(); b0._Call(); b0.Choose_(2); b0.FeatureStep("name"); b0.SelfStep(); b0._Choose(); b0._Path(); b0._Singleton(); b0._Addition(); b0._Addition(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("addAppInfo"); b0.Names_(1); b0.Name("contents"); b0._Names(); b0.Block_(2); b0.If_(); b0.ExpressionTest_(); b0.Path_(1); b0.VariableRefStep("contents"); b0._Path(); b0._ExpressionTest(); b0.PointwiseInsert_(); b0.Placement("INTO"); b0.Path_(2); b0.Choose_(2); b0.PointwiseUpdate_(); b0.Filter_(); b0.FeatureStep("annotation"); b0.KindTest("RESOLVER"); b0._Filter(); b1.StageUpFragment_(); b5.Annotation_(); b1.Resolver(); b1.Resolver(); b1.Resolver(); b5.AnnotationList_(0); b5._AnnotationList(); b5._Annotation(); b1._StageUpFragment(); b0._PointwiseUpdate(); b0.FeatureStep("annotation"); b0._Choose(); b0.FeatureStep("list"); b0._Path(); b1.StageUpFragment_(); b5.Appinfo_(); b1.Resolver(); b1.Resolver(); b1.Resolver(); b1.Resolver(); b5.AnnotationContents_(1); b1.SameStageFragment_(); b1.Variable_(); b1.VarType("http://lang.whole.org/Commons#Any"); b1.VarName("contents"); b1.Quantifier("!"); b1._Variable(); b1._SameStageFragment(); b5._AnnotationContents(); b5._Appinfo(); b1._StageUpFragment(); b0._PointwiseInsert(); b0._If(); b0.SelfStep(); b0._Block(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("cloneMappings"); b0.Names_(6); b0.Name("targetContextType"); b0.Name("sourceRef"); b0.Name("sourceContextType"); b0.Name("clonedMapping"); b0.Name("strategyRegistry"); b0.Name("lk"); b0._Names(); b0.Choose_(2); b0.If_(); b0.ExpressionTest_(); b0.Path_(2); b0.VariableRefStep("sourceRef"); b0.Call_(); b0.Name("isLocalQName"); b1.Resolver(); b0._Call(); b0._Path(); b0._ExpressionTest(); b0.Sequence_(2); b0.Path_(3); b0.VariableRefStep("sourceRef"); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("sourceContextType"); b0._Filter(); b0._Path(); b0.For_(); b0.Path_(3); b0.VariableRefStep("mappingStrategy"); b0.FeatureStep("http://xsd.lang.whole.org/Mapping#mappings"); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.SubtypeTest("http://xsd.lang.whole.org/Mapping#ContextMapping"); b0.ExpressionTest_(); b0.Equals_(); b0.Singleton_(); b0.FeatureStep("http://xsd.lang.whole.org/Mapping#contextEntityType"); b0._Singleton(); b0.VariableRefStep("sourceContextType"); b0._Equals(); b0._ExpressionTest(); b0._And(); b0._Filter(); b0._Path(); b0.Sequence_(3); b0.Filter_(); b1.SameStageFragment_(); b2.InvokeJavaClassMethod_(); b2.Text("clone mapping"); b1.Resolver(); b1.Resolver(); b2.StringLiteral("org.whole.lang.util.EntityUtils"); b2.StringLiteral("clone(org.whole.lang.model.IEntity)"); b2.Expressions_(1); b2.Variable("self"); b2._Expressions(); b2._InvokeJavaClassMethod(); b1._SameStageFragment(); b0.VariableTest("clonedMapping"); b0._Filter(); b0.PointwiseUpdate_(); b0.Path_(2); b0.VariableRefStep("clonedMapping"); b0.FeatureStep("http://xsd.lang.whole.org/Mapping#contextEntityType"); b0._Path(); b0.VariableRefStep("targetContextType"); b0._PointwiseUpdate(); b0.PointwiseInsert_(); b0.Placement("INTO"); b0.Path_(2); b0.VariableRefStep("mappingStrategy"); b0.FeatureStep("http://xsd.lang.whole.org/Mapping#mappings"); b0._Path(); b0.VariableRefStep("clonedMapping"); b0._PointwiseInsert(); b0._Sequence(); b0._For(); b0._Sequence(); b0._If(); b0.Do_(); b1.Resolver(); b0._Do(); b0._Choose(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getType"); b1.Resolver(); b0.Choose_(2); b0.Filter_(); b0.FeatureStep("simpleType"); b0.KindTest("IMPL"); b0._Filter(); b0.Filter_(); b0.FeatureStep("type"); b0.KindTest("IMPL"); b0._Filter(); b0._Choose(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getTypeDef"); b1.Resolver(); b0.Choose_(3); b0.Path_(2); b0.Call_(); b0.Name("getType"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0._Path(); b0.Filter_(); b0.FeatureStep("simpleTypeDef"); b0.KindTest("IMPL"); b0._Filter(); b0.Filter_(); b0.FeatureStep("typeDef"); b0.KindTest("IMPL"); b0._Filter(); b0._Choose(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getParticlesContainer"); b1.Resolver(); b0.Choose_(2); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ModelGroupDef"); b0._Filter(); b0.Path_(2); b0.FeatureStep("content"); b0.Choose_(2); b0.Path_(3); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ComplexContent"); b0._Filter(); b0.FeatureStep("derivation"); b0.FeatureStep("content"); b0._Path(); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#DeclaredContent"); b0._Filter(); b0._Choose(); b0._Path(); b0._Choose(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getDescendantParticles"); b1.Resolver(); b0.Path_(1); b0.Sequence_(2); b0.SelfStep(); b0.If_(); b0.SubtypeTest("http://www.w3.org/2001/XMLSchema#ModelGroupWithParticles"); b0.Path_(3); b0.FeatureStep("particles"); b0.ChildStep(); b0.Call_(); b0.Name("getDescendantParticles"); b1.Resolver(); b0._Call(); b0._Path(); b0._If(); b0._Sequence(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getComponentParticles"); b1.Resolver(); b0.Path_(3); b0.Call_(); b0.Name("getParticlesContainer"); b1.Resolver(); b0._Call(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#modelGroup"); b0.Call_(); b0.Name("getDescendantParticles"); b1.Resolver(); b0._Call(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getComponentChildParticles"); b1.Resolver(); b0.Path_(3); b0.Call_(); b0.Name("getParticlesContainer"); b1.Resolver(); b0._Call(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#modelGroup"); b0.Call_(); b0.Name("getChildParticles"); b1.Resolver(); b0._Call(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getChildParticles"); b1.Resolver(); b0.Path_(2); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#particles"); b0.ChildStep(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getLocalParticles"); b1.Resolver(); b0.Path_(2); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#particles"); b0.Filter_(); b0.ChildStep(); b0.Not_(); b0.SubtypeTest("http://www.w3.org/2001/XMLSchema#Reference"); b0._Not(); b0._Filter(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getReferencedParticles"); b1.Resolver(); b0.Path_(2); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#particles"); b0.Filter_(); b0.ChildStep(); b0.SubtypeTest("http://www.w3.org/2001/XMLSchema#Reference"); b0._Filter(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getComponentModelGroupWithParticles"); b1.Resolver(); b0.Filter_(); b0.Call_(); b0.Name("getComponentParticles"); b1.Resolver(); b0._Call(); b0.And_(2); b0.SubtypeTest("http://www.w3.org/2001/XMLSchema#ModelGroupWithParticles"); b0.KindTest("IMPL"); b0._And(); b0._Filter(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getBaseParticles"); b1.Resolver(); b0.Sequence_(2); b0.Path_(5); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#content"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ComplexContent"); b0._Filter(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#derivation"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ComplexExtension"); b0._Filter(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#base"); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getBaseParticles"); b1.Resolver(); b0._Call(); b0._Path(); b0.Path_(2); b0.Call_(); b0.Name("getParticlesContainer"); b1.Resolver(); b0._Call(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#modelGroup"); b0.KindTest("IMPL"); b0._Filter(); b0._Path(); b0._Sequence(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getAttributesContainer"); b1.Resolver(); b0.Path_(2); b0.FeatureStep("content"); b0.Choose_(3); b0.Path_(3); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ComplexContent"); b0._Filter(); b0.FeatureStep("derivation"); b0.FeatureStep("content"); b0._Path(); b0.Path_(2); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleContent"); b0._Filter(); b0.FeatureStep("derivation"); b0._Path(); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#DeclaredContent"); b0._Filter(); b0._Choose(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getAttributesGroupChildren"); b1.Resolver(); b0.Path_(5); b0.FeatureStep("ref"); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.FeatureStep("attributeUses"); b0.ChildStep(); b0.Choose_(2); b0.Path_(2); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeGroupRef"); b0._Filter(); b0.Call_(); b0.Name("getAttributesGroupChildren"); b1.Resolver(); b0._Call(); b0._Path(); b0.Filter_(); b0.SelfStep(); b0.Not_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeGroupRef"); b0._Not(); b0._Filter(); b0._Choose(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getLocalAttributes"); b1.Resolver(); b0.Path_(3); b0.Call_(); b0.Name("getAttributesContainer"); b1.Resolver(); b0._Call(); b0.FeatureStep("attributeUses"); b0.Filter_(); b0.ChildStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeUseDecl"); b0._Filter(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getReferencedAttributes"); b1.Resolver(); b0.Path_(4); b0.Call_(); b0.Name("getAttributesContainer"); b1.Resolver(); b0._Call(); b0.FeatureStep("attributeUses"); b0.Filter_(); b0.ChildStep(); b0.Not_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeUseDecl"); b0._Not(); b0._Filter(); b0.Choose_(2); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeUseRef"); b0._Filter(); b0.Call_(); b0.Name("getAttributesGroupChildren"); b1.Resolver(); b0._Call(); b0._Choose(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getDeclaredAttributes"); b1.Resolver(); b0.Sequence_(2); b0.Call_(); b0.Name("getReferencedAttributes"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getLocalAttributes"); b1.Resolver(); b0._Call(); b0._Sequence(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getInheritedAttributes"); b0.Names_(1); b0.Name("excluded"); b0._Names(); b0.Path_(3); b0.Call_(); b0.Name("getBaseType"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getAttributes"); b0.Expressions_(1); b0.VariableRefStep("excluded"); b0._Expressions(); b0._Call(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getAttributes"); b0.Names_(2); b0.Name("excluded"); b0.Name("declared"); b0._Names(); b0.Block_(3); b0.Filter_(); b0.Union_(); b0.Expressions_(0); b0._Expressions(); b1.Resolver(); b0._Union(); b0.VariableTest("excluded"); b0._Filter(); b0.Filter_(); b0.Except_(); b0.Expressions_(2); b0.Call_(); b0.Name("getDeclaredAttributes"); b1.Resolver(); b0._Call(); b0.Path_(2); b0.VariableRefStep("excluded"); b0.ChildStep(); b0._Path(); b0._Expressions(); b0.IdentityComparator_(); b0.FeatureStep("name"); b0._IdentityComparator(); b0._Except(); b0.VariableTest("declared"); b0._Filter(); b0.Sequence_(2); b0.CartesianInsert_(); b0.Placement("INTO"); b0.VariableRefStep("excluded"); b0.Path_(2); b0.VariableRefStep("declared"); b0.ChildStep(); b0._Path(); b0._CartesianInsert(); b0.Call_(); b0.Name("getInheritedAttributes"); b0.Expressions_(1); b0.VariableRefStep("excluded"); b0._Expressions(); b0._Call(); b0._Sequence(); b0._Block(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getAttributesGroupWildcards"); b1.Resolver(); b0.Path_(3); b0.FeatureStep("ref"); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.Sequence_(2); b0.Filter_(); b0.FeatureStep("anyAttribute"); b0.KindTest("IMPL"); b0._Filter(); b0.Path_(3); b0.FeatureStep("attributeUses"); b0.Filter_(); b0.ChildStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeGroupRef"); b0._Filter(); b0.Call_(); b0.Name("getAttributesGroupWildcards"); b1.Resolver(); b0._Call(); b0._Path(); b0._Sequence(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getLocalWildcardAttribute"); b1.Resolver(); b0.Path_(2); b0.Call_(); b0.Name("getAttributesContainer"); b1.Resolver(); b0._Call(); b0.Filter_(); b0.FeatureStep("anyAttribute"); b0.KindTest("IMPL"); b0._Filter(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getDeclaredWildcardAttribute"); b1.Resolver(); b0.Path_(2); b0.Call_(); b0.Name("getAttributesContainer"); b1.Resolver(); b0._Call(); b0.Sequence_(2); b0.Filter_(); b0.FeatureStep("anyAttribute"); b0.KindTest("IMPL"); b0._Filter(); b0.Path_(3); b0.FeatureStep("attributeUses"); b0.Filter_(); b0.ChildStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeGroupRef"); b0._Filter(); b0.Call_(); b0.Name("getAttributesGroupWildcards"); b1.Resolver(); b0._Call(); b0._Path(); b0._Sequence(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getInheritedWildcardAttribute"); b1.Resolver(); b0.Path_(3); b0.Call_(); b0.Name("getBaseType"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getWildcardAttribute"); b1.Resolver(); b0._Call(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getWildcardAttribute"); b1.Resolver(); b0.Block_(2); b1.StageUpFragment_(); org.whole.lang.text.builders.ITextBuilder b6 = (org.whole.lang.text.builders.ITextBuilder) op.wGetBuilder(org.whole.lang.text.reflect.TextLanguageKit.URI); b6.Document_(2); b6.Row_(1); b6.Text("1. Implement wildcard namespaceSpecs intersection/union algorithms"); b6._Row(); b6.Row_(1); b6.Text("(currently the first anyAttribute in hierarchy is returned)"); b6._Row(); b6._Document(); b1._StageUpFragment(); b0.Filter_(); b0.Sequence_(2); b0.Call_(); b0.Name("getDeclaredWildcardAttribute"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getInheritedWildcardAttribute"); b1.Resolver(); b0._Call(); b0._Sequence(); b0.IndexTest_(); b0.IntLiteral(0); b0._IndexTest(); b0._Filter(); b0._Block(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("hasAttributes"); b1.Resolver(); b0.Filter_(); b0.Sequence_(2); b0.Call_(); b0.Name("getAttributes"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getWildcardAttribute"); b1.Resolver(); b0._Call(); b0._Sequence(); b0.IndexTest_(); b0.IntLiteral(0); b0._IndexTest(); b0._Filter(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("needsFeatureDeclarations"); b1.Resolver(); b0.Choose_(2); b0.Path_(2); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#content"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleContent"); b0._Filter(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#derivation"); b0.And_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleRestriction"); b0.Not_(); b0.ExpressionTest_(); b0.Path_(2); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#facets"); b0.ChildStep(); b0._Path(); b0._ExpressionTest(); b0._Not(); b0._And(); b0._Filter(); b0._Path(); b0.Path_(2); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#content"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ComplexContent"); b0._Filter(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#derivation"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ComplexRestriction"); b0._Filter(); b0._Path(); b0._Choose(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("isChoiceModelGroupDef"); b1.Resolver(); b0.Filter_(); b0.SelfStep(); b0.And_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ModelGroupDef"); b0.ExpressionTest_(); b0.Filter_(); b0.Call_(); b0.Name("getComponentModelGroupWithParticles"); b1.Resolver(); b0._Call(); b0.And_(2); b0.IndexTest_(); b0.IntLiteral(0); b0._IndexTest(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#Choice"); b0._And(); b0._Filter(); b0._ExpressionTest(); b0._And(); b0._Filter(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("isChoiceModelGroupRef"); b1.Resolver(); b0.Path_(3); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ModelGroupRef"); b0._Filter(); b0.FeatureStep("ref"); b0.Filter_(); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.ExpressionTest_(); b0.Call_(); b0.Name("isChoiceModelGroupDef"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0._Filter(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("hasImportedType"); b1.Resolver(); b0.Filter_(); b0.Choose_(3); b0.Path_(2); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ElementDecl"); b0._Filter(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#type"); b0._Path(); b0.Path_(2); b0.Filter_(); b0.SelfStep(); b0.SubtypeTest("http://www.w3.org/2001/XMLSchema#AttributeDecl"); b0._Filter(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#simpleType"); b0._Path(); b0.Path_(2); b0.Filter_(); b0.SelfStep(); b0.And_(2); b0.SubtypeTest("http://www.w3.org/2001/XMLSchema#Reference"); b0.Not_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeGroupRef"); b0._Not(); b0._And(); b0._Filter(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#ref"); b0._Path(); b0._Choose(); b0.And_(2); b0.KindTest("IMPL"); b0.ExpressionTest_(); b0.Call_(); b0.Name("isImportedQName"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0._And(); b0._Filter(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("allChoiceSubstitutions"); b1.Resolver(); b0.Path_(2); b0.Call_(); b0.Name("getChildParticles"); b1.Resolver(); b0._Call(); b0.Choose_(2); b0.Path_(4); b0.Filter_(); b0.SelfStep(); b0.ExpressionTest_(); b0.Call_(); b0.Name("isChoiceModelGroupRef"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0._Filter(); b0.FeatureStep("ref"); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("allChoiceModelGroupDefSubstitutions"); b1.Resolver(); b0._Call(); b0._Path(); b0.SelfStep(); b0._Choose(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("allChoiceModelGroupDefSubstitutions"); b1.Resolver(); b0.Path_(2); b0.Filter_(); b0.Call_(); b0.Name("getComponentModelGroupWithParticles"); b1.Resolver(); b0._Call(); b0.IndexTest_(); b0.IntLiteral(0); b0._IndexTest(); b0._Filter(); b0.Call_(); b0.Name("allChoiceSubstitutions"); b1.Resolver(); b0._Call(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("mapsToCompositeEntity"); b1.Resolver(); b0.Choose_(2); b0.If_(); b0.And_(3); b0.TypeTest("http://www.w3.org/2001/XMLSchema#Sequence"); b0.Not_(); b0.ExpressionTest_(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#maxOccurs"); b0.ExpressionTest_(); b1.StageUpFragment_(); b5.Bounded(1); b1._StageUpFragment(); b0._ExpressionTest(); b0._Filter(); b0._ExpressionTest(); b0._Not(); b0.Not_(); b0.ExpressionTest_(); b0.Filter_(); b0.ParentStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ModelGroupDef"); b0._Filter(); b0._ExpressionTest(); b0._Not(); b0._And(); b0.BooleanLiteral(true); b0._If(); b0.Do_(); b0.BooleanLiteral(false); b0._Do(); b0._Choose(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("mapToModelDeclaration"); b0.Names_(7); b0.Name("eType"); b0.Name("cType"); b0.Name("features"); b0.Name("fName"); b0.Name("fType"); b0.Name("fModifier"); b0.Name("attributeFeatures"); b0._Names(); b0.Choose_(7); b0.If_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ElementDecl"); b0.Block_(2); b0.Call_(); b0.Name("addBuiltInModelDeclatration"); b0.Expressions_(1); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0._Expressions(); b0._Call(); b0.Path_(2); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#typeDef"); b0.Call_(); b0.Name("mapToModelDeclaration"); b1.Resolver(); b0._Call(); b0._Path(); b0._Block(); b0._If(); b0.If_(); b0.SubtypeTest("http://www.w3.org/2001/XMLSchema#AttributeDecl"); b0.Block_(2); b0.Call_(); b0.Name("addBuiltInModelDeclatration"); b0.Expressions_(1); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0._Expressions(); b0._Call(); b0.Path_(2); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#simpleTypeDef"); b0.Call_(); b0.Name("mapToModelDeclaration"); b1.Resolver(); b0._Call(); b0._Path(); b0._Block(); b0._If(); b0.If_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ComplexTypeDef"); b0.Sequence_(2); b0.Path_(2); b0.Sequence_(3); b0.Path_(2); b0.Call_(); b0.Name("getParticlesContainer"); b1.Resolver(); b0._Call(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#modelGroup"); b0._Path(); b0.Path_(3); b0.Filter_(); b0.SelfStep(); b0.Not_(); b0.ExpressionTest_(); b0.Call_(); b0.Name("needsFeatureDeclarations"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0._Not(); b0._Filter(); b0.Call_(); b0.Name("getDeclaredAttributes"); b1.Resolver(); b0._Call(); b0.Filter_(); b0.SelfStep(); b0.Not_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeUseRef"); b0._Not(); b0._Filter(); b0._Path(); b0.Path_(2); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#content"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleContent"); b0._Filter(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#derivation"); b0.And_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleRestriction"); b0.ExpressionTest_(); b0.Path_(2); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#facets"); b0.ChildStep(); b0._Path(); b0._ExpressionTest(); b0._And(); b0._Filter(); b0._Path(); b0._Sequence(); b0.Call_(); b0.Name("mapToModelDeclaration"); b1.Resolver(); b0._Call(); b0._Path(); b0.Select_(); b1.StageUpFragment_(); b3.SimpleEntity_(); b3.EntityModifiers_(0); b3._EntityModifiers(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("eType"); b1.Quantifier("!"); b1._Variable(); b3.Types_(0); b3._Types(); b3.Features_(2); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#Feature"); b1.VarName("attributeFeatures"); b1.Quantifier("*"); b1._Variable(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#Feature"); b1.VarName("features"); b1.Quantifier("*"); b1._Variable(); b3._Features(); b3._SimpleEntity(); b1._StageUpFragment(); b0.SelfStep(); b0.Sequence_(3); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("eType"); b0._Filter(); b0.Choose_(3); b0.Select_(); b0.Filter_(); b1.StageUpFragment_(); b3.Feature_(); b3.FeatureModifiers_(0); b3._FeatureModifiers(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("fType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("fName"); b1.Quantifier("!"); b1._Variable(); b1.Resolver(); b3._Feature(); b1._StageUpFragment(); b0.VariableTest("features"); b0._Filter(); b0.Path_(2); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#content"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleContent"); b0._Filter(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#derivation"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleExtension"); b0._Filter(); b0._Path(); b0.Sequence_(3); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("fType"); b0._Filter(); b0.Call_(); b0.Name("addBuiltInModelDeclatration"); b0.Expressions_(1); b0.VariableRefStep("fType"); b0._Expressions(); b0._Call(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoFeature"); b1.Resolver(); b0._Call(); b0.VariableTest("fName"); b0._Filter(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0.Select_(); b0.Filter_(); b1.StageUpFragment_(); b3.Feature_(); b3.FeatureModifiers_(0); b3._FeatureModifiers(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("fType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("fName"); b1.Quantifier("!"); b1._Variable(); b1.Resolver(); b3._Feature(); b1._StageUpFragment(); b0.VariableTest("features"); b0._Filter(); b0.Path_(2); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#content"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleContent"); b0._Filter(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#derivation"); b0.And_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleRestriction"); b0.ExpressionTest_(); b0.Path_(2); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#facets"); b0.ChildStep(); b0._Path(); b0._ExpressionTest(); b0._And(); b0._Filter(); b0._Path(); b0.Sequence_(2); b0.Path_(2); b0.Call_(); b0.Name("findAppInfo"); b1.Resolver(); b0._Call(); b0.Filter_(); b0.FeatureStep("http://lang.whole.org/Models#name"); b0.VariableTest("fType"); b0._Filter(); b0._Path(); b0.Path_(2); b0.Call_(); b0.Name("getSuperSimpleExtension"); b1.Resolver(); b0._Call(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoFeature"); b1.Resolver(); b0._Call(); b0.VariableTest("fName"); b0._Filter(); b0._Path(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0.Select_(); b0.Filter_(); b1.StageUpFragment_(); b3.Feature_(); b3.FeatureModifiers_(1); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#FeatureModifier"); b1.VarName("fModifier"); b1.Quantifier("*"); b1._Variable(); b3._FeatureModifiers(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("fType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("fName"); b1.Quantifier("!"); b1._Variable(); b1.Resolver(); b3._Feature(); b1._StageUpFragment(); b0.VariableTest("features"); b0._Filter(); b0.Path_(1); b0.Call_(); b0.Name("getBaseParticles"); b1.Resolver(); b0._Call(); b0._Path(); b0.Sequence_(3); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("fType"); b0._Filter(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoFeature"); b1.Resolver(); b0._Call(); b0.VariableTest("fName"); b0._Filter(); b0.If_(); b0.ExpressionTest_(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#minOccurs"); b0.ExpressionTest_(); b1.StageUpFragment_(); b5.Bounded(0); b1._StageUpFragment(); b0._ExpressionTest(); b0._Filter(); b0._ExpressionTest(); b0.Filter_(); b1.StageUpFragment_(); b3.FeatureModifier("optional"); b1._StageUpFragment(); b0.VariableTest("fModifier"); b0._Filter(); b0._If(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0._Choose(); b0.Select_(); b0.Filter_(); b1.StageUpFragment_(); b3.Feature_(); b3.FeatureModifiers_(1); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#FeatureModifier"); b1.VarName("fModifier"); b1.Quantifier("*"); b1._Variable(); b3._FeatureModifiers(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("fType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("fName"); b1.Quantifier("!"); b1._Variable(); b1.Resolver(); b3._Feature(); b1._StageUpFragment(); b0.VariableTest("attributeFeatures"); b0._Filter(); b0.Path_(2); b0.Filter_(); b0.SelfStep(); b0.Not_(); b0.ExpressionTest_(); b0.Call_(); b0.Name("needsFeatureDeclarations"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0._Not(); b0._Filter(); b0.Call_(); b0.Name("getDeclaredAttributes"); b1.Resolver(); b0._Call(); b0._Path(); b0.Sequence_(2); b0.Path_(2); b0.Choose_(2); b0.Path_(3); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeUseRef"); b0._Filter(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#ref"); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0._Path(); b0.SelfStep(); b0._Choose(); b0.Sequence_(2); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("fType"); b0._Filter(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoFeature"); b1.Resolver(); b0._Call(); b0.VariableTest("fName"); b0._Filter(); b0._Sequence(); b0._Path(); b0.If_(); b0.ExpressionTest_(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#use"); b0.ExpressionTest_(); b1.StageUpFragment_(); b5.Use("optional"); b1._StageUpFragment(); b0._ExpressionTest(); b0._Filter(); b0._ExpressionTest(); b0.Filter_(); b1.StageUpFragment_(); b3.FeatureModifier("optional"); b1._StageUpFragment(); b0.VariableTest("fModifier"); b0._Filter(); b0._If(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0._Sequence(); b0._If(); b0.If_(); b0.Or_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#Sequence"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#All"); b0._Or(); b0.Sequence_(2); b0.Path_(2); b0.Call_(); b0.Name("getChildParticles"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("mapToModelDeclaration"); b1.Resolver(); b0._Call(); b0._Path(); b0.Choose_(2); b0.If_(); b0.ExpressionTest_(); b0.Singleton_(); b0.Call_(); b0.Name("mapsToCompositeEntity"); b1.Resolver(); b0._Call(); b0._Singleton(); b0._ExpressionTest(); b0.Select_(); b1.StageUpFragment_(); b3.CompositeEntity_(); b3.EntityModifiers_(0); b3._EntityModifiers(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("eType"); b1.Quantifier("!"); b1._Variable(); b3.Types_(0); b3._Types(); b3.ComponentModifiers_(1); b3.ComponentModifier("ordered"); b3._ComponentModifiers(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("cType"); b1.Quantifier("?"); b1._Variable(); b3._CompositeEntity(); b1._StageUpFragment(); b0.SelfStep(); b0.Sequence_(2); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("eType"); b0._Filter(); b0.Path_(2); b0.Call_(); b0.Name("getChildParticles"); b1.Resolver(); b0._Call(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("cType"); b0._Filter(); b0._Path(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0._If(); b0.Select_(); b1.StageUpFragment_(); b3.SimpleEntity_(); b3.EntityModifiers_(0); b3._EntityModifiers(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("eType"); b1.Quantifier("!"); b1._Variable(); b3.Types_(0); b3._Types(); b3.Features_(1); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#Feature"); b1.VarName("features"); b1.Quantifier("*"); b1._Variable(); b3._Features(); b3._SimpleEntity(); b1._StageUpFragment(); b0.SelfStep(); b0.Sequence_(2); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("eType"); b0._Filter(); b0.Select_(); b0.Filter_(); b1.StageUpFragment_(); b3.Feature_(); b3.FeatureModifiers_(1); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#FeatureModifier"); b1.VarName("fModifier"); b1.Quantifier("*"); b1._Variable(); b3._FeatureModifiers(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("fType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("fName"); b1.Quantifier("!"); b1._Variable(); b1.Resolver(); b3._Feature(); b1._StageUpFragment(); b0.VariableTest("features"); b0._Filter(); b0.Call_(); b0.Name("getChildParticles"); b1.Resolver(); b0._Call(); b0.Sequence_(3); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("fType"); b0._Filter(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoFeature"); b1.Resolver(); b0._Call(); b0.VariableTest("fName"); b0._Filter(); b0.If_(); b0.ExpressionTest_(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#minOccurs"); b0.ExpressionTest_(); b1.StageUpFragment_(); b5.Bounded(0); b1._StageUpFragment(); b0._ExpressionTest(); b0._Filter(); b0._ExpressionTest(); b0.Filter_(); b1.StageUpFragment_(); b3.FeatureModifier("optional"); b1._StageUpFragment(); b0.VariableTest("fModifier"); b0._Filter(); b0._If(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0._Choose(); b0._Sequence(); b0._If(); b0.If_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#Choice"); b0.Sequence_(2); b0.Select_(); b1.StageUpFragment_(); b3.SimpleEntity_(); b3.EntityModifiers_(1); b3.EntityModifier("abstract"); b3._EntityModifiers(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("eType"); b1.Quantifier("!"); b1._Variable(); b3.Types_(0); b3._Types(); b3.Features_(0); b3._Features(); b3._SimpleEntity(); b1._StageUpFragment(); b0.SelfStep(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("eType"); b0._Filter(); b0.TemplateNames(); b0._Select(); b0.Path_(2); b0.Call_(); b0.Name("getChildParticles"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("mapToModelDeclaration"); b1.Resolver(); b0._Call(); b0._Path(); b0._Sequence(); b0._If(); b0.If_(); b0.Or_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleTypeDef"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleRestriction"); b0._Or(); b0.Block_(2); b0.PointwiseInsert_(); b0.Placement("INTO"); b0.VariableRefStep("mappedCustomDataTypes"); b0.Call_(); b0.Name("mapToDataType"); b1.Resolver(); b0._Call(); b0._PointwiseInsert(); b0.Call_(); b0.Name("findAppInfo"); b1.Resolver(); b0._Call(); b0._Block(); b0._If(); b0.If_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ModelGroupDef"); b0.Path_(2); b0.Call_(); b0.Name("getComponentChildParticles"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("mapToModelDeclaration"); b1.Resolver(); b0._Call(); b0._Path(); b0._If(); b0._Choose(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("mapToMapping"); b0.Names_(8); b0.Name("contextStack"); b0.Name("ncname"); b0.Name("entityType"); b0.Name("newContextStack"); b0.Name("context"); b0.Name("previousContext"); b0.Name("contextEntityType"); b0.Name("featureType"); b0._Names(); b0.Choose_(12); b0.If_(); b0.And_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ElementDecl"); b0.Not_(); b0.ExpressionTest_(); b0.Path_(1); b0.VariableRefStep("contextStack"); b0._Path(); b0._ExpressionTest(); b0._Not(); b0._And(); b0.Sequence_(2); b0.Select_(); b1.StageUpFragment_(); b4.RootMapping_(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#NCName"); b1.VarName("ncname"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("entityType"); b1.Quantifier("!"); b1._Variable(); b4._RootMapping(); b1._StageUpFragment(); b0.SelfStep(); b0.Sequence_(2); b0.Filter_(); b0.FeatureStep("name"); b0.VariableTest("ncname"); b0._Filter(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("entityType"); b0._Filter(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0.Path_(2); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#typeDef"); b0.Call_(); b0.Name("mapToMapping"); b1.Resolver(); b0._Call(); b0._Path(); b0._Sequence(); b0._If(); b0.If_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ComplexTypeDef"); b0.Block_(2); b0.Filter_(); b0.Union_(); b0.Expressions_(1); b0.SelfStep(); b0._Expressions(); b1.Resolver(); b0._Union(); b0.VariableTest("newContextStack"); b0._Filter(); b0.Path_(2); b0.Sequence_(2); b0.Choose_(2); b0.Path_(1); b0.Call_(); b0.Name("getBaseParticles"); b1.Resolver(); b0._Call(); b0._Path(); b0.Path_(2); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#content"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleContent"); b0._Filter(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#derivation"); b0.Or_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleExtension"); b0.And_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleRestriction"); b0.ExpressionTest_(); b0.Path_(2); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#facets"); b0.ChildStep(); b0._Path(); b0._ExpressionTest(); b0._And(); b0._Or(); b0._Filter(); b0._Path(); b0._Choose(); b0.Path_(3); b0.Filter_(); b0.SelfStep(); b0.Not_(); b0.ExpressionTest_(); b0.Call_(); b0.Name("needsFeatureDeclarations"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0._Not(); b0._Filter(); b0.Sequence_(2); b0.Call_(); b0.Name("getInheritedAttributes"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getDeclaredAttributes"); b1.Resolver(); b0._Call(); b0._Sequence(); b0.Choose_(2); b0.Path_(3); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeUseRef"); b0._Filter(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#ref"); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0._Path(); b0.SelfStep(); b0._Choose(); b0._Path(); b0._Sequence(); b0.Call_(); b0.Name("mapToMapping"); b0.Expressions_(1); b0.VariableRefStep("newContextStack"); b0._Expressions(); b0._Call(); b0._Path(); b0._Block(); b0._If(); b0.If_(); b0.Or_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ElementRef"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ElementDecl"); b0._Or(); b0.Block_(2); b0.Filter_(); b0.Call_(); b0.Name("getName"); b1.Resolver(); b0._Call(); b0.VariableTest("ncname"); b0._Filter(); b0.Sequence_(3); b0.Select_(); b1.StageUpFragment_(); b4.StructuralMapping_(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("contextEntityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#NCName"); b1.VarName("ncname"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("entityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("featureType"); b1.Quantifier("?"); b1._Variable(); b4._StructuralMapping(); b1._StageUpFragment(); b0.Path_(2); b0.VariableRefStep("contextStack"); b0.PointwiseProduct_(2); b0.Filter_(); b0.ChildStep(); b0.VariableTest("previousContext"); b0._Filter(); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.IndexRangeTest_(); b0.IntLiteral(1); b1.Resolver(); b0._IndexRangeTest(); b0.VariableTest("context"); b0._And(); b0._Filter(); b0._PointwiseProduct(); b0._Path(); b0.Sequence_(3); b0.Path_(2); b0.VariableRefStep("context"); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("contextEntityType"); b0._Filter(); b0._Path(); b0.Path_(2); b0.VariableRefStep("previousContext"); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("entityType"); b0._Filter(); b0._Path(); b0.If_(); b0.Not_(); b0.ExpressionTest_(); b0.Singleton_(); b0.Path_(2); b0.VariableRefStep("context"); b0.Call_(); b0.Name("mapsToCompositeEntity"); b1.Resolver(); b0._Call(); b0._Path(); b0._Singleton(); b0._ExpressionTest(); b0._Not(); b0.Path_(2); b0.VariableRefStep("previousContext"); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoFeature"); b1.Resolver(); b0._Call(); b0.VariableTest("featureType"); b0._Filter(); b0._Path(); b0._If(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0.Select_(); b1.StageUpFragment_(); b4.ElementMapping_(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("contextEntityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#NCName"); b1.VarName("ncname"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("entityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("featureType"); b1.Quantifier("?"); b1._Variable(); b4._ElementMapping(); b1._StageUpFragment(); b0.SelfStep(); b0.Sequence_(4); b0.Path_(2); b0.VariableRefStep("contextStack"); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.IndexTest_(); b0.IntLiteral(0); b0._IndexTest(); b0.VariableTest("context"); b0._And(); b0._Filter(); b0._Path(); b0.Path_(2); b0.VariableRefStep("context"); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("contextEntityType"); b0._Filter(); b0._Path(); b0.Filter_(); b0.Choose_(3); b0.Path_(2); b0.Filter_(); b0.VariableRefStep("ncname"); b0.And_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#QName"); b0.Not_(); b0.ExpressionTest_(); b0.Call_(); b0.Name("isLocalQNameù"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0._Not(); b0._And(); b0._Filter(); b0.Addition_(); b0.Singleton_(); b0.Call_(); b0.Name("getUriPart"); b1.Resolver(); b0._Call(); b0._Singleton(); b0.Addition_(); b0.StringLiteral("#"); b0.Singleton_(); b0.Path_(3); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getAppInfo"); b1.Resolver(); b0._Call(); b0.FeatureStep("type"); b0._Path(); b0._Singleton(); b0._Addition(); b0._Addition(); b0._Path(); b0.Path_(2); b0.Call_(); b0.Name("hasImportedType"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("findImportedAppInfoType"); b1.Resolver(); b0._Call(); b0._Path(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0._Choose(); b0.VariableTest("entityType"); b0._Filter(); b0.If_(); b0.Not_(); b0.ExpressionTest_(); b0.Singleton_(); b0.Path_(2); b0.VariableRefStep("context"); b0.Call_(); b0.Name("mapsToCompositeEntity"); b1.Resolver(); b0._Call(); b0._Path(); b0._Singleton(); b0._ExpressionTest(); b0._Not(); b0.Filter_(); b0.Choose_(2); b0.Call_(); b0.Name("findAppInfoFeature"); b1.Resolver(); b0._Call(); b0.Path_(3); b0.ParentStep(); b0.ParentStep(); b0.Call_(); b0.Name("findAppInfoFeature"); b1.Resolver(); b0._Call(); b0._Path(); b0._Choose(); b0.VariableTest("featureType"); b0._Filter(); b0._If(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0.Path_(2); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#typeDef"); b0.Call_(); b0.Name("mapToMapping"); b1.Resolver(); b0._Call(); b0._Path(); b0._Sequence(); b0._Block(); b0._If(); b0.If_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#Any"); b0.Sequence_(2); b0.Select_(); b1.StageUpFragment_(); b4.AnyStructuralMapping_(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("contextEntityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("entityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("featureType"); b1.Quantifier("?"); b1._Variable(); b4._AnyStructuralMapping(); b1._StageUpFragment(); b0.Path_(2); b0.VariableRefStep("contextStack"); b0.PointwiseProduct_(2); b0.Filter_(); b0.ChildStep(); b0.VariableTest("previousContext"); b0._Filter(); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.IndexRangeTest_(); b0.IntLiteral(1); b1.Resolver(); b0._IndexRangeTest(); b0.VariableTest("context"); b0._And(); b0._Filter(); b0._PointwiseProduct(); b0._Path(); b0.Sequence_(3); b0.Path_(2); b0.VariableRefStep("context"); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("contextEntityType"); b0._Filter(); b0._Path(); b0.Path_(2); b0.VariableRefStep("previousContext"); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("entityType"); b0._Filter(); b0._Path(); b0.If_(); b0.Not_(); b0.ExpressionTest_(); b0.Singleton_(); b0.Path_(2); b0.VariableRefStep("context"); b0.Call_(); b0.Name("mapsToCompositeEntity"); b1.Resolver(); b0._Call(); b0._Path(); b0._Singleton(); b0._ExpressionTest(); b0._Not(); b0.Path_(2); b0.VariableRefStep("previousContext"); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoFeature"); b1.Resolver(); b0._Call(); b0.VariableTest("featureType"); b0._Filter(); b0._Path(); b0._If(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0.Select_(); b1.StageUpFragment_(); b4.AnyElementMapping_(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("contextEntityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("entityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("featureType"); b1.Quantifier("?"); b1._Variable(); b4._AnyElementMapping(); b1._StageUpFragment(); b0.SelfStep(); b0.Sequence_(4); b0.Path_(2); b0.VariableRefStep("contextStack"); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.IndexTest_(); b0.IntLiteral(0); b0._IndexTest(); b0.VariableTest("context"); b0._And(); b0._Filter(); b0._Path(); b0.Path_(2); b0.VariableRefStep("context"); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("contextEntityType"); b0._Filter(); b0._Path(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("entityType"); b0._Filter(); b0.If_(); b0.Not_(); b0.ExpressionTest_(); b0.Singleton_(); b0.Path_(2); b0.VariableRefStep("context"); b0.Call_(); b0.Name("mapsToCompositeEntity"); b1.Resolver(); b0._Call(); b0._Path(); b0._Singleton(); b0._ExpressionTest(); b0._Not(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoFeature"); b1.Resolver(); b0._Call(); b0.VariableTest("featureType"); b0._Filter(); b0._If(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0._Sequence(); b0._If(); b0.If_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleExtension"); b0.Select_(); b1.StageUpFragment_(); b4.ContentMapping_(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("contextEntityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("entityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("featureType"); b1.Quantifier("!"); b1._Variable(); b4._ContentMapping(); b1._StageUpFragment(); b0.SelfStep(); b0.Sequence_(4); b0.Path_(2); b0.VariableRefStep("contextStack"); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.IndexTest_(); b0.IntLiteral(0); b0._IndexTest(); b0.VariableTest("context"); b0._And(); b0._Filter(); b0._Path(); b0.Path_(2); b0.VariableRefStep("context"); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("contextEntityType"); b0._Filter(); b0._Path(); b0.Path_(2); b0.Call_(); b0.Name("getExtensionBaseDataType"); b1.Resolver(); b0._Call(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("entityType"); b0._Filter(); b0._Path(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoFeature"); b1.Resolver(); b0._Call(); b0.VariableTest("featureType"); b0._Filter(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0._If(); b0.If_(); b0.And_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleRestriction"); b0.ExpressionTest_(); b0.Path_(2); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#facets"); b0.ChildStep(); b0._Path(); b0._ExpressionTest(); b0._And(); b0.Select_(); b1.StageUpFragment_(); b4.ContentMapping_(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("contextEntityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("entityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("featureType"); b1.Quantifier("!"); b1._Variable(); b4._ContentMapping(); b1._StageUpFragment(); b0.SelfStep(); b0.Sequence_(4); b0.Path_(2); b0.VariableRefStep("contextStack"); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.IndexTest_(); b0.IntLiteral(0); b0._IndexTest(); b0.VariableTest("context"); b0._And(); b0._Filter(); b0._Path(); b0.Path_(2); b0.VariableRefStep("context"); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("contextEntityType"); b0._Filter(); b0._Path(); b0.Path_(2); b0.Call_(); b0.Name("findAppInfo"); b1.Resolver(); b0._Call(); b0.Filter_(); b0.FeatureStep("http://lang.whole.org/Models#name"); b0.VariableTest("entityType"); b0._Filter(); b0._Path(); b0.Path_(2); b0.Call_(); b0.Name("getSuperSimpleExtension"); b1.Resolver(); b0._Call(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoFeature"); b1.Resolver(); b0._Call(); b0.VariableTest("featureType"); b0._Filter(); b0._Path(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0._If(); b0.If_(); b0.And_(2); b0.SubtypeTest("http://www.w3.org/2001/XMLSchema#AttributeDecl"); b0.ExpressionTest_(); b0.Path_(1); b0.VariableRefStep("contextStack"); b0._Path(); b0._ExpressionTest(); b0._And(); b0.Select_(); b1.StageUpFragment_(); b4.AttributeMapping_(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("contextEntityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#NCName"); b1.VarName("ncname"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("entityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("featureType"); b1.Quantifier("!"); b1._Variable(); b4._AttributeMapping(); b1._StageUpFragment(); b0.SelfStep(); b0.Sequence_(5); b0.Filter_(); b0.Call_(); b0.Name("getName"); b1.Resolver(); b0._Call(); b0.VariableTest("ncname"); b0._Filter(); b0.Path_(2); b0.VariableRefStep("contextStack"); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.IndexTest_(); b0.IntLiteral(0); b0._IndexTest(); b0.VariableTest("context"); b0._And(); b0._Filter(); b0._Path(); b0.Path_(2); b0.VariableRefStep("context"); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("contextEntityType"); b0._Filter(); b0._Path(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("entityType"); b0._Filter(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoFeature"); b1.Resolver(); b0._Call(); b0.VariableTest("featureType"); b0._Filter(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0._If(); b0.If_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#Sequence"); b0.Block_(2); b0.Filter_(); b0.Choose_(2); b0.If_(); b0.ExpressionTest_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0.Union_(); b0.Expressions_(2); b0.SelfStep(); b0.Path_(2); b0.VariableRefStep("contextStack"); b0.ChildStep(); b0._Path(); b0._Expressions(); b1.Resolver(); b0._Union(); b0._If(); b0.Do_(); b0.VariableRefStep("contextStack"); b0._Do(); b0._Choose(); b0.VariableTest("newContextStack"); b0._Filter(); b0.Path_(2); b0.Call_(); b0.Name("getChildParticles"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("mapToMapping"); b0.Expressions_(1); b0.VariableRefStep("newContextStack"); b0._Expressions(); b0._Call(); b0._Path(); b0._Block(); b0._If(); b0.If_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#All"); b0.Block_(2); b0.Filter_(); b0.Choose_(2); b0.If_(); b0.ExpressionTest_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0.Union_(); b0.Expressions_(2); b0.SelfStep(); b0.Path_(2); b0.VariableRefStep("contextStack"); b0.ChildStep(); b0._Path(); b0._Expressions(); b1.Resolver(); b0._Union(); b0._If(); b0.Do_(); b0.VariableRefStep("contextStack"); b0._Do(); b0._Choose(); b0.VariableTest("newContextStack"); b0._Filter(); b0.Path_(2); b0.Call_(); b0.Name("getChildParticles"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("mapToMapping"); b0.Expressions_(1); b0.VariableRefStep("newContextStack"); b0._Expressions(); b0._Call(); b0._Path(); b0._Block(); b0._If(); b0.If_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#Choice"); b0.Path_(2); b0.Call_(); b0.Name("allChoiceSubstitutions"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("mapToMapping"); b0.Expressions_(1); b0.VariableRefStep("contextStack"); b0._Expressions(); b0._Call(); b0._Path(); b0._If(); b0.If_(); b0.ExpressionTest_(); b0.Call_(); b0.Name("isChoiceModelGroupRef"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0.Path_(4); b0.FeatureStep("ref"); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("allChoiceModelGroupDefSubstitutions"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("mapToMapping"); b0.Expressions_(1); b0.VariableRefStep("contextStack"); b0._Expressions(); b0._Call(); b0._Path(); b0._If(); b0.Do_(); b0.VoidLiteral(); b0._Do(); b0._Choose(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("mapToDataType"); b0.Names_(6); b0.Name("enumerations"); b0.Name("entityType"); b0.Name("index"); b0.Name("enumValues"); b0.Name("enumValue"); b0.Name("value"); b0._Names(); b0.Block_(2); b0.QueryDeclaration_(); b0.Name("mapsToEnumEntity"); b1.Resolver(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfo"); b1.Resolver(); b0._Call(); b0.TypeTest("http://lang.whole.org/Models#EnumEntity"); b0._Filter(); b0._QueryDeclaration(); b0.Choose_(2); b0.Select_(); b1.StageUpFragment_(); b4.EnumDataType_(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("entityType"); b1.Quantifier("!"); b1._Variable(); b4.EnumValues_(1); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#EnumValue"); b1.VarName("enumValues"); b1.Quantifier("+"); b1._Variable(); b4._EnumValues(); b4._EnumDataType(); b1._StageUpFragment(); b0.Path_(2); b0.Filter_(); b0.SelfStep(); b0.And_(2); b0.ExpressionTest_(); b0.Call_(); b0.Name("mapsToEnumEntity"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0.ExpressionTest_(); b0.Path_(2); b0.Choose_(2); b0.Path_(2); b0.Filter_(); b0.SelfStep(); b0.And_(1); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleTypeDef"); b0._And(); b0._Filter(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#content"); b0._Path(); b0.Filter_(); b0.SelfStep(); b0.And_(1); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleRestriction"); b0._And(); b0._Filter(); b0._Choose(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#facets"); b0.VariableTest("enumerations"); b0._Filter(); b0._Path(); b0._ExpressionTest(); b0._And(); b0._Filter(); b0.Filter_(); b0.Call_(); b0.Name("getAppInfo"); b1.Resolver(); b0._Call(); b0.ExpressionTest_(); b0.Filter_(); b0.FeatureStep("name"); b0.VariableTest("entityType"); b0._Filter(); b0._ExpressionTest(); b0._Filter(); b0._Path(); b0.Select_(); b0.Filter_(); b1.StageUpFragment_(); b4.EnumValue_(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#Value"); b1.VarName("enumValue"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#Value"); b1.VarName("value"); b1.Quantifier("!"); b1._Variable(); b4._EnumValue(); b1._StageUpFragment(); b0.VariableTest("enumValues"); b0._Filter(); b0.Path_(2); b0.FeatureStep("values"); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.IndexVariableTest("index"); b0.VariableTest("enumValue"); b0._And(); b0._Filter(); b0._Path(); b0.Path_(3); b0.VariableRefStep("enumerations"); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#Enumeration"); b0.IndexVariableTest("index"); b0._And(); b0._Filter(); b0.Filter_(); b0.FeatureStep("value"); b0.VariableTest("value"); b0._Filter(); b0._Path(); b0.TemplateNames(); b0._Select(); b0.TemplateNames(); b0._Select(); b0.Path_(1); b0.Call_(); b0.Name("getCustomDataType"); b0.Expressions_(2); b0.Path_(2); b0.Call_(); b0.Name("findAppInfo"); b1.Resolver(); b0._Call(); b0.FeatureStep("name"); b0._Path(); b0.Call_(); b0.Name("getBuiltInType"); b1.Resolver(); b0._Call(); b0._Expressions(); b0._Call(); b0._Path(); b0._Choose(); b0._Block(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("addSubtype"); b0.Names_(2); b0.Name("subType"); b0.Name("superType"); b0._Names(); b0.PointwiseInsert_(); b0.Placement("INTO"); b0.Path_(4); b0.VariableRefStep("model"); b0.FeatureStep("http://lang.whole.org/Models#declarations"); b0.Filter_(); b0.ChildStep(); b0.ExpressionTest_(); b0.Filter_(); b0.FeatureStep("http://lang.whole.org/Models#name"); b0.VariableTest("subType"); b0._Filter(); b0._ExpressionTest(); b0._Filter(); b0.Filter_(); b0.FeatureStep("http://lang.whole.org/Models#types"); b0.Not_(); b0.ExpressionTest_(); b0.Filter_(); b0.ChildStep(); b0.VariableTest("superType"); b0._Filter(); b0._ExpressionTest(); b0._Not(); b0._Filter(); b0._Path(); b0.VariableRefStep("superType"); b0._PointwiseInsert(); b0._QueryDeclaration(); b0.Select_(); b0.Tuple_(2); b0.Filter_(); b1.StageUpFragment_(); b3.Model_(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("fileName"); b1.Quantifier("!"); b1._Variable(); b3.TypeRelations_(0); b3._TypeRelations(); b3.ModelDeclarations_(2); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#ModelDeclaration"); b1.VarName("modelDeclarations"); b1.Quantifier("*"); b1._Variable(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#ModelDeclaration"); b1.VarName("builtInModelDeclarations"); b1.Quantifier("*"); b1._Variable(); b3._ModelDeclarations(); b3.Namespace("org.whole.lang.xsi"); b1.Resolver(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#URI"); b1.VarName("languageURI"); b1.Quantifier("!"); b1._Variable(); b3._Model(); b1._StageUpFragment(); b0.VariableTest("model"); b0._Filter(); b0.Filter_(); b1.StageUpFragment_(); b4.MappingStrategy_(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("languageURI"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("fileLocationURI"); b1.Quantifier("!"); b1._Variable(); b4.BooleanType(false); b4.BooleanType(true); b4.BooleanType(false); b1.Resolver(); b1.Resolver(); b4.Mappings_(1); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#Mapping"); b1.VarName("mappings"); b1.Quantifier("*"); b1._Variable(); b4._Mappings(); b4.DataTypes_(1); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#DataType"); b1.VarName("customDataTypes"); b1.Quantifier("*"); b1._Variable(); b4._DataTypes(); b4._MappingStrategy(); b1._StageUpFragment(); b0.VariableTest("mappingStrategy"); b0._Filter(); b0._Tuple(); b0.SelfStep(); b0.Sequence_(4); b0.Filter_(); b0.Choose_(2); b0.If_(); b0.Not_(); b0.ExpressionTest_(); b0.Equals_(); b0.VariableRefStep("TARGET_NS_URI"); b0.StringLiteral(""); b0._Equals(); b0._ExpressionTest(); b0._Not(); b0.VariableRefStep("TARGET_NS_URI"); b0._If(); b0.Do_(); b1.SameStageFragment_(); b2.Sequence_(); b2.Text("sequence"); b2.FlowObjects_(1); b2.InvokeJavaClassMethod_(); b2.Text("calculate internal namespace"); b1.Resolver(); b1.Resolver(); b2.StringLiteral("org.whole.lang.xsd.util.NamespaceUtils"); b2.StringLiteral("calculateInternalNamespace(boolean)"); b1.Resolver(); b2._InvokeJavaClassMethod(); b2._FlowObjects(); b2._Sequence(); b1._SameStageFragment(); b0._Do(); b0._Choose(); b0.VariableTest("languageURI"); b0._Filter(); b0.Path_(3); b0.FeatureStep("components"); b0.ChildStep(); b0.Sequence_(2); b0.Filter_(); b0.Call_(); b0.Name("mapToMapping"); b1.Resolver(); b0._Call(); b0.VariableTest("mappings"); b0._Filter(); b0.Filter_(); b0.Call_(); b0.Name("mapToModelDeclaration"); b1.Resolver(); b0._Call(); b0.VariableTest("modelDeclarations"); b0._Filter(); b0._Sequence(); b0._Path(); b0.Path_(2); b0.VariableRefStep("mappedBuiltInTypes"); b0.Filter_(); b0.ChildStep(); b0.VariableTest("builtInModelDeclarations"); b0._Filter(); b0._Path(); b0.Path_(2); b0.VariableRefStep("mappedCustomDataTypes"); b0.Filter_(); b0.ChildStep(); b0.VariableTest("customDataTypes"); b0._Filter(); b0._Path(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0.Path_(2); b0.Filter_(); b0.DescendantStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#Choice"); b0._Filter(); b0.Block_(2); b0.Filter_(); b0.Choose_(2); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.Path_(2); b0.ParentStep(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0._Path(); b0._Choose(); b0.VariableTest("sType"); b0._Filter(); b0.Path_(3); b0.Call_(); b0.Name("getChildParticles"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("addSubtype"); b0.Expressions_(2); b0.SelfStep(); b0.VariableRefStep("sType"); b0._Expressions(); b0._Call(); b0._Path(); b0._Block(); b0._Path(); b0.Path_(2); b0.Filter_(); b0.DescendantStep(); b0.Or_(2); b0.SubtypeTest("http://www.w3.org/2001/XMLSchema#ComplexDerivation"); b0.And_(3); b0.SubtypeTest("http://www.w3.org/2001/XMLSchema#SimpleDerivation"); b0.ExpressionTest_(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#base"); b0.Not_(); b0.ExpressionTest_(); b0.Call_(); b0.Name("isSchemaQName"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0._Not(); b0._Filter(); b0._ExpressionTest(); b0.Not_(); b0.ExpressionTest_(); b0.Path_(3); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#base"); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfo"); b1.Resolver(); b0._Call(); b0.Or_(2); b0.TypeTest("http://lang.whole.org/Models#DataEntity"); b0.TypeTest("http://lang.whole.org/Models#EnumEntity"); b0._Or(); b0._Filter(); b0._Path(); b0._ExpressionTest(); b0._Not(); b0._And(); b0._Or(); b0._Filter(); b0.Call_(); b0.Name("addSubtype"); b0.Expressions_(2); b0.Path_(3); b0.ParentStep(); b0.ParentStep(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0._Path(); b0.Path_(3); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#base"); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0._Path(); b0._Expressions(); b0._Call(); b0._Path(); b0.Path_(2); b0.Filter_(); b0.DescendantStep(); b0.And_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleRestriction"); b0.Not_(); b0.ExpressionTest_(); b0.Path_(2); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#facets"); b0.ChildStep(); b0._Path(); b0._ExpressionTest(); b0._Not(); b0._And(); b0._Filter(); b0.Call_(); b0.Name("cloneMappings"); b0.Expressions_(2); b0.Path_(3); b0.ParentStep(); b0.ParentStep(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0._Path(); b0.Path_(1); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#base"); b0._Path(); b0._Expressions(); b0._Call(); b0._Path(); b0.Tuple_(2); b0.VariableRefStep("model"); b0.VariableRefStep("mappingStrategy"); b0._Tuple(); b0._Block(); }
public void apply(IBuilderOperation op) { org.whole.lang.queries.builders.IQueriesBuilder b0 = (org.whole.lang.queries.builders.IQueriesBuilder) op.wGetBuilder(org.whole.lang.queries.reflect.QueriesLanguageKit.URI); b0.Block_(67); b0.Filter_(); b0.StringLiteral("http://www.w3.org/2001/XMLSchema"); b0.VariableTest("XML_SCHEMA_NS_URI"); b0._Filter(); b0.Filter_(); b0.Choose_(2); b0.Filter_(); b0.FeatureStep("targetNamespace"); b0.KindTest("IMPL"); b0._Filter(); b0.StringLiteral(""); b0._Choose(); b0.VariableTest("TARGET_NS_URI"); b0._Filter(); b0.Filter_(); b0.Union_(); b0.Expressions_(0); b0._Expressions(); org.whole.lang.commons.builders.ICommonsBuilder b1 = (org.whole.lang.commons.builders.ICommonsBuilder) op.wGetBuilder(org.whole.lang.commons.reflect.CommonsLanguageKit.URI); b1.Resolver(); b0._Union(); b0.VariableTest("mappedBuiltInTypes"); b0._Filter(); b0.Filter_(); b0.Union_(); b0.Expressions_(0); b0._Expressions(); b1.Resolver(); b0._Union(); b0.VariableTest("mappedCustomDataTypes"); b0._Filter(); b0.QueryDeclaration_(); b0.Name("getUriPart"); b1.Resolver(); b1.SameStageFragment_(); org.whole.lang.workflows.builders.IWorkflowsBuilder b2 = (org.whole.lang.workflows.builders.IWorkflowsBuilder) op.wGetBuilder(org.whole.lang.workflows.reflect.WorkflowsLanguageKit.URI); b2.InvokeJavaInstanceMethod_(); b2.Text("get uri part"); b1.Resolver(); b2.Variable("self"); b1.Resolver(); b2.StringLiteral("java.lang.String"); b2.StringLiteral("replaceFirst(java.lang.String, java.lang.String)"); b2.Expressions_(2); b2.StringLiteral(":[^:]+$"); b2.StringLiteral(""); b2._Expressions(); b2._InvokeJavaInstanceMethod(); b1._SameStageFragment(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getBasePart"); b1.Resolver(); b1.SameStageFragment_(); b2.InvokeJavaInstanceMethod_(); b2.Text("get base part"); b1.Resolver(); b2.Variable("self"); b1.Resolver(); b2.StringLiteral("java.lang.String"); b2.StringLiteral("replaceFirst(java.lang.String, java.lang.String)"); b2.Expressions_(2); b2.StringLiteral(".+:"); b2.StringLiteral(""); b2._Expressions(); b2._InvokeJavaInstanceMethod(); b1._SameStageFragment(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("matchesUriInQName"); b0.Names_(1); b0.Name("uri"); b0._Names(); b0.Filter_(); b0.SelfStep(); b0.ExpressionTest_(); b0.Equals_(); b0.Singleton_(); b0.Call_(); b0.Name("getUriPart"); b1.Resolver(); b0._Call(); b0._Singleton(); b0.VariableRefStep("uri"); b0._Equals(); b0._ExpressionTest(); b0._Filter(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("isLocalQName"); b1.Resolver(); b0.Call_(); b0.Name("matchesUriInQName"); b0.Expressions_(1); b0.VariableRefStep("TARGET_NS_URI"); b0._Expressions(); b0._Call(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("isSchemaQName"); b1.Resolver(); b0.Call_(); b0.Name("matchesUriInQName"); b0.Expressions_(1); b0.VariableRefStep("XML_SCHEMA_NS_URI"); b0._Expressions(); b0._Call(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("isImportedQName"); b1.Resolver(); b0.Filter_(); b0.SelfStep(); b0.Not_(); b0.Or_(2); b0.ExpressionTest_(); b0.Call_(); b0.Name("isLocalQName"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0.ExpressionTest_(); b0.Call_(); b0.Name("isSchemaQName"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0._Or(); b0._Not(); b0._Filter(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("toType"); b0.Names_(3); b0.Name("entity"); b0.Name("type"); b0.Name("ed"); b0._Names(); b1.SameStageFragment_(); b2.Sequence_(); b2.Text("sequence"); b2.FlowObjects_(2); b2.InvokeJavaClassMethod_(); b2.Text("convert type to entity descriptor"); b2.Variable("ed"); b1.Resolver(); b2.StringLiteral("org.whole.lang.commons.parsers.CommonsDataTypePersistenceParser"); b2.StringLiteral("getEntityDescriptor(java.lang.String)"); b2.Expressions_(1); b2.Variable("type"); b2._Expressions(); b2._InvokeJavaClassMethod(); b2.InvokeJavaClassMethod_(); b2.Text("convert entity"); b1.Resolver(); b1.Resolver(); b2.StringLiteral("org.whole.lang.util.EntityUtils"); b2.StringLiteral("convert(org.whole.lang.model.IEntity, org.whole.lang.reflect.EntityDescriptor)"); b2.Expressions_(2); b2.Variable("entity"); b2.Variable("ed"); b2._Expressions(); b2._InvokeJavaClassMethod(); b2._FlowObjects(); b2._Sequence(); b1._SameStageFragment(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("addBuiltInModelDeclatration"); b0.Names_(2); b0.Name("entityType"); b0.Name("builtInType"); b0._Names(); b0.Block_(3); b0.QueryDeclaration_(); b0.Name("createBuiltInModelDeclaration"); b0.Names_(3); b0.Name("builtInComponentType"); b0.Name("componentType"); b0.Name("dataType"); b0._Names(); b0.Choose_(2); b0.Select_(); b1.StageUpFragment_(); org.whole.lang.models.builders.IModelsBuilder b3 = (org.whole.lang.models.builders.IModelsBuilder) op.wGetBuilder(org.whole.lang.models.reflect.ModelsLanguageKit.URI); b3.CompositeEntity_(); b3.EntityModifiers_(0); b3._EntityModifiers(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("entityType"); b1.Quantifier("!"); b1._Variable(); b3.Types_(0); b3._Types(); b3.ComponentModifiers_(1); b3.ComponentModifier("ordered"); b3._ComponentModifiers(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#Type"); b1.VarName("componentType"); b1.Quantifier("!"); b1._Variable(); b3._CompositeEntity(); b1._StageUpFragment(); b0.Filter_(); b0.SelfStep(); b0.ExpressionTest_(); b1.SameStageFragment_(); b2.InvokeJavaClassMethod_(); b2.Text("is list derived?"); b1.Resolver(); b1.Resolver(); b2.StringLiteral("org.whole.lang.xsd.parsers.SchemaDataTypes"); b2.StringLiteral("isListDerived(java.lang.String)"); b2.Expressions_(1); b2.Variable("builtInType"); b2._Expressions(); b2._InvokeJavaClassMethod(); b1._SameStageFragment(); b0._ExpressionTest(); b0._Filter(); b0.Sequence_(2); b0.Filter_(); b1.SameStageFragment_(); b2.Sequence_(); b2.Text("calculate component type"); b2.FlowObjects_(2); b2.InvokeJavaClassMethod_(); b2.Text("get built in component type"); b2.Variable("builtInComponentType"); b1.Resolver(); b2.StringLiteral("org.whole.lang.xsd.parsers.SchemaDataTypes"); b2.StringLiteral("getBuiltInComponentType(java.lang.String)"); b2.Expressions_(1); b2.Variable("builtInType"); b2._Expressions(); b2._InvokeJavaClassMethod(); b2.InvokeJavaClassMethod_(); b2.Text("get component type"); b1.Resolver(); b1.Resolver(); b2.StringLiteral("org.whole.lang.xsd.parsers.SchemaDataTypes"); b2.StringLiteral("getEntityNameFromBuiltIn(java.lang.String)"); b2.Expressions_(1); b2.Variable("builtInComponentType"); b2._Expressions(); b2._InvokeJavaClassMethod(); b2._FlowObjects(); b2._Sequence(); b1._SameStageFragment(); b0.VariableTest("componentType"); b0._Filter(); b0.Call_(); b0.Name("addBuiltInModelDeclatration"); b0.Expressions_(1); b0.VariableRefStep("componentType"); b0._Expressions(); b0._Call(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0.Select_(); b1.StageUpFragment_(); b3.DataEntity_(); b3.EntityModifiers_(0); b3._EntityModifiers(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("entityType"); b1.Quantifier("!"); b1._Variable(); b3.Types_(0); b3._Types(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#DataType"); b1.VarName("dataType"); b1.Quantifier("!"); b1._Variable(); b3._DataEntity(); b1._StageUpFragment(); b0.SelfStep(); b0.Filter_(); b1.SameStageFragment_(); b2.InvokeJavaClassMethod_(); b2.Text("get data type"); b1.Resolver(); b1.Resolver(); b2.StringLiteral("org.whole.lang.xsd.parsers.SchemaDataTypes"); b2.StringLiteral("getDataType(java.lang.String)"); b2.Expressions_(1); b2.Variable("builtInType"); b2._Expressions(); b2._InvokeJavaClassMethod(); b1._SameStageFragment(); b0.VariableTest("dataType"); b0._Filter(); b0.TemplateNames(); b0._Select(); b0._Choose(); b0._QueryDeclaration(); b0.If_(); b0.And_(2); b0.ExpressionTest_(); b1.SameStageFragment_(); b2.InvokeJavaClassMethod_(); b2.Text("is schema built in?"); b1.Resolver(); b1.Resolver(); b2.StringLiteral("org.whole.lang.xsd.parsers.SchemaDataTypes"); b2.StringLiteral("isBuiltInEntityName(java.lang.String)"); b2.Expressions_(1); b2.Variable("entityType"); b2._Expressions(); b2._InvokeJavaClassMethod(); b1._SameStageFragment(); b0._ExpressionTest(); b0.Not_(); b0.ExpressionTest_(); b0.Path_(3); b0.VariableRefStep("mappedBuiltInTypes"); b0.ChildStep(); b0.Filter_(); b0.FeatureStep("name"); b0.VariableTest("entityType"); b0._Filter(); b0._Path(); b0._ExpressionTest(); b0._Not(); b0._And(); b0.Block_(4); b0.Filter_(); b1.SameStageFragment_(); b2.InvokeJavaClassMethod_(); b2.Text("get built in type"); b1.Resolver(); b1.Resolver(); b2.StringLiteral("org.whole.lang.xsd.parsers.SchemaDataTypes"); b2.StringLiteral("getBuiltInFromEntityName(java.lang.String)"); b2.Expressions_(1); b2.Variable("entityType"); b2._Expressions(); b2._InvokeJavaClassMethod(); b1._SameStageFragment(); b0.VariableTest("builtInType"); b0._Filter(); b0.PointwiseInsert_(); b0.Placement("INTO"); b0.VariableRefStep("mappedBuiltInTypes"); b0.Call_(); b0.Name("createBuiltInModelDeclaration"); b1.Resolver(); b0._Call(); b0._PointwiseInsert(); b0.PointwiseInsert_(); b0.Placement("INTO"); b0.VariableRefStep("mappedCustomDataTypes"); b0.Call_(); b0.Name("getCustomDataType"); b0.Expressions_(2); b0.VariableRefStep("entityType"); b0.VariableRefStep("builtInType"); b0._Expressions(); b0._Call(); b0._PointwiseInsert(); b0.SelfStep(); b0._Block(); b0._If(); b0.SelfStep(); b0._Block(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getCustomDataType"); b0.Names_(2); b0.Name("entityType"); b0.Name("builtInType"); b0._Names(); b0.If_(); b0.ExpressionTest_(); b0.Singleton_(); b1.SameStageFragment_(); b2.InvokeJavaClassMethod_(); b2.Text("has custom data type?"); b1.Resolver(); b1.Resolver(); b2.StringLiteral("org.whole.lang.xsd.parsers.SchemaDataTypes"); b2.StringLiteral("hasCustomDataType(java.lang.String)"); b2.Expressions_(1); b2.Variable("builtInType"); b2._Expressions(); b2._InvokeJavaClassMethod(); b1._SameStageFragment(); b0._Singleton(); b0._ExpressionTest(); b1.StageUpFragment_(); org.whole.lang.xsd.mapping.builders.IMappingBuilder b4 = (org.whole.lang.xsd.mapping.builders.IMappingBuilder) op.wGetBuilder(org.whole.lang.xsd.mapping.reflect.MappingLanguageKit.URI); b4.CustomDataType_(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("entityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#BuiltInType"); b1.VarName("builtInType"); b1.Quantifier("!"); b1._Variable(); b4._CustomDataType(); b1._StageUpFragment(); b0._If(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getName"); b1.Resolver(); b0.Path_(2); b0.Choose_(3); b0.If_(); b0.Or_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#QName"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#Name"); b0._Or(); b0.SelfStep(); b0._If(); b0.If_(); b0.SubtypeTest("http://www.w3.org/2001/XMLSchema#Reference"); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#ref"); b0._If(); b0.Do_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#name"); b0._Do(); b0._Choose(); b0.Choose_(2); b0.Filter_(); b0.SelfStep(); b0.And_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#QName"); b0.Not_(); b0.ExpressionTest_(); b0.Call_(); b0.Name("isLocalQName"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0._Not(); b0._And(); b0._Filter(); b0.Call_(); b0.Name("getBasePart"); b1.Resolver(); b0._Call(); b0._Choose(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getComponent"); b0.Names_(3); b0.Name("uri"); b0.Name("components"); b0.Name("name"); b0._Names(); b0.Block_(3); b0.Path_(2); b1.SameStageFragment_(); b2.Sequence_(); b2.Text("retrive target schmea"); b2.FlowObjects_(2); b2.InvokeJavaClassMethod_(); b2.Text("get XsdRegistry instance"); b2.Variable("schemaRegistry"); b1.Resolver(); b2.StringLiteral("org.whole.lang.xsd.resources.XsdRegistry"); b2.StringLiteral("instance()"); b1.Resolver(); b2._InvokeJavaClassMethod(); b2.InvokeJavaInstanceMethod_(); b2.Text("get xml schema"); b1.Resolver(); b2.Variable("schemaRegistry"); b1.Resolver(); b2.StringLiteral("org.whole.lang.xsd.resources.XsdRegistry"); b2.StringLiteral("getSchemaFor(java.lang.String)"); b2.Expressions_(1); b1.SameStageFragment_(); b0.Call_(); b0.Name("getUriPart"); b1.Resolver(); b0._Call(); b1._SameStageFragment(); b2._Expressions(); b2._InvokeJavaInstanceMethod(); b2._FlowObjects(); b2._Sequence(); b1._SameStageFragment(); b0.Filter_(); b0.FeatureStep("components"); b0.VariableTest("components"); b0._Filter(); b0._Path(); b0.Filter_(); b0.Call_(); b0.Name("toType"); b0.Expressions_(2); b0.Call_(); b0.Name("getBasePart"); b1.Resolver(); b0._Call(); b0.Addition_(); b0.VariableRefStep("XML_SCHEMA_NS_URI"); b0.StringLiteral("#Name"); b0._Addition(); b0._Expressions(); b0._Call(); b0.VariableTest("name"); b0._Filter(); b0.Choose_(5); b0.Path_(3); b0.Filter_(); b0.ParentStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ElementRef"); b0._Filter(); b0.VariableRefStep("components"); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.ExpressionTest_(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#name"); b0.VariableTest("name"); b0._Filter(); b0._ExpressionTest(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ElementDecl"); b0._And(); b0._Filter(); b0._Path(); b0.Path_(3); b0.Filter_(); b0.ParentStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeUseRef"); b0._Filter(); b0.VariableRefStep("components"); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.ExpressionTest_(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#name"); b0.VariableTest("name"); b0._Filter(); b0._ExpressionTest(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeDecl"); b0._And(); b0._Filter(); b0._Path(); b0.Path_(3); b0.Filter_(); b0.ParentStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeGroupRef"); b0._Filter(); b0.VariableRefStep("components"); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.ExpressionTest_(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#name"); b0.VariableTest("name"); b0._Filter(); b0._ExpressionTest(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeGroupDef"); b0._And(); b0._Filter(); b0._Path(); b0.Path_(3); b0.Filter_(); b0.ParentStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ModelGroupRef"); b0._Filter(); b0.VariableRefStep("components"); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.ExpressionTest_(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#name"); b0.VariableTest("name"); b0._Filter(); b0._ExpressionTest(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ModelGroupDef"); b0._And(); b0._Filter(); b0._Path(); b0.Path_(2); b0.VariableRefStep("components"); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.ExpressionTest_(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#name"); b0.VariableTest("name"); b0._Filter(); b0._ExpressionTest(); b0.SubtypeTest("http://www.w3.org/2001/XMLSchema#TypeDef"); b0._And(); b0._Filter(); b0._Path(); b0._Choose(); b0._Block(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getSuperSimpleExtension"); b1.Resolver(); b0.Choose_(2); b0.If_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleExtension"); b0.SelfStep(); b0._If(); b0.Path_(5); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#base"); b0.KindTest("IMPL"); b0._Filter(); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#content"); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#derivation"); b0.Call_(); b0.Name("getSuperSimpleExtension"); b1.Resolver(); b0._Call(); b0._Path(); b0._Choose(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getSimpleBaseType"); b1.Resolver(); b0.Choose_(2); b0.Path_(2); b0.FeatureStep("content"); b0.Choose_(2); b0.Path_(3); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleContent"); b0._Filter(); b0.FeatureStep("derivation"); b0.FeatureStep("base"); b0._Path(); b0.FeatureStep("base"); b0._Choose(); b0._Path(); b0.Path_(3); b0.Filter_(); b0.SelfStep(); b0.And_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleRestriction"); b0.ExpressionTest_(); b0.Path_(2); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#facets"); b0.ChildStep(); b0._Path(); b0._ExpressionTest(); b0._And(); b0._Filter(); b0.Call_(); b0.Name("getSuperSimpleExtension"); b1.Resolver(); b0._Call(); b0.FeatureStep("base"); b0._Path(); b0._Choose(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getBaseType"); b1.Resolver(); b0.Block_(2); b0.QueryDeclaration_(); b0.Name("getComplexBaseType"); b1.Resolver(); b0.Path_(3); b0.Filter_(); b0.FeatureStep("content"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ComplexContent"); b0._Filter(); b0.FeatureStep("derivation"); b0.FeatureStep("base"); b0._Path(); b0._QueryDeclaration(); b0.Choose_(2); b0.Call_(); b0.Name("getComplexBaseType"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getSimpleBaseType"); b1.Resolver(); b0._Call(); b0._Choose(); b0._Block(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getExtensionBaseDataType"); b0.Names_(1); b0.Name("extension"); b0._Names(); b0.Block_(2); b0.Filter_(); b0.SelfStep(); b0.VariableTest("extension"); b0._Filter(); b0.Path_(2); b0.FeatureStep("base"); b0.Choose_(2); b0.Path_(2); b0.Call_(); b0.Name("isSchemaQName"); b1.Resolver(); b0._Call(); b0.VariableRefStep("extension"); b0._Path(); b0.Path_(3); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.FeatureStep("content"); b0.Choose_(2); b0.Path_(3); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleContent"); b0._Filter(); b0.FeatureStep("derivation"); b0.Call_(); b0.Name("getExtensionBaseDataType"); b1.Resolver(); b0._Call(); b0._Path(); b0.VariableRefStep("extension"); b0._Choose(); b0._Path(); b0._Choose(); b0._Path(); b0._Block(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getBuiltInType"); b1.Resolver(); b0.Path_(2); b0.Call_(); b0.Name("getSimpleBaseType"); b1.Resolver(); b0._Call(); b0.Choose_(2); b0.Path_(2); b0.Call_(); b0.Name("isSchemaQName"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getBasePart"); b1.Resolver(); b0._Call(); b0._Path(); b0.Path_(2); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getBuiltInType"); b1.Resolver(); b0._Call(); b0._Path(); b0._Choose(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getAppInfo"); b0.Names_(1); b0.Name("annotated"); b0._Names(); b0.Block_(2); b0.Filter_(); b0.SelfStep(); b0.VariableTest("annotated"); b0._Filter(); b0.Path_(7); b0.VariableRefStep("annotated"); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#annotation"); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#list"); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#Appinfo"); b0.ExpressionTest_(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#source"); b0.ExpressionTest_(); b1.StageUpFragment_(); org.whole.lang.xsd.builders.IXsdBuilder b5 = (org.whole.lang.xsd.builders.IXsdBuilder) op.wGetBuilder(org.whole.lang.xsd.reflect.XsdLanguageKit.URI); b5.AnyURI("http://lang.whole.org/Models"); b1._StageUpFragment(); b0._ExpressionTest(); b0._Filter(); b0._ExpressionTest(); b0._And(); b0._Filter(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#content"); b0.Filter_(); b0.ChildStep(); b0.SubtypeTest("http://lang.whole.org/Commons#Fragment"); b0._Filter(); b0.Filter_(); b0.FeatureStep("http://lang.whole.org/Commons#rootEntity"); b0.LanguageTest("http://lang.whole.org/Models"); b0._Filter(); b0._Path(); b0._Block(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("findAppInfo"); b1.Resolver(); b0.Path_(2); b0.Choose_(4); b0.Path_(4); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ModelGroupRef"); b0._Filter(); b0.FeatureStep("ref"); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.FeatureStep("modelGroup"); b0._Path(); b0.Path_(2); b0.FeatureStep("ref"); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0._Path(); b0.Path_(2); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ModelGroupDef"); b0._Filter(); b0.FeatureStep("modelGroup"); b0._Path(); b0.SelfStep(); b0._Choose(); b0.Call_(); b0.Name("getAppInfo"); b1.Resolver(); b0._Call(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("findAppInfoFeature"); b1.Resolver(); b0.Path_(2); b0.Call_(); b0.Name("findAppInfo"); b1.Resolver(); b0._Call(); b0.FeatureStep("name"); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("findAppInfoType"); b1.Resolver(); b0.Path_(2); b0.Call_(); b0.Name("findAppInfo"); b1.Resolver(); b0._Call(); b0.Choose_(2); b0.If_(); b0.TypeTest("http://lang.whole.org/Models#Feature"); b0.FeatureStep("type"); b0._If(); b0.SelfStep(); b0._Choose(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("findImportedAppInfoType"); b0.Names_(3); b0.Name("prefix"); b0.Name("uri"); b0.Name("schemaRegistry"); b0._Names(); b0.Addition_(); b0.Singleton_(); b0.Call_(); b0.Name("getUriPart"); b1.Resolver(); b0._Call(); b0._Singleton(); b0.Addition_(); b0.StringLiteral("#"); b0.Singleton_(); b0.Path_(3); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getAppInfo"); b1.Resolver(); b0._Call(); b0.Choose_(2); b0.FeatureStep("name"); b0.SelfStep(); b0._Choose(); b0._Path(); b0._Singleton(); b0._Addition(); b0._Addition(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("addAppInfo"); b0.Names_(1); b0.Name("contents"); b0._Names(); b0.Block_(2); b0.If_(); b0.ExpressionTest_(); b0.Path_(1); b0.VariableRefStep("contents"); b0._Path(); b0._ExpressionTest(); b0.PointwiseInsert_(); b0.Placement("INTO"); b0.Path_(2); b0.Choose_(2); b0.PointwiseUpdate_(); b0.Filter_(); b0.FeatureStep("annotation"); b0.KindTest("RESOLVER"); b0._Filter(); b1.StageUpFragment_(); b5.Annotation_(); b1.Resolver(); b1.Resolver(); b1.Resolver(); b5.AnnotationList_(0); b5._AnnotationList(); b5._Annotation(); b1._StageUpFragment(); b0._PointwiseUpdate(); b0.FeatureStep("annotation"); b0._Choose(); b0.FeatureStep("list"); b0._Path(); b1.StageUpFragment_(); b5.Appinfo_(); b1.Resolver(); b1.Resolver(); b1.Resolver(); b1.Resolver(); b5.AnnotationContents_(1); b1.SameStageFragment_(); b1.Variable_(); b1.VarType("http://lang.whole.org/Commons#Any"); b1.VarName("contents"); b1.Quantifier("!"); b1._Variable(); b1._SameStageFragment(); b5._AnnotationContents(); b5._Appinfo(); b1._StageUpFragment(); b0._PointwiseInsert(); b0._If(); b0.SelfStep(); b0._Block(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("cloneMappings"); b0.Names_(6); b0.Name("targetContextType"); b0.Name("sourceRef"); b0.Name("sourceContextType"); b0.Name("clonedMapping"); b0.Name("strategyRegistry"); b0.Name("lk"); b0._Names(); b0.Choose_(2); b0.If_(); b0.ExpressionTest_(); b0.Path_(2); b0.VariableRefStep("sourceRef"); b0.Call_(); b0.Name("isLocalQName"); b1.Resolver(); b0._Call(); b0._Path(); b0._ExpressionTest(); b0.Sequence_(2); b0.Path_(3); b0.VariableRefStep("sourceRef"); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("sourceContextType"); b0._Filter(); b0._Path(); b0.For_(); b0.Path_(3); b0.VariableRefStep("mappingStrategy"); b0.FeatureStep("http://xsd.lang.whole.org/Mapping#mappings"); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.SubtypeTest("http://xsd.lang.whole.org/Mapping#ContextMapping"); b0.ExpressionTest_(); b0.Equals_(); b0.Singleton_(); b0.FeatureStep("http://xsd.lang.whole.org/Mapping#contextEntityType"); b0._Singleton(); b0.VariableRefStep("sourceContextType"); b0._Equals(); b0._ExpressionTest(); b0._And(); b0._Filter(); b0._Path(); b0.Sequence_(3); b0.Filter_(); b1.SameStageFragment_(); b2.InvokeJavaClassMethod_(); b2.Text("clone mapping"); b1.Resolver(); b1.Resolver(); b2.StringLiteral("org.whole.lang.util.EntityUtils"); b2.StringLiteral("clone(org.whole.lang.model.IEntity)"); b2.Expressions_(1); b2.Variable("self"); b2._Expressions(); b2._InvokeJavaClassMethod(); b1._SameStageFragment(); b0.VariableTest("clonedMapping"); b0._Filter(); b0.PointwiseUpdate_(); b0.Path_(2); b0.VariableRefStep("clonedMapping"); b0.FeatureStep("http://xsd.lang.whole.org/Mapping#contextEntityType"); b0._Path(); b0.VariableRefStep("targetContextType"); b0._PointwiseUpdate(); b0.PointwiseInsert_(); b0.Placement("INTO"); b0.Path_(2); b0.VariableRefStep("mappingStrategy"); b0.FeatureStep("http://xsd.lang.whole.org/Mapping#mappings"); b0._Path(); b0.VariableRefStep("clonedMapping"); b0._PointwiseInsert(); b0._Sequence(); b0._For(); b0._Sequence(); b0._If(); b0.Do_(); b1.Resolver(); b0._Do(); b0._Choose(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getType"); b1.Resolver(); b0.Choose_(2); b0.Filter_(); b0.FeatureStep("simpleType"); b0.KindTest("IMPL"); b0._Filter(); b0.Filter_(); b0.FeatureStep("type"); b0.KindTest("IMPL"); b0._Filter(); b0._Choose(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getTypeDef"); b1.Resolver(); b0.Choose_(3); b0.Path_(2); b0.Call_(); b0.Name("getType"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0._Path(); b0.Filter_(); b0.FeatureStep("simpleTypeDef"); b0.KindTest("IMPL"); b0._Filter(); b0.Filter_(); b0.FeatureStep("typeDef"); b0.KindTest("IMPL"); b0._Filter(); b0._Choose(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getParticlesContainer"); b1.Resolver(); b0.Choose_(2); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ModelGroupDef"); b0._Filter(); b0.Path_(2); b0.FeatureStep("content"); b0.Choose_(2); b0.Path_(3); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ComplexContent"); b0._Filter(); b0.FeatureStep("derivation"); b0.FeatureStep("content"); b0._Path(); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#DeclaredContent"); b0._Filter(); b0._Choose(); b0._Path(); b0._Choose(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getDescendantParticles"); b1.Resolver(); b0.Path_(1); b0.Sequence_(2); b0.SelfStep(); b0.If_(); b0.SubtypeTest("http://www.w3.org/2001/XMLSchema#ModelGroupWithParticles"); b0.Path_(3); b0.FeatureStep("particles"); b0.ChildStep(); b0.Call_(); b0.Name("getDescendantParticles"); b1.Resolver(); b0._Call(); b0._Path(); b0._If(); b0._Sequence(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getComponentParticles"); b1.Resolver(); b0.Path_(3); b0.Call_(); b0.Name("getParticlesContainer"); b1.Resolver(); b0._Call(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#modelGroup"); b0.Call_(); b0.Name("getDescendantParticles"); b1.Resolver(); b0._Call(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getComponentChildParticles"); b1.Resolver(); b0.Path_(3); b0.Call_(); b0.Name("getParticlesContainer"); b1.Resolver(); b0._Call(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#modelGroup"); b0.Call_(); b0.Name("getChildParticles"); b1.Resolver(); b0._Call(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getChildParticles"); b1.Resolver(); b0.Path_(2); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#particles"); b0.ChildStep(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getLocalParticles"); b1.Resolver(); b0.Path_(2); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#particles"); b0.Filter_(); b0.ChildStep(); b0.Not_(); b0.SubtypeTest("http://www.w3.org/2001/XMLSchema#Reference"); b0._Not(); b0._Filter(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getReferencedParticles"); b1.Resolver(); b0.Path_(2); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#particles"); b0.Filter_(); b0.ChildStep(); b0.SubtypeTest("http://www.w3.org/2001/XMLSchema#Reference"); b0._Filter(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getComponentModelGroupWithParticles"); b1.Resolver(); b0.Filter_(); b0.Call_(); b0.Name("getComponentParticles"); b1.Resolver(); b0._Call(); b0.And_(2); b0.SubtypeTest("http://www.w3.org/2001/XMLSchema#ModelGroupWithParticles"); b0.KindTest("IMPL"); b0._And(); b0._Filter(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getBaseParticles"); b1.Resolver(); b0.Sequence_(2); b0.Path_(5); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#content"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ComplexContent"); b0._Filter(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#derivation"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ComplexExtension"); b0._Filter(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#base"); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getBaseParticles"); b1.Resolver(); b0._Call(); b0._Path(); b0.Path_(2); b0.Call_(); b0.Name("getParticlesContainer"); b1.Resolver(); b0._Call(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#modelGroup"); b0.KindTest("IMPL"); b0._Filter(); b0._Path(); b0._Sequence(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getAttributesContainer"); b1.Resolver(); b0.Path_(2); b0.FeatureStep("content"); b0.Choose_(3); b0.Path_(3); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ComplexContent"); b0._Filter(); b0.FeatureStep("derivation"); b0.FeatureStep("content"); b0._Path(); b0.Path_(2); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleContent"); b0._Filter(); b0.FeatureStep("derivation"); b0._Path(); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#DeclaredContent"); b0._Filter(); b0._Choose(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getAttributesGroupChildren"); b1.Resolver(); b0.Path_(5); b0.FeatureStep("ref"); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.FeatureStep("attributeUses"); b0.ChildStep(); b0.Choose_(2); b0.Path_(2); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeGroupRef"); b0._Filter(); b0.Call_(); b0.Name("getAttributesGroupChildren"); b1.Resolver(); b0._Call(); b0._Path(); b0.Filter_(); b0.SelfStep(); b0.Not_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeGroupRef"); b0._Not(); b0._Filter(); b0._Choose(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getLocalAttributes"); b1.Resolver(); b0.Path_(3); b0.Call_(); b0.Name("getAttributesContainer"); b1.Resolver(); b0._Call(); b0.FeatureStep("attributeUses"); b0.Filter_(); b0.ChildStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeUseDecl"); b0._Filter(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getReferencedAttributes"); b1.Resolver(); b0.Path_(4); b0.Call_(); b0.Name("getAttributesContainer"); b1.Resolver(); b0._Call(); b0.FeatureStep("attributeUses"); b0.Filter_(); b0.ChildStep(); b0.Not_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeUseDecl"); b0._Not(); b0._Filter(); b0.Choose_(2); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeUseRef"); b0._Filter(); b0.Call_(); b0.Name("getAttributesGroupChildren"); b1.Resolver(); b0._Call(); b0._Choose(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getDeclaredAttributes"); b1.Resolver(); b0.Sequence_(2); b0.Call_(); b0.Name("getReferencedAttributes"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getLocalAttributes"); b1.Resolver(); b0._Call(); b0._Sequence(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getInheritedAttributes"); b0.Names_(1); b0.Name("excluded"); b0._Names(); b0.Path_(3); b0.Call_(); b0.Name("getBaseType"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getAttributes"); b0.Expressions_(1); b0.VariableRefStep("excluded"); b0._Expressions(); b0._Call(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getAttributes"); b0.Names_(2); b0.Name("excluded"); b0.Name("declared"); b0._Names(); b0.Block_(3); b0.Filter_(); b0.Union_(); b0.Expressions_(0); b0._Expressions(); b1.Resolver(); b0._Union(); b0.VariableTest("excluded"); b0._Filter(); b0.Filter_(); b0.Except_(); b0.Expressions_(2); b0.Call_(); b0.Name("getDeclaredAttributes"); b1.Resolver(); b0._Call(); b0.Path_(2); b0.VariableRefStep("excluded"); b0.ChildStep(); b0._Path(); b0._Expressions(); b0.IdentityComparator_(); b0.FeatureStep("name"); b0._IdentityComparator(); b0._Except(); b0.VariableTest("declared"); b0._Filter(); b0.Sequence_(2); b0.CartesianInsert_(); b0.Placement("INTO"); b0.VariableRefStep("excluded"); b0.Path_(2); b0.VariableRefStep("declared"); b0.ChildStep(); b0._Path(); b0._CartesianInsert(); b0.Call_(); b0.Name("getInheritedAttributes"); b0.Expressions_(1); b0.VariableRefStep("excluded"); b0._Expressions(); b0._Call(); b0._Sequence(); b0._Block(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getAttributesGroupWildcards"); b1.Resolver(); b0.Path_(3); b0.FeatureStep("ref"); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.Sequence_(2); b0.Filter_(); b0.FeatureStep("anyAttribute"); b0.KindTest("IMPL"); b0._Filter(); b0.Path_(3); b0.FeatureStep("attributeUses"); b0.Filter_(); b0.ChildStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeGroupRef"); b0._Filter(); b0.Call_(); b0.Name("getAttributesGroupWildcards"); b1.Resolver(); b0._Call(); b0._Path(); b0._Sequence(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getLocalWildcardAttribute"); b1.Resolver(); b0.Path_(2); b0.Call_(); b0.Name("getAttributesContainer"); b1.Resolver(); b0._Call(); b0.Filter_(); b0.FeatureStep("anyAttribute"); b0.KindTest("IMPL"); b0._Filter(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getDeclaredWildcardAttribute"); b1.Resolver(); b0.Path_(2); b0.Call_(); b0.Name("getAttributesContainer"); b1.Resolver(); b0._Call(); b0.Sequence_(2); b0.Filter_(); b0.FeatureStep("anyAttribute"); b0.KindTest("IMPL"); b0._Filter(); b0.Path_(3); b0.FeatureStep("attributeUses"); b0.Filter_(); b0.ChildStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeGroupRef"); b0._Filter(); b0.Call_(); b0.Name("getAttributesGroupWildcards"); b1.Resolver(); b0._Call(); b0._Path(); b0._Sequence(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getInheritedWildcardAttribute"); b1.Resolver(); b0.Path_(3); b0.Call_(); b0.Name("getBaseType"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getWildcardAttribute"); b1.Resolver(); b0._Call(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("getWildcardAttribute"); b1.Resolver(); b0.Block_(2); b1.StageUpFragment_(); org.whole.lang.text.builders.ITextBuilder b6 = (org.whole.lang.text.builders.ITextBuilder) op.wGetBuilder(org.whole.lang.text.reflect.TextLanguageKit.URI); b6.Document_(2); b6.Row_(1); b6.Text("1. Implement wildcard namespaceSpecs intersection/union algorithms"); b6._Row(); b6.Row_(1); b6.Text("(currently the first anyAttribute in hierarchy is returned)"); b6._Row(); b6._Document(); b1._StageUpFragment(); b0.Filter_(); b0.Sequence_(2); b0.Call_(); b0.Name("getDeclaredWildcardAttribute"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getInheritedWildcardAttribute"); b1.Resolver(); b0._Call(); b0._Sequence(); b0.IndexTest_(); b0.IntLiteral(0); b0._IndexTest(); b0._Filter(); b0._Block(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("hasAttributes"); b1.Resolver(); b0.Filter_(); b0.Sequence_(2); b0.Call_(); b0.Name("getAttributes"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getWildcardAttribute"); b1.Resolver(); b0._Call(); b0._Sequence(); b0.IndexTest_(); b0.IntLiteral(0); b0._IndexTest(); b0._Filter(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("needsFeatureDeclarations"); b1.Resolver(); b0.Choose_(2); b0.Path_(2); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#content"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleContent"); b0._Filter(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#derivation"); b0.And_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleRestriction"); b0.Not_(); b0.ExpressionTest_(); b0.Path_(2); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#facets"); b0.ChildStep(); b0._Path(); b0._ExpressionTest(); b0._Not(); b0._And(); b0._Filter(); b0._Path(); b0.Path_(2); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#content"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ComplexContent"); b0._Filter(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#derivation"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ComplexRestriction"); b0._Filter(); b0._Path(); b0._Choose(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("isChoiceModelGroupDef"); b1.Resolver(); b0.Filter_(); b0.SelfStep(); b0.And_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ModelGroupDef"); b0.ExpressionTest_(); b0.Filter_(); b0.Call_(); b0.Name("getComponentModelGroupWithParticles"); b1.Resolver(); b0._Call(); b0.And_(2); b0.IndexTest_(); b0.IntLiteral(0); b0._IndexTest(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#Choice"); b0._And(); b0._Filter(); b0._ExpressionTest(); b0._And(); b0._Filter(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("isChoiceModelGroupRef"); b1.Resolver(); b0.Path_(3); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ModelGroupRef"); b0._Filter(); b0.FeatureStep("ref"); b0.Filter_(); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.ExpressionTest_(); b0.Call_(); b0.Name("isChoiceModelGroupDef"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0._Filter(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("hasImportedType"); b1.Resolver(); b0.Filter_(); b0.Choose_(3); b0.Path_(2); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ElementDecl"); b0._Filter(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#type"); b0._Path(); b0.Path_(2); b0.Filter_(); b0.SelfStep(); b0.SubtypeTest("http://www.w3.org/2001/XMLSchema#AttributeDecl"); b0._Filter(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#simpleType"); b0._Path(); b0.Path_(2); b0.Filter_(); b0.SelfStep(); b0.And_(2); b0.SubtypeTest("http://www.w3.org/2001/XMLSchema#Reference"); b0.Not_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeGroupRef"); b0._Not(); b0._And(); b0._Filter(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#ref"); b0._Path(); b0._Choose(); b0.And_(2); b0.KindTest("IMPL"); b0.ExpressionTest_(); b0.Call_(); b0.Name("isImportedQName"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0._And(); b0._Filter(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("allChoiceSubstitutions"); b1.Resolver(); b0.Path_(2); b0.Call_(); b0.Name("getChildParticles"); b1.Resolver(); b0._Call(); b0.Choose_(2); b0.Path_(4); b0.Filter_(); b0.SelfStep(); b0.ExpressionTest_(); b0.Call_(); b0.Name("isChoiceModelGroupRef"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0._Filter(); b0.FeatureStep("ref"); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("allChoiceModelGroupDefSubstitutions"); b1.Resolver(); b0._Call(); b0._Path(); b0.SelfStep(); b0._Choose(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("allChoiceModelGroupDefSubstitutions"); b1.Resolver(); b0.Path_(2); b0.Filter_(); b0.Call_(); b0.Name("getComponentModelGroupWithParticles"); b1.Resolver(); b0._Call(); b0.IndexTest_(); b0.IntLiteral(0); b0._IndexTest(); b0._Filter(); b0.Call_(); b0.Name("allChoiceSubstitutions"); b1.Resolver(); b0._Call(); b0._Path(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("mapsToCompositeEntity"); b1.Resolver(); b0.Choose_(2); b0.If_(); b0.And_(3); b0.TypeTest("http://www.w3.org/2001/XMLSchema#Sequence"); b0.Not_(); b0.ExpressionTest_(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#maxOccurs"); b0.ExpressionTest_(); b1.StageUpFragment_(); b5.Bounded(1); b1._StageUpFragment(); b0._ExpressionTest(); b0._Filter(); b0._ExpressionTest(); b0._Not(); b0.Not_(); b0.ExpressionTest_(); b0.Filter_(); b0.ParentStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ModelGroupDef"); b0._Filter(); b0._ExpressionTest(); b0._Not(); b0._And(); b0.BooleanLiteral(true); b0._If(); b0.Do_(); b0.BooleanLiteral(false); b0._Do(); b0._Choose(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("mapToModelDeclaration"); b0.Names_(7); b0.Name("eType"); b0.Name("cType"); b0.Name("features"); b0.Name("fName"); b0.Name("fType"); b0.Name("fModifier"); b0.Name("attributeFeatures"); b0._Names(); b0.Choose_(7); b0.If_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ElementDecl"); b0.Block_(2); b0.Call_(); b0.Name("addBuiltInModelDeclatration"); b0.Expressions_(1); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0._Expressions(); b0._Call(); b0.Path_(2); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#typeDef"); b0.Call_(); b0.Name("mapToModelDeclaration"); b1.Resolver(); b0._Call(); b0._Path(); b0._Block(); b0._If(); b0.If_(); b0.SubtypeTest("http://www.w3.org/2001/XMLSchema#AttributeDecl"); b0.Block_(2); b0.Call_(); b0.Name("addBuiltInModelDeclatration"); b0.Expressions_(1); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0._Expressions(); b0._Call(); b0.Path_(2); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#simpleTypeDef"); b0.Call_(); b0.Name("mapToModelDeclaration"); b1.Resolver(); b0._Call(); b0._Path(); b0._Block(); b0._If(); b0.If_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ComplexTypeDef"); b0.Sequence_(2); b0.Path_(2); b0.Sequence_(3); b0.Path_(2); b0.Call_(); b0.Name("getParticlesContainer"); b1.Resolver(); b0._Call(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#modelGroup"); b0._Path(); b0.Path_(3); b0.Filter_(); b0.SelfStep(); b0.Not_(); b0.ExpressionTest_(); b0.Call_(); b0.Name("needsFeatureDeclarations"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0._Not(); b0._Filter(); b0.Call_(); b0.Name("getDeclaredAttributes"); b1.Resolver(); b0._Call(); b0.Filter_(); b0.SelfStep(); b0.Not_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeUseRef"); b0._Not(); b0._Filter(); b0._Path(); b0.Path_(2); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#content"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleContent"); b0._Filter(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#derivation"); b0.And_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleRestriction"); b0.ExpressionTest_(); b0.Path_(2); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#facets"); b0.ChildStep(); b0._Path(); b0._ExpressionTest(); b0._And(); b0._Filter(); b0._Path(); b0._Sequence(); b0.Call_(); b0.Name("mapToModelDeclaration"); b1.Resolver(); b0._Call(); b0._Path(); b0.Select_(); b1.StageUpFragment_(); b3.SimpleEntity_(); b3.EntityModifiers_(0); b3._EntityModifiers(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("eType"); b1.Quantifier("!"); b1._Variable(); b3.Types_(0); b3._Types(); b3.Features_(2); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#Feature"); b1.VarName("attributeFeatures"); b1.Quantifier("*"); b1._Variable(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#Feature"); b1.VarName("features"); b1.Quantifier("*"); b1._Variable(); b3._Features(); b3._SimpleEntity(); b1._StageUpFragment(); b0.SelfStep(); b0.Sequence_(3); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("eType"); b0._Filter(); b0.Choose_(3); b0.Select_(); b0.Filter_(); b1.StageUpFragment_(); b3.Feature_(); b3.FeatureModifiers_(0); b3._FeatureModifiers(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("fType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("fName"); b1.Quantifier("!"); b1._Variable(); b1.Resolver(); b3._Feature(); b1._StageUpFragment(); b0.VariableTest("features"); b0._Filter(); b0.Path_(2); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#content"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleContent"); b0._Filter(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#derivation"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleExtension"); b0._Filter(); b0._Path(); b0.Sequence_(3); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("fType"); b0._Filter(); b0.Call_(); b0.Name("addBuiltInModelDeclatration"); b0.Expressions_(1); b0.VariableRefStep("fType"); b0._Expressions(); b0._Call(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoFeature"); b1.Resolver(); b0._Call(); b0.VariableTest("fName"); b0._Filter(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0.Select_(); b0.Filter_(); b1.StageUpFragment_(); b3.Feature_(); b3.FeatureModifiers_(0); b3._FeatureModifiers(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("fType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("fName"); b1.Quantifier("!"); b1._Variable(); b1.Resolver(); b3._Feature(); b1._StageUpFragment(); b0.VariableTest("features"); b0._Filter(); b0.Path_(2); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#content"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleContent"); b0._Filter(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#derivation"); b0.And_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleRestriction"); b0.ExpressionTest_(); b0.Path_(2); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#facets"); b0.ChildStep(); b0._Path(); b0._ExpressionTest(); b0._And(); b0._Filter(); b0._Path(); b0.Sequence_(2); b0.Path_(2); b0.Call_(); b0.Name("findAppInfo"); b1.Resolver(); b0._Call(); b0.Filter_(); b0.FeatureStep("http://lang.whole.org/Models#name"); b0.VariableTest("fType"); b0._Filter(); b0._Path(); b0.Path_(2); b0.Call_(); b0.Name("getSuperSimpleExtension"); b1.Resolver(); b0._Call(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoFeature"); b1.Resolver(); b0._Call(); b0.VariableTest("fName"); b0._Filter(); b0._Path(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0.Select_(); b0.Filter_(); b1.StageUpFragment_(); b3.Feature_(); b3.FeatureModifiers_(1); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#FeatureModifier"); b1.VarName("fModifier"); b1.Quantifier("*"); b1._Variable(); b3._FeatureModifiers(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("fType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("fName"); b1.Quantifier("!"); b1._Variable(); b1.Resolver(); b3._Feature(); b1._StageUpFragment(); b0.VariableTest("features"); b0._Filter(); b0.Path_(1); b0.Call_(); b0.Name("getBaseParticles"); b1.Resolver(); b0._Call(); b0._Path(); b0.Sequence_(3); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("fType"); b0._Filter(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoFeature"); b1.Resolver(); b0._Call(); b0.VariableTest("fName"); b0._Filter(); b0.If_(); b0.ExpressionTest_(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#minOccurs"); b0.ExpressionTest_(); b1.StageUpFragment_(); b5.Bounded(0); b1._StageUpFragment(); b0._ExpressionTest(); b0._Filter(); b0._ExpressionTest(); b0.Filter_(); b1.StageUpFragment_(); b3.FeatureModifier("optional"); b1._StageUpFragment(); b0.VariableTest("fModifier"); b0._Filter(); b0._If(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0._Choose(); b0.Select_(); b0.Filter_(); b1.StageUpFragment_(); b3.Feature_(); b3.FeatureModifiers_(1); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#FeatureModifier"); b1.VarName("fModifier"); b1.Quantifier("*"); b1._Variable(); b3._FeatureModifiers(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("fType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("fName"); b1.Quantifier("!"); b1._Variable(); b1.Resolver(); b3._Feature(); b1._StageUpFragment(); b0.VariableTest("attributeFeatures"); b0._Filter(); b0.Path_(2); b0.Filter_(); b0.SelfStep(); b0.Not_(); b0.ExpressionTest_(); b0.Call_(); b0.Name("needsFeatureDeclarations"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0._Not(); b0._Filter(); b0.Call_(); b0.Name("getDeclaredAttributes"); b1.Resolver(); b0._Call(); b0._Path(); b0.Sequence_(2); b0.Path_(2); b0.Choose_(2); b0.Path_(3); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeUseRef"); b0._Filter(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#ref"); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0._Path(); b0.SelfStep(); b0._Choose(); b0.Sequence_(2); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("fType"); b0._Filter(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoFeature"); b1.Resolver(); b0._Call(); b0.VariableTest("fName"); b0._Filter(); b0._Sequence(); b0._Path(); b0.If_(); b0.ExpressionTest_(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#use"); b0.ExpressionTest_(); b1.StageUpFragment_(); b5.Use("optional"); b1._StageUpFragment(); b0._ExpressionTest(); b0._Filter(); b0._ExpressionTest(); b0.Filter_(); b1.StageUpFragment_(); b3.FeatureModifier("optional"); b1._StageUpFragment(); b0.VariableTest("fModifier"); b0._Filter(); b0._If(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0._Sequence(); b0._If(); b0.If_(); b0.Or_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#Sequence"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#All"); b0._Or(); b0.Sequence_(2); b0.Path_(2); b0.Call_(); b0.Name("getChildParticles"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("mapToModelDeclaration"); b1.Resolver(); b0._Call(); b0._Path(); b0.Choose_(2); b0.If_(); b0.ExpressionTest_(); b0.Singleton_(); b0.Call_(); b0.Name("mapsToCompositeEntity"); b1.Resolver(); b0._Call(); b0._Singleton(); b0._ExpressionTest(); b0.Select_(); b1.StageUpFragment_(); b3.CompositeEntity_(); b3.EntityModifiers_(0); b3._EntityModifiers(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("eType"); b1.Quantifier("!"); b1._Variable(); b3.Types_(0); b3._Types(); b3.ComponentModifiers_(1); b3.ComponentModifier("ordered"); b3._ComponentModifiers(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("cType"); b1.Quantifier("?"); b1._Variable(); b3._CompositeEntity(); b1._StageUpFragment(); b0.SelfStep(); b0.Sequence_(2); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("eType"); b0._Filter(); b0.Path_(2); b0.Call_(); b0.Name("getChildParticles"); b1.Resolver(); b0._Call(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("cType"); b0._Filter(); b0._Path(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0._If(); b0.Select_(); b1.StageUpFragment_(); b3.SimpleEntity_(); b3.EntityModifiers_(0); b3._EntityModifiers(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("eType"); b1.Quantifier("!"); b1._Variable(); b3.Types_(0); b3._Types(); b3.Features_(1); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#Feature"); b1.VarName("features"); b1.Quantifier("*"); b1._Variable(); b3._Features(); b3._SimpleEntity(); b1._StageUpFragment(); b0.SelfStep(); b0.Sequence_(2); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("eType"); b0._Filter(); b0.Select_(); b0.Filter_(); b1.StageUpFragment_(); b3.Feature_(); b3.FeatureModifiers_(1); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#FeatureModifier"); b1.VarName("fModifier"); b1.Quantifier("*"); b1._Variable(); b3._FeatureModifiers(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("fType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("fName"); b1.Quantifier("!"); b1._Variable(); b1.Resolver(); b3._Feature(); b1._StageUpFragment(); b0.VariableTest("features"); b0._Filter(); b0.Call_(); b0.Name("getChildParticles"); b1.Resolver(); b0._Call(); b0.Sequence_(3); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("fType"); b0._Filter(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoFeature"); b1.Resolver(); b0._Call(); b0.VariableTest("fName"); b0._Filter(); b0.If_(); b0.ExpressionTest_(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#minOccurs"); b0.ExpressionTest_(); b1.StageUpFragment_(); b5.Bounded(0); b1._StageUpFragment(); b0._ExpressionTest(); b0._Filter(); b0._ExpressionTest(); b0.Filter_(); b1.StageUpFragment_(); b3.FeatureModifier("optional"); b1._StageUpFragment(); b0.VariableTest("fModifier"); b0._Filter(); b0._If(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0._Choose(); b0._Sequence(); b0._If(); b0.If_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#Choice"); b0.Sequence_(2); b0.Select_(); b1.StageUpFragment_(); b3.SimpleEntity_(); b3.EntityModifiers_(1); b3.EntityModifier("abstract"); b3._EntityModifiers(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("eType"); b1.Quantifier("!"); b1._Variable(); b3.Types_(0); b3._Types(); b3.Features_(0); b3._Features(); b3._SimpleEntity(); b1._StageUpFragment(); b0.SelfStep(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("eType"); b0._Filter(); b0.TemplateNames(); b0._Select(); b0.Path_(2); b0.Call_(); b0.Name("getChildParticles"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("mapToModelDeclaration"); b1.Resolver(); b0._Call(); b0._Path(); b0._Sequence(); b0._If(); b0.If_(); b0.Or_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleTypeDef"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleRestriction"); b0._Or(); b0.Block_(2); b0.PointwiseInsert_(); b0.Placement("INTO"); b0.VariableRefStep("mappedCustomDataTypes"); b0.Call_(); b0.Name("mapToDataType"); b1.Resolver(); b0._Call(); b0._PointwiseInsert(); b0.Call_(); b0.Name("findAppInfo"); b1.Resolver(); b0._Call(); b0._Block(); b0._If(); b0.If_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ModelGroupDef"); b0.Path_(2); b0.Call_(); b0.Name("getComponentChildParticles"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("mapToModelDeclaration"); b1.Resolver(); b0._Call(); b0._Path(); b0._If(); b0._Choose(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("mapToMapping"); b0.Names_(8); b0.Name("contextStack"); b0.Name("ncname"); b0.Name("entityType"); b0.Name("newContextStack"); b0.Name("context"); b0.Name("previousContext"); b0.Name("contextEntityType"); b0.Name("featureType"); b0._Names(); b0.Choose_(12); b0.If_(); b0.And_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ElementDecl"); b0.Not_(); b0.ExpressionTest_(); b0.Path_(1); b0.VariableRefStep("contextStack"); b0._Path(); b0._ExpressionTest(); b0._Not(); b0._And(); b0.Sequence_(2); b0.Select_(); b1.StageUpFragment_(); b4.RootMapping_(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#NCName"); b1.VarName("ncname"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("entityType"); b1.Quantifier("!"); b1._Variable(); b4._RootMapping(); b1._StageUpFragment(); b0.SelfStep(); b0.Sequence_(2); b0.Filter_(); b0.FeatureStep("name"); b0.VariableTest("ncname"); b0._Filter(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("entityType"); b0._Filter(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0.Path_(2); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#typeDef"); b0.Call_(); b0.Name("mapToMapping"); b1.Resolver(); b0._Call(); b0._Path(); b0._Sequence(); b0._If(); b0.If_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ComplexTypeDef"); b0.Block_(2); b0.Filter_(); b0.Union_(); b0.Expressions_(1); b0.SelfStep(); b0._Expressions(); b1.Resolver(); b0._Union(); b0.VariableTest("newContextStack"); b0._Filter(); b0.Path_(2); b0.Sequence_(2); b0.Choose_(2); b0.Path_(1); b0.Call_(); b0.Name("getBaseParticles"); b1.Resolver(); b0._Call(); b0._Path(); b0.Path_(2); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#content"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleContent"); b0._Filter(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#derivation"); b0.Or_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleExtension"); b0.And_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleRestriction"); b0.ExpressionTest_(); b0.Path_(2); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#facets"); b0.ChildStep(); b0._Path(); b0._ExpressionTest(); b0._And(); b0._Or(); b0._Filter(); b0._Path(); b0._Choose(); b0.Path_(3); b0.Filter_(); b0.SelfStep(); b0.Not_(); b0.ExpressionTest_(); b0.Call_(); b0.Name("needsFeatureDeclarations"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0._Not(); b0._Filter(); b0.Sequence_(2); b0.Call_(); b0.Name("getInheritedAttributes"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getDeclaredAttributes"); b1.Resolver(); b0._Call(); b0._Sequence(); b0.Choose_(2); b0.Path_(3); b0.Filter_(); b0.SelfStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#AttributeUseRef"); b0._Filter(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#ref"); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0._Path(); b0.SelfStep(); b0._Choose(); b0._Path(); b0._Sequence(); b0.Call_(); b0.Name("mapToMapping"); b0.Expressions_(1); b0.VariableRefStep("newContextStack"); b0._Expressions(); b0._Call(); b0._Path(); b0._Block(); b0._If(); b0.If_(); b0.Or_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ElementRef"); b0.TypeTest("http://www.w3.org/2001/XMLSchema#ElementDecl"); b0._Or(); b0.Block_(2); b0.Filter_(); b0.Call_(); b0.Name("getName"); b1.Resolver(); b0._Call(); b0.VariableTest("ncname"); b0._Filter(); b0.Sequence_(3); b0.Select_(); b1.StageUpFragment_(); b4.StructuralMapping_(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("contextEntityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#NCName"); b1.VarName("ncname"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("entityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("featureType"); b1.Quantifier("?"); b1._Variable(); b4._StructuralMapping(); b1._StageUpFragment(); b0.Path_(2); b0.VariableRefStep("contextStack"); b0.PointwiseProduct_(2); b0.Filter_(); b0.ChildStep(); b0.VariableTest("previousContext"); b0._Filter(); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.IndexRangeTest_(); b0.IntLiteral(1); b1.Resolver(); b0._IndexRangeTest(); b0.VariableTest("context"); b0._And(); b0._Filter(); b0._PointwiseProduct(); b0._Path(); b0.Sequence_(3); b0.Path_(2); b0.VariableRefStep("context"); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("contextEntityType"); b0._Filter(); b0._Path(); b0.Path_(2); b0.VariableRefStep("previousContext"); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("entityType"); b0._Filter(); b0._Path(); b0.If_(); b0.Not_(); b0.ExpressionTest_(); b0.Singleton_(); b0.Path_(2); b0.VariableRefStep("context"); b0.Call_(); b0.Name("mapsToCompositeEntity"); b1.Resolver(); b0._Call(); b0._Path(); b0._Singleton(); b0._ExpressionTest(); b0._Not(); b0.Path_(2); b0.VariableRefStep("previousContext"); b0.Filter_(); b0.Choose_(2); b0.If_(); b0.And_(2); b0.ExpressionTest_(); b0.Path_(2); b0.ParentStep(); b0.Filter_(); b0.ParentStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#Choice"); b0._Filter(); b0._Path(); b0._ExpressionTest(); b0.ExpressionTest_(); b0.Singleton_(); b0.Path_(1); b0.Call_(); b0.Name("mapsToCompositeEntity"); b1.Resolver(); b0._Call(); b0._Path(); b0._Singleton(); b0._ExpressionTest(); b0._And(); b0.Path_(3); b0.ParentStep(); b0.ParentStep(); b0.Call_(); b0.Name("findAppInfoFeature"); b1.Resolver(); b0._Call(); b0._Path(); b0._If(); b0.Do_(); b0.Call_(); b0.Name("findAppInfoFeature"); b1.Resolver(); b0._Call(); b0._Do(); b0._Choose(); b0.VariableTest("featureType"); b0._Filter(); b0._Path(); b0._If(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0.Select_(); b1.StageUpFragment_(); b4.ElementMapping_(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("contextEntityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#NCName"); b1.VarName("ncname"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("entityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("featureType"); b1.Quantifier("?"); b1._Variable(); b4._ElementMapping(); b1._StageUpFragment(); b0.SelfStep(); b0.Sequence_(4); b0.Path_(2); b0.VariableRefStep("contextStack"); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.IndexTest_(); b0.IntLiteral(0); b0._IndexTest(); b0.VariableTest("context"); b0._And(); b0._Filter(); b0._Path(); b0.Path_(2); b0.VariableRefStep("context"); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("contextEntityType"); b0._Filter(); b0._Path(); b0.Filter_(); b0.Choose_(3); b0.Path_(2); b0.Filter_(); b0.VariableRefStep("ncname"); b0.And_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#QName"); b0.Not_(); b0.ExpressionTest_(); b0.Call_(); b0.Name("isLocalQNameù"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0._Not(); b0._And(); b0._Filter(); b0.Addition_(); b0.Singleton_(); b0.Call_(); b0.Name("getUriPart"); b1.Resolver(); b0._Call(); b0._Singleton(); b0.Addition_(); b0.StringLiteral("#"); b0.Singleton_(); b0.Path_(3); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("getAppInfo"); b1.Resolver(); b0._Call(); b0.FeatureStep("type"); b0._Path(); b0._Singleton(); b0._Addition(); b0._Addition(); b0._Path(); b0.Path_(2); b0.Call_(); b0.Name("hasImportedType"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("findImportedAppInfoType"); b1.Resolver(); b0._Call(); b0._Path(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0._Choose(); b0.VariableTest("entityType"); b0._Filter(); b0.If_(); b0.Not_(); b0.ExpressionTest_(); b0.Singleton_(); b0.Path_(2); b0.VariableRefStep("context"); b0.Call_(); b0.Name("mapsToCompositeEntity"); b1.Resolver(); b0._Call(); b0._Path(); b0._Singleton(); b0._ExpressionTest(); b0._Not(); b0.Filter_(); b0.Choose_(2); b0.Call_(); b0.Name("findAppInfoFeature"); b1.Resolver(); b0._Call(); b0.Path_(3); b0.ParentStep(); b0.ParentStep(); b0.Call_(); b0.Name("findAppInfoFeature"); b1.Resolver(); b0._Call(); b0._Path(); b0._Choose(); b0.VariableTest("featureType"); b0._Filter(); b0._If(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0.Path_(2); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#typeDef"); b0.Call_(); b0.Name("mapToMapping"); b1.Resolver(); b0._Call(); b0._Path(); b0._Sequence(); b0._Block(); b0._If(); b0.If_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#Any"); b0.Sequence_(2); b0.Select_(); b1.StageUpFragment_(); b4.AnyStructuralMapping_(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("contextEntityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("entityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("featureType"); b1.Quantifier("?"); b1._Variable(); b4._AnyStructuralMapping(); b1._StageUpFragment(); b0.Path_(2); b0.VariableRefStep("contextStack"); b0.PointwiseProduct_(2); b0.Filter_(); b0.ChildStep(); b0.VariableTest("previousContext"); b0._Filter(); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.IndexRangeTest_(); b0.IntLiteral(1); b1.Resolver(); b0._IndexRangeTest(); b0.VariableTest("context"); b0._And(); b0._Filter(); b0._PointwiseProduct(); b0._Path(); b0.Sequence_(3); b0.Path_(2); b0.VariableRefStep("context"); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("contextEntityType"); b0._Filter(); b0._Path(); b0.Path_(2); b0.VariableRefStep("previousContext"); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("entityType"); b0._Filter(); b0._Path(); b0.If_(); b0.Not_(); b0.ExpressionTest_(); b0.Singleton_(); b0.Path_(2); b0.VariableRefStep("context"); b0.Call_(); b0.Name("mapsToCompositeEntity"); b1.Resolver(); b0._Call(); b0._Path(); b0._Singleton(); b0._ExpressionTest(); b0._Not(); b0.Path_(2); b0.VariableRefStep("previousContext"); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoFeature"); b1.Resolver(); b0._Call(); b0.VariableTest("featureType"); b0._Filter(); b0._Path(); b0._If(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0.Select_(); b1.StageUpFragment_(); b4.AnyElementMapping_(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("contextEntityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("entityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("featureType"); b1.Quantifier("?"); b1._Variable(); b4._AnyElementMapping(); b1._StageUpFragment(); b0.SelfStep(); b0.Sequence_(4); b0.Path_(2); b0.VariableRefStep("contextStack"); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.IndexTest_(); b0.IntLiteral(0); b0._IndexTest(); b0.VariableTest("context"); b0._And(); b0._Filter(); b0._Path(); b0.Path_(2); b0.VariableRefStep("context"); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("contextEntityType"); b0._Filter(); b0._Path(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("entityType"); b0._Filter(); b0.If_(); b0.Not_(); b0.ExpressionTest_(); b0.Singleton_(); b0.Path_(2); b0.VariableRefStep("context"); b0.Call_(); b0.Name("mapsToCompositeEntity"); b1.Resolver(); b0._Call(); b0._Path(); b0._Singleton(); b0._ExpressionTest(); b0._Not(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoFeature"); b1.Resolver(); b0._Call(); b0.VariableTest("featureType"); b0._Filter(); b0._If(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0._Sequence(); b0._If(); b0.If_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleExtension"); b0.Select_(); b1.StageUpFragment_(); b4.ContentMapping_(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("contextEntityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("entityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("featureType"); b1.Quantifier("!"); b1._Variable(); b4._ContentMapping(); b1._StageUpFragment(); b0.SelfStep(); b0.Sequence_(4); b0.Path_(2); b0.VariableRefStep("contextStack"); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.IndexTest_(); b0.IntLiteral(0); b0._IndexTest(); b0.VariableTest("context"); b0._And(); b0._Filter(); b0._Path(); b0.Path_(2); b0.VariableRefStep("context"); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("contextEntityType"); b0._Filter(); b0._Path(); b0.Path_(2); b0.Call_(); b0.Name("getExtensionBaseDataType"); b1.Resolver(); b0._Call(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("entityType"); b0._Filter(); b0._Path(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoFeature"); b1.Resolver(); b0._Call(); b0.VariableTest("featureType"); b0._Filter(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0._If(); b0.If_(); b0.And_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleRestriction"); b0.ExpressionTest_(); b0.Path_(2); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#facets"); b0.ChildStep(); b0._Path(); b0._ExpressionTest(); b0._And(); b0.Select_(); b1.StageUpFragment_(); b4.ContentMapping_(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("contextEntityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("entityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("featureType"); b1.Quantifier("!"); b1._Variable(); b4._ContentMapping(); b1._StageUpFragment(); b0.SelfStep(); b0.Sequence_(4); b0.Path_(2); b0.VariableRefStep("contextStack"); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.IndexTest_(); b0.IntLiteral(0); b0._IndexTest(); b0.VariableTest("context"); b0._And(); b0._Filter(); b0._Path(); b0.Path_(2); b0.VariableRefStep("context"); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("contextEntityType"); b0._Filter(); b0._Path(); b0.Path_(2); b0.Call_(); b0.Name("findAppInfo"); b1.Resolver(); b0._Call(); b0.Filter_(); b0.FeatureStep("http://lang.whole.org/Models#name"); b0.VariableTest("entityType"); b0._Filter(); b0._Path(); b0.Path_(2); b0.Call_(); b0.Name("getSuperSimpleExtension"); b1.Resolver(); b0._Call(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoFeature"); b1.Resolver(); b0._Call(); b0.VariableTest("featureType"); b0._Filter(); b0._Path(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0._If(); b0.If_(); b0.And_(2); b0.SubtypeTest("http://www.w3.org/2001/XMLSchema#AttributeDecl"); b0.ExpressionTest_(); b0.Path_(1); b0.VariableRefStep("contextStack"); b0._Path(); b0._ExpressionTest(); b0._And(); b0.Select_(); b1.StageUpFragment_(); b4.AttributeMapping_(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("contextEntityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#NCName"); b1.VarName("ncname"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("entityType"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("featureType"); b1.Quantifier("!"); b1._Variable(); b4._AttributeMapping(); b1._StageUpFragment(); b0.SelfStep(); b0.Sequence_(5); b0.Filter_(); b0.Call_(); b0.Name("getName"); b1.Resolver(); b0._Call(); b0.VariableTest("ncname"); b0._Filter(); b0.Path_(2); b0.VariableRefStep("contextStack"); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.IndexTest_(); b0.IntLiteral(0); b0._IndexTest(); b0.VariableTest("context"); b0._And(); b0._Filter(); b0._Path(); b0.Path_(2); b0.VariableRefStep("context"); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("contextEntityType"); b0._Filter(); b0._Path(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.VariableTest("entityType"); b0._Filter(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfoFeature"); b1.Resolver(); b0._Call(); b0.VariableTest("featureType"); b0._Filter(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0._If(); b0.If_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#Sequence"); b0.Block_(2); b0.Filter_(); b0.Choose_(2); b0.If_(); b0.ExpressionTest_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0.Union_(); b0.Expressions_(2); b0.SelfStep(); b0.Path_(2); b0.VariableRefStep("contextStack"); b0.ChildStep(); b0._Path(); b0._Expressions(); b1.Resolver(); b0._Union(); b0._If(); b0.Do_(); b0.VariableRefStep("contextStack"); b0._Do(); b0._Choose(); b0.VariableTest("newContextStack"); b0._Filter(); b0.Path_(2); b0.Call_(); b0.Name("getChildParticles"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("mapToMapping"); b0.Expressions_(1); b0.VariableRefStep("newContextStack"); b0._Expressions(); b0._Call(); b0._Path(); b0._Block(); b0._If(); b0.If_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#All"); b0.Block_(2); b0.Filter_(); b0.Choose_(2); b0.If_(); b0.ExpressionTest_(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0.Union_(); b0.Expressions_(2); b0.SelfStep(); b0.Path_(2); b0.VariableRefStep("contextStack"); b0.ChildStep(); b0._Path(); b0._Expressions(); b1.Resolver(); b0._Union(); b0._If(); b0.Do_(); b0.VariableRefStep("contextStack"); b0._Do(); b0._Choose(); b0.VariableTest("newContextStack"); b0._Filter(); b0.Path_(2); b0.Call_(); b0.Name("getChildParticles"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("mapToMapping"); b0.Expressions_(1); b0.VariableRefStep("newContextStack"); b0._Expressions(); b0._Call(); b0._Path(); b0._Block(); b0._If(); b0.If_(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#Choice"); b0.Path_(2); b0.Call_(); b0.Name("allChoiceSubstitutions"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("mapToMapping"); b0.Expressions_(1); b0.VariableRefStep("contextStack"); b0._Expressions(); b0._Call(); b0._Path(); b0._If(); b0.If_(); b0.ExpressionTest_(); b0.Call_(); b0.Name("isChoiceModelGroupRef"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0.Path_(4); b0.FeatureStep("ref"); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("allChoiceModelGroupDefSubstitutions"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("mapToMapping"); b0.Expressions_(1); b0.VariableRefStep("contextStack"); b0._Expressions(); b0._Call(); b0._Path(); b0._If(); b0.Do_(); b0.VoidLiteral(); b0._Do(); b0._Choose(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("mapToDataType"); b0.Names_(6); b0.Name("enumerations"); b0.Name("entityType"); b0.Name("index"); b0.Name("enumValues"); b0.Name("enumValue"); b0.Name("value"); b0._Names(); b0.Block_(2); b0.QueryDeclaration_(); b0.Name("mapsToEnumEntity"); b1.Resolver(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfo"); b1.Resolver(); b0._Call(); b0.TypeTest("http://lang.whole.org/Models#EnumEntity"); b0._Filter(); b0._QueryDeclaration(); b0.Choose_(2); b0.Select_(); b1.StageUpFragment_(); b4.EnumDataType_(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("entityType"); b1.Quantifier("!"); b1._Variable(); b4.EnumValues_(1); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#EnumValue"); b1.VarName("enumValues"); b1.Quantifier("+"); b1._Variable(); b4._EnumValues(); b4._EnumDataType(); b1._StageUpFragment(); b0.Path_(2); b0.Filter_(); b0.SelfStep(); b0.And_(2); b0.ExpressionTest_(); b0.Call_(); b0.Name("mapsToEnumEntity"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0.ExpressionTest_(); b0.Path_(2); b0.Choose_(2); b0.Path_(2); b0.Filter_(); b0.SelfStep(); b0.And_(1); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleTypeDef"); b0._And(); b0._Filter(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#content"); b0._Path(); b0.Filter_(); b0.SelfStep(); b0.And_(1); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleRestriction"); b0._And(); b0._Filter(); b0._Choose(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#facets"); b0.VariableTest("enumerations"); b0._Filter(); b0._Path(); b0._ExpressionTest(); b0._And(); b0._Filter(); b0.Filter_(); b0.Call_(); b0.Name("getAppInfo"); b1.Resolver(); b0._Call(); b0.ExpressionTest_(); b0.Filter_(); b0.FeatureStep("name"); b0.VariableTest("entityType"); b0._Filter(); b0._ExpressionTest(); b0._Filter(); b0._Path(); b0.Select_(); b0.Filter_(); b1.StageUpFragment_(); b4.EnumValue_(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#Value"); b1.VarName("enumValue"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#Value"); b1.VarName("value"); b1.Quantifier("!"); b1._Variable(); b4._EnumValue(); b1._StageUpFragment(); b0.VariableTest("enumValues"); b0._Filter(); b0.Path_(2); b0.FeatureStep("values"); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.IndexVariableTest("index"); b0.VariableTest("enumValue"); b0._And(); b0._Filter(); b0._Path(); b0.Path_(3); b0.VariableRefStep("enumerations"); b0.Filter_(); b0.ChildStep(); b0.And_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#Enumeration"); b0.IndexVariableTest("index"); b0._And(); b0._Filter(); b0.Filter_(); b0.FeatureStep("value"); b0.VariableTest("value"); b0._Filter(); b0._Path(); b0.TemplateNames(); b0._Select(); b0.TemplateNames(); b0._Select(); b0.Path_(1); b0.Call_(); b0.Name("getCustomDataType"); b0.Expressions_(2); b0.Path_(2); b0.Call_(); b0.Name("findAppInfo"); b1.Resolver(); b0._Call(); b0.FeatureStep("name"); b0._Path(); b0.Call_(); b0.Name("getBuiltInType"); b1.Resolver(); b0._Call(); b0._Expressions(); b0._Call(); b0._Path(); b0._Choose(); b0._Block(); b0._QueryDeclaration(); b0.QueryDeclaration_(); b0.Name("addSubtype"); b0.Names_(2); b0.Name("subType"); b0.Name("superType"); b0._Names(); b0.PointwiseInsert_(); b0.Placement("INTO"); b0.Path_(4); b0.VariableRefStep("model"); b0.FeatureStep("http://lang.whole.org/Models#declarations"); b0.Filter_(); b0.ChildStep(); b0.ExpressionTest_(); b0.Filter_(); b0.FeatureStep("http://lang.whole.org/Models#name"); b0.VariableTest("subType"); b0._Filter(); b0._ExpressionTest(); b0._Filter(); b0.Filter_(); b0.FeatureStep("http://lang.whole.org/Models#types"); b0.Not_(); b0.ExpressionTest_(); b0.Filter_(); b0.ChildStep(); b0.VariableTest("superType"); b0._Filter(); b0._ExpressionTest(); b0._Not(); b0._Filter(); b0._Path(); b0.VariableRefStep("superType"); b0._PointwiseInsert(); b0._QueryDeclaration(); b0.Select_(); b0.Tuple_(2); b0.Filter_(); b1.StageUpFragment_(); b3.Model_(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#SimpleName"); b1.VarName("fileName"); b1.Quantifier("!"); b1._Variable(); b3.TypeRelations_(0); b3._TypeRelations(); b3.ModelDeclarations_(2); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#ModelDeclaration"); b1.VarName("modelDeclarations"); b1.Quantifier("*"); b1._Variable(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#ModelDeclaration"); b1.VarName("builtInModelDeclarations"); b1.Quantifier("*"); b1._Variable(); b3._ModelDeclarations(); b3.Namespace("org.whole.lang.xsi"); b1.Resolver(); b1.Variable_(); b1.VarType("http://lang.whole.org/Models#URI"); b1.VarName("languageURI"); b1.Quantifier("!"); b1._Variable(); b3._Model(); b1._StageUpFragment(); b0.VariableTest("model"); b0._Filter(); b0.Filter_(); b1.StageUpFragment_(); b4.MappingStrategy_(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("languageURI"); b1.Quantifier("!"); b1._Variable(); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#URI"); b1.VarName("fileLocationURI"); b1.Quantifier("!"); b1._Variable(); b4.BooleanType(false); b4.BooleanType(true); b4.BooleanType(false); b1.Resolver(); b1.Resolver(); b4.Mappings_(1); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#Mapping"); b1.VarName("mappings"); b1.Quantifier("*"); b1._Variable(); b4._Mappings(); b4.DataTypes_(1); b1.Variable_(); b1.VarType("http://xsd.lang.whole.org/Mapping#DataType"); b1.VarName("customDataTypes"); b1.Quantifier("*"); b1._Variable(); b4._DataTypes(); b4._MappingStrategy(); b1._StageUpFragment(); b0.VariableTest("mappingStrategy"); b0._Filter(); b0._Tuple(); b0.SelfStep(); b0.Sequence_(4); b0.Filter_(); b0.Choose_(2); b0.If_(); b0.Not_(); b0.ExpressionTest_(); b0.Equals_(); b0.VariableRefStep("TARGET_NS_URI"); b0.StringLiteral(""); b0._Equals(); b0._ExpressionTest(); b0._Not(); b0.VariableRefStep("TARGET_NS_URI"); b0._If(); b0.Do_(); b1.SameStageFragment_(); b2.Sequence_(); b2.Text("sequence"); b2.FlowObjects_(1); b2.InvokeJavaClassMethod_(); b2.Text("calculate internal namespace"); b1.Resolver(); b1.Resolver(); b2.StringLiteral("org.whole.lang.xsd.util.NamespaceUtils"); b2.StringLiteral("calculateInternalNamespace(boolean)"); b1.Resolver(); b2._InvokeJavaClassMethod(); b2._FlowObjects(); b2._Sequence(); b1._SameStageFragment(); b0._Do(); b0._Choose(); b0.VariableTest("languageURI"); b0._Filter(); b0.Path_(3); b0.FeatureStep("components"); b0.ChildStep(); b0.Sequence_(2); b0.Filter_(); b0.Call_(); b0.Name("mapToMapping"); b1.Resolver(); b0._Call(); b0.VariableTest("mappings"); b0._Filter(); b0.Filter_(); b0.Call_(); b0.Name("mapToModelDeclaration"); b1.Resolver(); b0._Call(); b0.VariableTest("modelDeclarations"); b0._Filter(); b0._Sequence(); b0._Path(); b0.Path_(2); b0.VariableRefStep("mappedBuiltInTypes"); b0.Filter_(); b0.ChildStep(); b0.VariableTest("builtInModelDeclarations"); b0._Filter(); b0._Path(); b0.Path_(2); b0.VariableRefStep("mappedCustomDataTypes"); b0.Filter_(); b0.ChildStep(); b0.VariableTest("customDataTypes"); b0._Filter(); b0._Path(); b0._Sequence(); b0.TemplateNames(); b0._Select(); b0.Path_(2); b0.Filter_(); b0.DescendantStep(); b0.TypeTest("http://www.w3.org/2001/XMLSchema#Choice"); b0._Filter(); b0.Block_(2); b0.Filter_(); b0.Choose_(2); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.Path_(2); b0.ParentStep(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0._Path(); b0._Choose(); b0.VariableTest("sType"); b0._Filter(); b0.Path_(3); b0.Call_(); b0.Name("getChildParticles"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("addSubtype"); b0.Expressions_(2); b0.SelfStep(); b0.VariableRefStep("sType"); b0._Expressions(); b0._Call(); b0._Path(); b0._Block(); b0._Path(); b0.Path_(2); b0.Filter_(); b0.DescendantStep(); b0.Or_(2); b0.SubtypeTest("http://www.w3.org/2001/XMLSchema#ComplexDerivation"); b0.And_(3); b0.SubtypeTest("http://www.w3.org/2001/XMLSchema#SimpleDerivation"); b0.ExpressionTest_(); b0.Filter_(); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#base"); b0.Not_(); b0.ExpressionTest_(); b0.Call_(); b0.Name("isSchemaQName"); b1.Resolver(); b0._Call(); b0._ExpressionTest(); b0._Not(); b0._Filter(); b0._ExpressionTest(); b0.Not_(); b0.ExpressionTest_(); b0.Path_(3); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#base"); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.Filter_(); b0.Call_(); b0.Name("findAppInfo"); b1.Resolver(); b0._Call(); b0.Or_(2); b0.TypeTest("http://lang.whole.org/Models#DataEntity"); b0.TypeTest("http://lang.whole.org/Models#EnumEntity"); b0._Or(); b0._Filter(); b0._Path(); b0._ExpressionTest(); b0._Not(); b0._And(); b0._Or(); b0._Filter(); b0.Call_(); b0.Name("addSubtype"); b0.Expressions_(2); b0.Path_(3); b0.ParentStep(); b0.ParentStep(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0._Path(); b0.Path_(3); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#base"); b0.Call_(); b0.Name("getComponent"); b1.Resolver(); b0._Call(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0._Path(); b0._Expressions(); b0._Call(); b0._Path(); b0.Path_(2); b0.Filter_(); b0.DescendantStep(); b0.And_(2); b0.TypeTest("http://www.w3.org/2001/XMLSchema#SimpleRestriction"); b0.Not_(); b0.ExpressionTest_(); b0.Path_(2); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#facets"); b0.ChildStep(); b0._Path(); b0._ExpressionTest(); b0._Not(); b0._And(); b0._Filter(); b0.Call_(); b0.Name("cloneMappings"); b0.Expressions_(2); b0.Path_(3); b0.ParentStep(); b0.ParentStep(); b0.Call_(); b0.Name("findAppInfoType"); b1.Resolver(); b0._Call(); b0._Path(); b0.Path_(1); b0.FeatureStep("http://www.w3.org/2001/XMLSchema#base"); b0._Path(); b0._Expressions(); b0._Call(); b0._Path(); b0.Tuple_(2); b0.VariableRefStep("model"); b0.VariableRefStep("mappingStrategy"); b0._Tuple(); b0._Block(); }
diff --git a/wcs1_1/src/main/java/org/geoserver/wcs/DefaultWebCoverageService111.java b/wcs1_1/src/main/java/org/geoserver/wcs/DefaultWebCoverageService111.java index 364a43237..ca2f22b8e 100644 --- a/wcs1_1/src/main/java/org/geoserver/wcs/DefaultWebCoverageService111.java +++ b/wcs1_1/src/main/java/org/geoserver/wcs/DefaultWebCoverageService111.java @@ -1,846 +1,846 @@ package org.geoserver.wcs; import static org.vfny.geoserver.wcs.WcsException.WcsExceptionCode.*; import java.awt.geom.AffineTransform; import java.io.IOException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TimeZone; import java.util.logging.Level; import java.util.logging.Logger; import javax.media.jai.Interpolation; import net.opengis.ows11.BoundingBoxType; import net.opengis.ows11.CodeType; import net.opengis.wcs11.AxisSubsetType; import net.opengis.wcs11.DescribeCoverageType; import net.opengis.wcs11.DomainSubsetType; import net.opengis.wcs11.FieldSubsetType; import net.opengis.wcs11.GetCapabilitiesType; import net.opengis.wcs11.GetCoverageType; import net.opengis.wcs11.GridCrsType; import net.opengis.wcs11.OutputType; import net.opengis.wcs11.RangeSubsetType; import net.opengis.wcs11.TimePeriodType; import net.opengis.wcs11.TimeSequenceType; import org.geoserver.catalog.Catalog; import org.geoserver.catalog.CoverageDimensionInfo; import org.geoserver.catalog.CoverageInfo; import org.geoserver.config.GeoServer; import org.geoserver.data.util.CoverageUtils; import org.geoserver.ows.util.RequestUtils; import org.geoserver.wcs.kvp.GridCS; import org.geoserver.wcs.kvp.GridType; import org.geoserver.wcs.response.DescribeCoverageTransformer; import org.geoserver.wcs.response.WCSCapsTransformer; import org.geotools.coverage.grid.GeneralGridGeometry; import org.geotools.coverage.grid.GridCoverage2D; import org.geotools.coverage.grid.GridGeometry2D; import org.geotools.coverage.grid.io.AbstractGridCoverage2DReader; import org.geotools.coverage.grid.io.AbstractGridFormat; import org.geotools.geometry.GeneralEnvelope; import org.geotools.gml2.bindings.GML2EncodingUtils; import org.geotools.parameter.DefaultParameterDescriptor; import org.geotools.referencing.CRS; import org.geotools.referencing.operation.transform.AffineTransform2D; import org.geotools.referencing.operation.transform.IdentityTransform; import org.geotools.util.logging.Logging; import org.opengis.coverage.grid.GridCoverage; import org.opengis.geometry.Envelope; import org.opengis.parameter.GeneralParameterDescriptor; import org.opengis.parameter.GeneralParameterValue; import org.opengis.parameter.ParameterValue; import org.opengis.parameter.ParameterValueGroup; import org.opengis.referencing.crs.CoordinateReferenceSystem; import org.opengis.referencing.crs.GeographicCRS; import org.opengis.referencing.cs.AxisDirection; import org.opengis.referencing.cs.CoordinateSystemAxis; import org.opengis.referencing.datum.PixelInCell; import org.opengis.referencing.operation.CoordinateOperation; import org.opengis.referencing.operation.CoordinateOperationFactory; import org.opengis.referencing.operation.MathTransform; import org.vfny.geoserver.util.WCSUtils; import org.vfny.geoserver.wcs.WcsException; import org.vfny.geoserver.wcs.WcsException.WcsExceptionCode; import org.vfny.geoserver.wcs.responses.CoverageResponseDelegate; import org.vfny.geoserver.wcs.responses.CoverageResponseDelegateFactory; public class DefaultWebCoverageService111 implements WebCoverageService111 { Logger LOGGER = Logging.getLogger(DefaultWebCoverageService111.class); private Catalog catalog; private GeoServer geoServer; public DefaultWebCoverageService111(GeoServer geoServer) { this.geoServer = geoServer; this.catalog = geoServer.getCatalog(); } public WCSInfo getServiceInfo() { return geoServer.getService(WCSInfo.class); } public WCSCapsTransformer getCapabilities(GetCapabilitiesType request) { // do the version negotiation dance List<String> provided = new ArrayList<String>(); // provided.add("1.0.0"); provided.add("1.1.0"); provided.add("1.1.1"); List<String> accepted = null; if (request.getAcceptVersions() != null) accepted = request.getAcceptVersions().getVersion(); String version = RequestUtils.getVersionOws11(provided, accepted); // TODO: add support for 1.0.0 in here if ("1.1.0".equals(version) || "1.1.1".equals(version)) { WCSCapsTransformer capsTransformer = new WCSCapsTransformer(geoServer); capsTransformer.setEncoding(Charset.forName((getServiceInfo().getGeoServer().getGlobal().getCharset()))); return capsTransformer; } throw new WcsException("Could not understand version:" + version); } public DescribeCoverageTransformer describeCoverage(DescribeCoverageType request) { final String version = request.getVersion(); if ("1.1.0".equals(version) || "1.1.1".equals(version)) { WCSInfo wcs = getServiceInfo(); DescribeCoverageTransformer describeTransformer = new DescribeCoverageTransformer(wcs, catalog); describeTransformer.setEncoding(Charset.forName(wcs.getGeoServer().getGlobal().getCharset())); return describeTransformer; } throw new WcsException("Could not understand version:" + version); } @SuppressWarnings({ "deprecation", "unchecked" }) public GridCoverage[] getCoverage(GetCoverageType request) { if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.finest(new StringBuffer("execute CoverageRequest response. Called request is: ").append(request).toString()); } WCSInfo wcs = getServiceInfo(); CoverageInfo meta = null; GridCoverage2D coverage = null; try { CodeType identifier = request.getIdentifier(); if (identifier == null) throw new WcsException("Internal error, the coverage identifier must not be null", InvalidParameterValue, "identifier"); meta = catalog.getCoverageByName(identifier.getValue()); if (meta == null) { throw new WcsException("No such coverage: " + request.getIdentifier().getValue()); } // first let's run some sanity checks on the inputs checkDomainSubset(meta, request.getDomainSubset(), wcs); checkRangeSubset(meta, request.getRangeSubset()); checkOutput(meta, request.getOutput()); // grab the format, the reader using the default params final AbstractGridCoverage2DReader reader = (AbstractGridCoverage2DReader) meta.getGridCoverageReader(null, WCSUtils.getReaderHints(wcs)); // handle spatial domain subset, if needed final GeneralEnvelope originalEnvelope = reader.getOriginalEnvelope(); final BoundingBoxType bbox = request.getDomainSubset().getBoundingBox(); final CoordinateReferenceSystem nativeCRS = originalEnvelope.getCoordinateReferenceSystem(); final GeneralEnvelope requestedEnvelopeInSourceCRS; final GeneralEnvelope requestedEnvelope; MathTransform bboxToNativeTx=null; if (bbox != null) { // first off, parse the envelope corners double[] lowerCorner = new double[bbox.getLowerCorner().size()]; double[] upperCorner = new double[bbox.getUpperCorner().size()]; for (int i = 0; i < lowerCorner.length; i++) { lowerCorner[i] = (Double) bbox.getLowerCorner().get(i); upperCorner[i] = (Double) bbox.getUpperCorner().get(i); } requestedEnvelope = new GeneralEnvelope(lowerCorner, upperCorner); // grab the native crs // if no crs has beens specified, the native one is assumed if (bbox.getCrs() == null) { requestedEnvelope.setCoordinateReferenceSystem(nativeCRS); requestedEnvelopeInSourceCRS = requestedEnvelope; } else { // otherwise we need to transform final CoordinateReferenceSystem bboxCRS = CRS.decode(bbox.getCrs()); requestedEnvelope.setCoordinateReferenceSystem(bboxCRS); bboxToNativeTx = CRS.findMathTransform(bboxCRS, nativeCRS,true); if(!bboxToNativeTx.isIdentity()){ requestedEnvelopeInSourceCRS = CRS.transform(bboxToNativeTx,requestedEnvelope); requestedEnvelopeInSourceCRS.setCoordinateReferenceSystem(nativeCRS); } else requestedEnvelopeInSourceCRS= new GeneralEnvelope(requestedEnvelope); } } else { requestedEnvelopeInSourceCRS = reader.getOriginalEnvelope(); requestedEnvelope = requestedEnvelopeInSourceCRS; } final GridCrsType gridCRS = request.getOutput().getGridCRS(); // Compute the target crs, the crs that the final coverage will be // served into final CoordinateReferenceSystem targetCRS; if (gridCRS == null) targetCRS = reader.getOriginalEnvelope().getCoordinateReferenceSystem(); else targetCRS = CRS.decode(gridCRS.getGridBaseCRS()); // // Raster destination size // int elevationLevels=0; double[] elevations = null; // grab the grid to world transformation MathTransform gridToCRS = reader.getOriginalGridToWorld(PixelInCell.CELL_CORNER); if (gridCRS != null) { Double[] origin = (Double[]) gridCRS.getGridOrigin(); Double[] offsets = (Double[]) gridCRS.getGridOffsets(); // from the specification if grid origin is omitted and the crs // is 2d the default it's 0,0 if (origin == null) { origin = new Double[] { 0.0, 0.0 }; } // if no offsets has been specified we try to default on the // native ones if (offsets == null) { if (!(gridToCRS instanceof AffineTransform2D)&& !(gridToCRS instanceof IdentityTransform)) throw new WcsException( "Internal error, the coverage we're playing with does not have an affine transform..."); if (gridToCRS instanceof IdentityTransform) { if (gridCRS.getGridType().equals(GridType.GT2dSimpleGrid.getXmlConstant()) || gridCRS.getGridType().equals(GridType.GT2dGridIn2dCrs.getXmlConstant())) offsets = new Double[] { 1.0, 1.0 }; else offsets = new Double[] { 1.0, 0.0, 0.0, 0.0, 1.0, 0.0 }; } else { AffineTransform2D affine = (AffineTransform2D) gridToCRS; if (gridCRS.getGridType().equals(GridType.GT2dSimpleGrid.getXmlConstant()) || gridCRS.getGridType().equals(GridType.GT2dGridIn2dCrs.getXmlConstant())) offsets = new Double[] { affine.getScaleX(), affine.getScaleY() }; else offsets = new Double[] { affine.getScaleX(), affine.getShearX(), affine.getShearY(), affine.getScaleY() }; } } // building the actual transform for the resulting grid geometry AffineTransform tx; if (gridCRS.getGridType().equals(GridType.GT2dSimpleGrid.getXmlConstant())) { tx = new AffineTransform( offsets[0], 0, 0, offsets[1], origin[0], origin[1] ); } else if(gridCRS.getGridType().equals(GridType.GT2dGridIn2dCrs.getXmlConstant())) { tx = new AffineTransform( offsets[0], offsets[1], offsets[2], offsets[3], origin[0], origin[1] ); } else { tx = new AffineTransform( offsets[0], offsets[4], offsets[1], offsets[3], origin[0], origin[1] ); if (origin.length != 3 || offsets.length != 6) throw new WcsException("", InvalidParameterValue, "GridCRS"); // // ELEVATIONS // // TODO: draft code ... it needs more study! elevationLevels = (int) Math.round(requestedEnvelope.getUpperCorner().getOrdinate(2) - requestedEnvelope.getLowerCorner().getOrdinate(2)); // compute the elevation levels, we have elevationLevels values if (elevationLevels > 0) { elevations=new double[elevationLevels]; elevations[0]=requestedEnvelope.getLowerCorner().getOrdinate(2); // TODO put the extrema elevations[elevationLevels-1]=requestedEnvelope.getUpperCorner().getOrdinate(2); if(elevationLevels>2){ final int adjustedLevelsNum=elevationLevels-1; double step = (elevations[elevationLevels-1]-elevations[0])/adjustedLevelsNum; for(int i=1;i<adjustedLevelsNum;i++) elevations[i]=elevations[i-1]+step; } } } gridToCRS = new AffineTransform2D(tx); } // // TIME Values // final List<Date> timeValues = new LinkedList<Date>(); TimeSequenceType temporalSubset = request.getDomainSubset().getTemporalSubset(); if (temporalSubset != null && temporalSubset.getTimePosition() != null && temporalSubset.getTimePosition().size() > 0) { for (Iterator it = temporalSubset.getTimePosition().iterator(); it.hasNext(); ) { Date tp = (Date) it.next(); timeValues.add(tp); } } else if (temporalSubset != null && temporalSubset.getTimePeriod() != null && temporalSubset.getTimePeriod().size() > 0) { for (Iterator it = temporalSubset.getTimePeriod().iterator(); it.hasNext(); ) { TimePeriodType tp = (TimePeriodType) it.next(); Date beginning = (Date)tp.getBeginPosition(); Date ending = (Date)tp.getEndPosition(); timeValues.add(beginning); timeValues.add(ending); } } // now we have enough info to read the coverage, grab the parameters // and add the grid geometry info final GeneralEnvelope intersectionEnvelopeInSourceCRS = new GeneralEnvelope(requestedEnvelopeInSourceCRS); intersectionEnvelopeInSourceCRS.intersect(originalEnvelope); final GeneralEnvelope intersectionEnvelope= bboxToNativeTx.isIdentity()? new GeneralEnvelope(intersectionEnvelopeInSourceCRS): CRS.transform(bboxToNativeTx.inverse(), intersectionEnvelopeInSourceCRS); intersectionEnvelope.setCoordinateReferenceSystem(targetCRS); final GridGeometry2D requestedGridGeometry = new GridGeometry2D(PixelInCell.CELL_CORNER, gridToCRS, intersectionEnvelopeInSourceCRS, null); final ParameterValueGroup readParametersDescriptor = reader.getFormat().getReadParameters(); GeneralParameterValue[] readParameters = CoverageUtils.getParameters(readParametersDescriptor, meta.getParameters()); readParameters = (readParameters != null ? readParameters : new GeneralParameterValue[0]); // // Setting coverage reading params. // final ParameterValue requestedGridGeometryParam = new DefaultParameterDescriptor(AbstractGridFormat.READ_GRIDGEOMETRY2D.getName().toString(), GeneralGridGeometry.class, null, requestedGridGeometry).createValue(); /* * Test if the parameter "TIME" is present in the WMS * request, and by the way in the reading parameters. If * it is the case, one can adds it to the request. If an * exception is thrown, we have nothing to do. */ final List<GeneralParameterDescriptor> parameterDescriptors = readParametersDescriptor.getDescriptor().descriptors(); ParameterValue time=null; boolean hasTime=timeValues.size()>0; ParameterValue elevation=null; boolean hasElevation=elevations != null && !Double.isNaN(elevations[0]); if(hasElevation||hasTime){ for(GeneralParameterDescriptor pd:parameterDescriptors){ final String code=pd.getName().getCode(); // // TIME // if(code.equalsIgnoreCase("TIME")){ time=(ParameterValue) pd.createValue(); time.setValue(timeValues); } // // ELEVATION // if(code.equalsIgnoreCase("ELEVATION")){ elevation=(ParameterValue) pd.createValue(); elevation.setValue(elevations[0]); } // leave? if((hasElevation&&elevation!=null&&hasTime&&time!=null)|| !hasElevation&&hasTime&&time!=null|| hasElevation&&elevation!=null&&!hasTime) break; } } // // add read parameters // int addedParams=1+(hasTime?1:0)+(hasElevation?1:0); // add to the list GeneralParameterValue[] readParametersClone = new GeneralParameterValue[readParameters.length+addedParams--]; System.arraycopy(readParameters, 0,readParametersClone , 0, readParameters.length); readParametersClone[readParameters.length+addedParams--]=requestedGridGeometryParam; if(hasTime) readParametersClone[readParameters.length+addedParams--]=time; if(hasElevation) readParametersClone[readParameters.length+addedParams--]=elevation; readParameters=readParametersClone; // Check we're not being requested to read too much data from input (first check, // guesses the grid size using the information contained in CoverageInfo) WCSUtils.checkInputLimits(wcs, meta, reader, requestedGridGeometry); // // perform Read ... // coverage = (GridCoverage2D) reader.read(readParameters); if ((coverage == null) || !(coverage instanceof GridCoverage2D)) { throw new IOException("The requested coverage could not be found."); } // now that we have read the coverage double check the input size WCSUtils.checkInputLimits(wcs, coverage); /** * Band Select (works on just one field) */ GridCoverage2D bandSelectedCoverage = coverage; String interpolationType = null; if (request.getRangeSubset() != null) { if (request.getRangeSubset().getFieldSubset().size() > 1) { throw new WcsException("Multi field coverages are not supported yet"); } FieldSubsetType field = (FieldSubsetType) request.getRangeSubset().getFieldSubset().get(0); interpolationType = field.getInterpolationType(); // handle axis subset if (field.getAxisSubset().size() > 1) { throw new WcsException("Multi axis coverages are not supported yet"); } if (field.getAxisSubset().size() == 1) { // prepare a support structure to quickly get the band index // of a // key List<CoverageDimensionInfo> dimensions = meta.getDimensions(); Map<String, Integer> dimensionMap = new HashMap<String, Integer>(); for (int i = 0; i < dimensions.size(); i++) { String keyName = dimensions.get(i).getName().replace(' ', '_'); dimensionMap.put(keyName, i); } // extract the band indexes AxisSubsetType axisSubset = (AxisSubsetType) field.getAxisSubset().get(0); List keys = axisSubset.getKey(); int[] bands = new int[keys.size()]; for (int j = 0; j < bands.length; j++) { final String key = (String) keys.get(j); Integer index = dimensionMap.get(key); if (index == null) throw new WcsException("Unknown field/axis/key combination " + field.getIdentifier().getValue() + "/" + axisSubset.getIdentifier() + "/" + key); bands[j] = index; } // finally execute the band select try { bandSelectedCoverage = (GridCoverage2D) WCSUtils .bandSelect(coverage, bands); } catch (WcsException e) { throw new WcsException(e.getLocalizedMessage()); } } } /** * Checking for supported Interpolation Methods */ Interpolation interpolation = Interpolation.getInstance(Interpolation.INTERP_NEAREST); if (interpolationType != null) { if (interpolationType.equalsIgnoreCase("bilinear")) { interpolation = Interpolation.getInstance(Interpolation.INTERP_BILINEAR); } else if (interpolationType.equalsIgnoreCase("bicubic")) { interpolation = Interpolation.getInstance(Interpolation.INTERP_BICUBIC); } else if (interpolationType.equalsIgnoreCase("nearest")) { interpolation = Interpolation.getInstance(Interpolation.INTERP_NEAREST); } } /** * Reproject */ // adjust the grid geometry to use the final bbox and crs final GridGeometry2D destinationGridGeometry = new GridGeometry2D(PixelInCell.CELL_CORNER, gridToCRS, intersectionEnvelope, null); // before extracting the output make sure it's not too big WCSUtils.checkOutputLimits(wcs, destinationGridGeometry.getGridRange2D(), bandSelectedCoverage.getRenderedImage().getSampleModel()); // reproject if necessary - if(!CRS.equalsIgnoreMetadata(nativeCRS, targetCRS)) { + if(!CRS.equalsIgnoreMetadata(nativeCRS, targetCRS) || !bandSelectedCoverage.getGridGeometry().equals(destinationGridGeometry)) { final GridCoverage2D reprojectedCoverage = WCSUtils.resample( bandSelectedCoverage, nativeCRS, targetCRS, destinationGridGeometry,interpolation); return new GridCoverage[] { reprojectedCoverage }; } else { return new GridCoverage[] { bandSelectedCoverage }; } } catch (Throwable e) { if (e instanceof WcsException) throw (WcsException) e; else throw new WcsException(e); } } private void checkDomainSubset(CoverageInfo meta, DomainSubsetType domainSubset, WCSInfo wcs) throws Exception { BoundingBoxType bbox = domainSubset.getBoundingBox(); // workaround for http://jira.codehaus.org/browse/GEOT-1710 if("urn:ogc:def:crs:OGC:1.3:CRS84".equals(bbox.getCrs())) bbox.setCrs("EPSG:4326"); CoordinateReferenceSystem bboxCRs = CRS.decode(bbox.getCrs()); Envelope gridEnvelope = meta.getGridCoverage(null, WCSUtils.getReaderHints(wcs)).getEnvelope(); GeneralEnvelope gridEnvelopeBboxCRS = null; if (bboxCRs instanceof GeographicCRS) { try { CoordinateOperationFactory cof = CRS.getCoordinateOperationFactory(true); final CoordinateOperation operation = cof.createOperation(gridEnvelope .getCoordinateReferenceSystem(), bboxCRs); gridEnvelopeBboxCRS = CRS.transform(operation, gridEnvelope); } catch (Exception e) { // this may happen, there is nothing we can do about it, we just // use the back transformed envelope to be more lenient about // which coordinate coorections to make on the longitude axis // should the antimeridian style be used } } // check the coordinates, but make sure the case 175,-175 is handled // as valid for the longitude axis in a geographic coordinate system // see section 7.6.2 of the WCS 1.1.1 spec) List<Double> lower = bbox.getLowerCorner(); List<Double> upper = bbox.getUpperCorner(); for (int i = 0; i < lower.size(); i++) { if (lower.get(i) > upper.get(i)) { final CoordinateSystemAxis axis = bboxCRs.getCoordinateSystem().getAxis(i); // see if the coordinates can be fixed if (bboxCRs instanceof GeographicCRS && axis.getDirection() == AxisDirection.EAST) { if (gridEnvelopeBboxCRS != null) { // try to guess which one needs to be fixed final double envMax = gridEnvelopeBboxCRS.getMaximum(i); if (envMax >= lower.get(i)) upper.set(i, upper.get(i) + (axis.getMaximumValue() - axis.getMinimumValue())); else lower.set(i, lower.get(i) - (axis.getMaximumValue() - axis.getMinimumValue())); } else { // just fix the upper and hope... upper.set(i, upper.get(i) + (axis.getMaximumValue() - axis.getMinimumValue())); } } // if even after the fix we're in the wrong situation, complain if (lower.get(i) > upper.get(i)) { throw new WcsException("illegal bbox, min of dimension " + (i + 1) + ": " + lower.get(i) + " is " + "greater than max of same dimension: " + upper.get(i), WcsExceptionCode.InvalidParameterValue, "BoundingBox"); } } } } /** * Checks that the elements of the Output part of the request do make sense * by comparing them to the coverage metadata * * @param info * @param rangeSubset */ private void checkOutput(CoverageInfo meta, OutputType output) { if (output == null) return; String format = output.getFormat(); String declaredFormat = getDeclaredFormat(meta.getSupportedFormats(), format); if (declaredFormat == null) throw new WcsException("format " + format + " is not supported for this coverage", InvalidParameterValue, "format"); final GridCrsType gridCRS = output.getGridCRS(); if (gridCRS != null) { // check grid base crs is valid, and eventually default it out String gridBaseCrs = gridCRS.getGridBaseCRS(); if (gridBaseCrs != null) { // make sure the requested is among the supported ones, by // making a // code level // comparison (to avoid assuming epsg:xxxx and // http://www.opengis.net/gml/srs/epsg.xml#xxx are different // ones. // We'll also consider the urn one comparable, allowing eventual // axis flip on the // geographic crs String actualCRS = null; final String gridBaseCrsCode = extractCode(gridBaseCrs); for (Iterator it = meta.getResponseSRS().iterator(); it.hasNext();) { final String responseCRS = (String) it.next(); final String code = extractCode(responseCRS); if (code.equalsIgnoreCase(gridBaseCrsCode)) { actualCRS = responseCRS; } } if (actualCRS == null) throw new WcsException("CRS " + gridBaseCrs + " is not among the supported ones for coverage " + meta.getName(), WcsExceptionCode.InvalidParameterValue, "GridBaseCrs"); gridCRS.setGridBaseCRS(gridBaseCrs); } else { String code = GML2EncodingUtils.epsgCode(meta.getCRS()); gridCRS.setGridBaseCRS("urn:x-ogc:def:crs:EPSG:" + code); } // check grid type makes sense and apply default otherwise String gridTypeValue = gridCRS.getGridType(); GridType type = GridType.GT2dGridIn2dCrs; if (gridTypeValue != null) { type = null; for (GridType gt : GridType.values()) { if (gt.getXmlConstant().equalsIgnoreCase(gridTypeValue)) type = gt; } if (type == null) throw new WcsException("Unknown grid type " + gridTypeValue, InvalidParameterValue, "GridType"); else if (type == GridType.GT2dGridIn3dCrs) throw new WcsException("Unsupported grid type " + gridTypeValue, InvalidParameterValue, "GridType"); } gridCRS.setGridType(type.getXmlConstant()); // check gridcs and apply only value we know about String gridCS = gridCRS.getGridCS(); if (gridCS != null) { if (!gridCS.equalsIgnoreCase(GridCS.GCSGrid2dSquare.getXmlConstant())) throw new WcsException("Unsupported grid cs " + gridCS, InvalidParameterValue, "GridCS"); } gridCRS.setGridCS(GridCS.GCSGrid2dSquare.getXmlConstant()); // check the grid origin and set defaults CoordinateReferenceSystem crs = null; try { crs = CRS.decode(gridCRS.getGridBaseCRS()); } catch (Exception e) { throw new WcsException("Could not understand crs " + gridCRS.getGridBaseCRS(), WcsExceptionCode.InvalidParameterValue, "GridBaseCRS"); } if (!gridCRS.isSetGridOrigin() || gridCRS.getGridOrigin() == null) { // if not set, we have a default of "0 0" as a string, since I // cannot // find a way to make it default to new Double[] {0 0} I'll fix // it here Double[] origin = new Double[type.getOriginArrayLength()]; Arrays.fill(origin, 0.0); gridCRS.setGridOrigin(origin); } else { Double[] gridOrigin = (Double[]) gridCRS.getGridOrigin(); // make sure the origin dimension matches the output crs // dimension if (gridOrigin.length != type.getOriginArrayLength()) throw new WcsException("Grid origin size (" + gridOrigin.length + ") inconsistent with grid type " + type.getXmlConstant() + " that requires (" + type.getOriginArrayLength() + ")", WcsExceptionCode.InvalidParameterValue, "GridOrigin"); gridCRS.setGridOrigin(gridOrigin); } // perform same checks on the offsets Double[] gridOffsets = (Double[]) gridCRS.getGridOffsets(); if (gridOffsets != null) { // make sure the origin dimension matches the grid type if (type.getOffsetArrayLength() != gridOffsets.length) throw new WcsException("Invalid offsets lenght, grid type " + type.getXmlConstant() + " requires " + type.getOffsetArrayLength(), InvalidParameterValue, "GridOffsets"); } else { gridCRS.setGridOffsets(null); } } } /** * Extracts only the final part of an EPSG code allowing for a specification * independent comparison (that is, it removes the EPSG:, urn:xxx:, * http://... prefixes) * * @param srsName * @return */ private String extractCode(String srsName) { if (srsName.startsWith("http://www.opengis.net/gml/srs/epsg.xml#")) return srsName.substring(40); else if (srsName.startsWith("urn:")) return srsName.substring(srsName.lastIndexOf(':') + 1); else if (srsName.startsWith("EPSG:")) return srsName.substring(5); else return srsName; } /** * Checks if the supported format string list contains the specified format, * doing a case insensitive search. If found the declared output format name * is returned, otherwise null is returned. * * @param supportedFormats * @param format * @return */ private String getDeclaredFormat(List supportedFormats, String format) { // supported formats may be setup using old style formats, first scan // the // configured list for (Iterator it = supportedFormats.iterator(); it.hasNext();) { String sf = (String) it.next(); if (sf.equalsIgnoreCase(format)) { return sf; } else { CoverageResponseDelegate delegate = CoverageResponseDelegateFactory.encoderFor(sf); if (delegate != null && delegate.canProduce(format)) return sf; } } return null; } /** * Checks that the elements of the RangeSubset part of the request do make * sense by comparing them to the coverage metadata * * @param info * @param rangeSubset */ private void checkRangeSubset(CoverageInfo info, RangeSubsetType rangeSubset) { // quick escape if no range subset has been specified (it's legal) if (rangeSubset == null) return; if (rangeSubset.getFieldSubset().size() > 1) { throw new WcsException("Multi field coverages are not supported yet", InvalidParameterValue, "RangeSubset"); } // check field identifier FieldSubsetType field = (FieldSubsetType) rangeSubset.getFieldSubset().get(0); final String fieldId = field.getIdentifier().getValue(); if (!fieldId.equalsIgnoreCase("contents")) throw new WcsException("Unknown field " + fieldId, InvalidParameterValue, "RangeSubset"); // check interpolation String interpolation = field.getInterpolationType(); if (interpolation != null) { boolean interpolationSupported = false; if (interpolation.equalsIgnoreCase("nearest")) { interpolation = "nearest neighbor"; } for (Iterator it = info.getInterpolationMethods().iterator(); it.hasNext();) { String method = (String) it.next(); if (interpolation.equalsIgnoreCase(method)) { interpolationSupported = true; } } if (!interpolationSupported) throw new WcsException( "The requested Interpolation method is not supported by this Coverage.", InvalidParameterValue, "RangeSubset"); } // check axis if (field.getAxisSubset().size() > 1) { throw new WcsException("Multi axis coverages are not supported yet", InvalidParameterValue, "RangeSubset"); } else if (field.getAxisSubset().size() == 0) return; AxisSubsetType axisSubset = (AxisSubsetType) field.getAxisSubset().get(0); final String axisId = axisSubset.getIdentifier(); if (!axisId.equalsIgnoreCase("Bands")) throw new WcsException("Unknown axis " + axisId + " in field " + fieldId, InvalidParameterValue, "RangeSubset"); // prepare a support structure to quickly get the band index of a key // (and remember we replaced spaces with underscores in the keys to // avoid issues // with the kvp parsing of indentifiers that include spaces) List<CoverageDimensionInfo> dimensions = info.getDimensions(); Set<String> dimensionMap = new HashSet<String>(); for (int i = 0; i < dimensions.size(); i++) { String keyName = dimensions.get(i).getName().replace(' ', '_'); dimensionMap.add(keyName); } // check keys List keys = axisSubset.getKey(); int[] bands = new int[keys.size()]; for (int j = 0; j < bands.length; j++) { final String key = (String) keys.get(j); String parsedKey = null; for (String dimensionName : dimensionMap) { if (dimensionName.equalsIgnoreCase(key)) { parsedKey = dimensionName; break; } } if (parsedKey == null) throw new WcsException("Unknown field/axis/key combination " + fieldId + "/" + axisSubset.getIdentifier() + "/" + key, InvalidParameterValue, "RangeSubset"); else keys.set(j, parsedKey); } } /** * * @param date * @return */ private static Date cvtToGmt( Date date ) { TimeZone tz = TimeZone.getDefault(); Date ret = new Date( date.getTime() - tz.getRawOffset() ); // if we are now in DST, back off by the delta. Note that we are checking the GMT date, this is the KEY. if ( tz.inDaylightTime( ret )) { Date dstDate = new Date( ret.getTime() - tz.getDSTSavings() ); // check to make sure we have not crossed back into standard time // this happens when we are on the cusp of DST (7pm the day before the change for PDT) if ( tz.inDaylightTime( dstDate )) { ret = dstDate; } } return ret; } }
true
true
public GridCoverage[] getCoverage(GetCoverageType request) { if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.finest(new StringBuffer("execute CoverageRequest response. Called request is: ").append(request).toString()); } WCSInfo wcs = getServiceInfo(); CoverageInfo meta = null; GridCoverage2D coverage = null; try { CodeType identifier = request.getIdentifier(); if (identifier == null) throw new WcsException("Internal error, the coverage identifier must not be null", InvalidParameterValue, "identifier"); meta = catalog.getCoverageByName(identifier.getValue()); if (meta == null) { throw new WcsException("No such coverage: " + request.getIdentifier().getValue()); } // first let's run some sanity checks on the inputs checkDomainSubset(meta, request.getDomainSubset(), wcs); checkRangeSubset(meta, request.getRangeSubset()); checkOutput(meta, request.getOutput()); // grab the format, the reader using the default params final AbstractGridCoverage2DReader reader = (AbstractGridCoverage2DReader) meta.getGridCoverageReader(null, WCSUtils.getReaderHints(wcs)); // handle spatial domain subset, if needed final GeneralEnvelope originalEnvelope = reader.getOriginalEnvelope(); final BoundingBoxType bbox = request.getDomainSubset().getBoundingBox(); final CoordinateReferenceSystem nativeCRS = originalEnvelope.getCoordinateReferenceSystem(); final GeneralEnvelope requestedEnvelopeInSourceCRS; final GeneralEnvelope requestedEnvelope; MathTransform bboxToNativeTx=null; if (bbox != null) { // first off, parse the envelope corners double[] lowerCorner = new double[bbox.getLowerCorner().size()]; double[] upperCorner = new double[bbox.getUpperCorner().size()]; for (int i = 0; i < lowerCorner.length; i++) { lowerCorner[i] = (Double) bbox.getLowerCorner().get(i); upperCorner[i] = (Double) bbox.getUpperCorner().get(i); } requestedEnvelope = new GeneralEnvelope(lowerCorner, upperCorner); // grab the native crs // if no crs has beens specified, the native one is assumed if (bbox.getCrs() == null) { requestedEnvelope.setCoordinateReferenceSystem(nativeCRS); requestedEnvelopeInSourceCRS = requestedEnvelope; } else { // otherwise we need to transform final CoordinateReferenceSystem bboxCRS = CRS.decode(bbox.getCrs()); requestedEnvelope.setCoordinateReferenceSystem(bboxCRS); bboxToNativeTx = CRS.findMathTransform(bboxCRS, nativeCRS,true); if(!bboxToNativeTx.isIdentity()){ requestedEnvelopeInSourceCRS = CRS.transform(bboxToNativeTx,requestedEnvelope); requestedEnvelopeInSourceCRS.setCoordinateReferenceSystem(nativeCRS); } else requestedEnvelopeInSourceCRS= new GeneralEnvelope(requestedEnvelope); } } else { requestedEnvelopeInSourceCRS = reader.getOriginalEnvelope(); requestedEnvelope = requestedEnvelopeInSourceCRS; } final GridCrsType gridCRS = request.getOutput().getGridCRS(); // Compute the target crs, the crs that the final coverage will be // served into final CoordinateReferenceSystem targetCRS; if (gridCRS == null) targetCRS = reader.getOriginalEnvelope().getCoordinateReferenceSystem(); else targetCRS = CRS.decode(gridCRS.getGridBaseCRS()); // // Raster destination size // int elevationLevels=0; double[] elevations = null; // grab the grid to world transformation MathTransform gridToCRS = reader.getOriginalGridToWorld(PixelInCell.CELL_CORNER); if (gridCRS != null) { Double[] origin = (Double[]) gridCRS.getGridOrigin(); Double[] offsets = (Double[]) gridCRS.getGridOffsets(); // from the specification if grid origin is omitted and the crs // is 2d the default it's 0,0 if (origin == null) { origin = new Double[] { 0.0, 0.0 }; } // if no offsets has been specified we try to default on the // native ones if (offsets == null) { if (!(gridToCRS instanceof AffineTransform2D)&& !(gridToCRS instanceof IdentityTransform)) throw new WcsException( "Internal error, the coverage we're playing with does not have an affine transform..."); if (gridToCRS instanceof IdentityTransform) { if (gridCRS.getGridType().equals(GridType.GT2dSimpleGrid.getXmlConstant()) || gridCRS.getGridType().equals(GridType.GT2dGridIn2dCrs.getXmlConstant())) offsets = new Double[] { 1.0, 1.0 }; else offsets = new Double[] { 1.0, 0.0, 0.0, 0.0, 1.0, 0.0 }; } else { AffineTransform2D affine = (AffineTransform2D) gridToCRS; if (gridCRS.getGridType().equals(GridType.GT2dSimpleGrid.getXmlConstant()) || gridCRS.getGridType().equals(GridType.GT2dGridIn2dCrs.getXmlConstant())) offsets = new Double[] { affine.getScaleX(), affine.getScaleY() }; else offsets = new Double[] { affine.getScaleX(), affine.getShearX(), affine.getShearY(), affine.getScaleY() }; } } // building the actual transform for the resulting grid geometry AffineTransform tx; if (gridCRS.getGridType().equals(GridType.GT2dSimpleGrid.getXmlConstant())) { tx = new AffineTransform( offsets[0], 0, 0, offsets[1], origin[0], origin[1] ); } else if(gridCRS.getGridType().equals(GridType.GT2dGridIn2dCrs.getXmlConstant())) { tx = new AffineTransform( offsets[0], offsets[1], offsets[2], offsets[3], origin[0], origin[1] ); } else { tx = new AffineTransform( offsets[0], offsets[4], offsets[1], offsets[3], origin[0], origin[1] ); if (origin.length != 3 || offsets.length != 6) throw new WcsException("", InvalidParameterValue, "GridCRS"); // // ELEVATIONS // // TODO: draft code ... it needs more study! elevationLevels = (int) Math.round(requestedEnvelope.getUpperCorner().getOrdinate(2) - requestedEnvelope.getLowerCorner().getOrdinate(2)); // compute the elevation levels, we have elevationLevels values if (elevationLevels > 0) { elevations=new double[elevationLevels]; elevations[0]=requestedEnvelope.getLowerCorner().getOrdinate(2); // TODO put the extrema elevations[elevationLevels-1]=requestedEnvelope.getUpperCorner().getOrdinate(2); if(elevationLevels>2){ final int adjustedLevelsNum=elevationLevels-1; double step = (elevations[elevationLevels-1]-elevations[0])/adjustedLevelsNum; for(int i=1;i<adjustedLevelsNum;i++) elevations[i]=elevations[i-1]+step; } } } gridToCRS = new AffineTransform2D(tx); } // // TIME Values // final List<Date> timeValues = new LinkedList<Date>(); TimeSequenceType temporalSubset = request.getDomainSubset().getTemporalSubset(); if (temporalSubset != null && temporalSubset.getTimePosition() != null && temporalSubset.getTimePosition().size() > 0) { for (Iterator it = temporalSubset.getTimePosition().iterator(); it.hasNext(); ) { Date tp = (Date) it.next(); timeValues.add(tp); } } else if (temporalSubset != null && temporalSubset.getTimePeriod() != null && temporalSubset.getTimePeriod().size() > 0) { for (Iterator it = temporalSubset.getTimePeriod().iterator(); it.hasNext(); ) { TimePeriodType tp = (TimePeriodType) it.next(); Date beginning = (Date)tp.getBeginPosition(); Date ending = (Date)tp.getEndPosition(); timeValues.add(beginning); timeValues.add(ending); } } // now we have enough info to read the coverage, grab the parameters // and add the grid geometry info final GeneralEnvelope intersectionEnvelopeInSourceCRS = new GeneralEnvelope(requestedEnvelopeInSourceCRS); intersectionEnvelopeInSourceCRS.intersect(originalEnvelope); final GeneralEnvelope intersectionEnvelope= bboxToNativeTx.isIdentity()? new GeneralEnvelope(intersectionEnvelopeInSourceCRS): CRS.transform(bboxToNativeTx.inverse(), intersectionEnvelopeInSourceCRS); intersectionEnvelope.setCoordinateReferenceSystem(targetCRS); final GridGeometry2D requestedGridGeometry = new GridGeometry2D(PixelInCell.CELL_CORNER, gridToCRS, intersectionEnvelopeInSourceCRS, null); final ParameterValueGroup readParametersDescriptor = reader.getFormat().getReadParameters(); GeneralParameterValue[] readParameters = CoverageUtils.getParameters(readParametersDescriptor, meta.getParameters()); readParameters = (readParameters != null ? readParameters : new GeneralParameterValue[0]); // // Setting coverage reading params. // final ParameterValue requestedGridGeometryParam = new DefaultParameterDescriptor(AbstractGridFormat.READ_GRIDGEOMETRY2D.getName().toString(), GeneralGridGeometry.class, null, requestedGridGeometry).createValue(); /* * Test if the parameter "TIME" is present in the WMS * request, and by the way in the reading parameters. If * it is the case, one can adds it to the request. If an * exception is thrown, we have nothing to do. */ final List<GeneralParameterDescriptor> parameterDescriptors = readParametersDescriptor.getDescriptor().descriptors(); ParameterValue time=null; boolean hasTime=timeValues.size()>0; ParameterValue elevation=null; boolean hasElevation=elevations != null && !Double.isNaN(elevations[0]); if(hasElevation||hasTime){ for(GeneralParameterDescriptor pd:parameterDescriptors){ final String code=pd.getName().getCode(); // // TIME // if(code.equalsIgnoreCase("TIME")){ time=(ParameterValue) pd.createValue(); time.setValue(timeValues); } // // ELEVATION // if(code.equalsIgnoreCase("ELEVATION")){ elevation=(ParameterValue) pd.createValue(); elevation.setValue(elevations[0]); } // leave? if((hasElevation&&elevation!=null&&hasTime&&time!=null)|| !hasElevation&&hasTime&&time!=null|| hasElevation&&elevation!=null&&!hasTime) break; } } // // add read parameters // int addedParams=1+(hasTime?1:0)+(hasElevation?1:0); // add to the list GeneralParameterValue[] readParametersClone = new GeneralParameterValue[readParameters.length+addedParams--]; System.arraycopy(readParameters, 0,readParametersClone , 0, readParameters.length); readParametersClone[readParameters.length+addedParams--]=requestedGridGeometryParam; if(hasTime) readParametersClone[readParameters.length+addedParams--]=time; if(hasElevation) readParametersClone[readParameters.length+addedParams--]=elevation; readParameters=readParametersClone; // Check we're not being requested to read too much data from input (first check, // guesses the grid size using the information contained in CoverageInfo) WCSUtils.checkInputLimits(wcs, meta, reader, requestedGridGeometry); // // perform Read ... // coverage = (GridCoverage2D) reader.read(readParameters); if ((coverage == null) || !(coverage instanceof GridCoverage2D)) { throw new IOException("The requested coverage could not be found."); } // now that we have read the coverage double check the input size WCSUtils.checkInputLimits(wcs, coverage); /** * Band Select (works on just one field) */ GridCoverage2D bandSelectedCoverage = coverage; String interpolationType = null; if (request.getRangeSubset() != null) { if (request.getRangeSubset().getFieldSubset().size() > 1) { throw new WcsException("Multi field coverages are not supported yet"); } FieldSubsetType field = (FieldSubsetType) request.getRangeSubset().getFieldSubset().get(0); interpolationType = field.getInterpolationType(); // handle axis subset if (field.getAxisSubset().size() > 1) { throw new WcsException("Multi axis coverages are not supported yet"); } if (field.getAxisSubset().size() == 1) { // prepare a support structure to quickly get the band index // of a // key List<CoverageDimensionInfo> dimensions = meta.getDimensions(); Map<String, Integer> dimensionMap = new HashMap<String, Integer>(); for (int i = 0; i < dimensions.size(); i++) { String keyName = dimensions.get(i).getName().replace(' ', '_'); dimensionMap.put(keyName, i); } // extract the band indexes AxisSubsetType axisSubset = (AxisSubsetType) field.getAxisSubset().get(0); List keys = axisSubset.getKey(); int[] bands = new int[keys.size()]; for (int j = 0; j < bands.length; j++) { final String key = (String) keys.get(j); Integer index = dimensionMap.get(key); if (index == null) throw new WcsException("Unknown field/axis/key combination " + field.getIdentifier().getValue() + "/" + axisSubset.getIdentifier() + "/" + key); bands[j] = index; } // finally execute the band select try { bandSelectedCoverage = (GridCoverage2D) WCSUtils .bandSelect(coverage, bands); } catch (WcsException e) { throw new WcsException(e.getLocalizedMessage()); } } } /** * Checking for supported Interpolation Methods */ Interpolation interpolation = Interpolation.getInstance(Interpolation.INTERP_NEAREST); if (interpolationType != null) { if (interpolationType.equalsIgnoreCase("bilinear")) { interpolation = Interpolation.getInstance(Interpolation.INTERP_BILINEAR); } else if (interpolationType.equalsIgnoreCase("bicubic")) { interpolation = Interpolation.getInstance(Interpolation.INTERP_BICUBIC); } else if (interpolationType.equalsIgnoreCase("nearest")) { interpolation = Interpolation.getInstance(Interpolation.INTERP_NEAREST); } } /** * Reproject */ // adjust the grid geometry to use the final bbox and crs final GridGeometry2D destinationGridGeometry = new GridGeometry2D(PixelInCell.CELL_CORNER, gridToCRS, intersectionEnvelope, null); // before extracting the output make sure it's not too big WCSUtils.checkOutputLimits(wcs, destinationGridGeometry.getGridRange2D(), bandSelectedCoverage.getRenderedImage().getSampleModel()); // reproject if necessary if(!CRS.equalsIgnoreMetadata(nativeCRS, targetCRS)) { final GridCoverage2D reprojectedCoverage = WCSUtils.resample( bandSelectedCoverage, nativeCRS, targetCRS, destinationGridGeometry,interpolation); return new GridCoverage[] { reprojectedCoverage }; } else { return new GridCoverage[] { bandSelectedCoverage }; } } catch (Throwable e) { if (e instanceof WcsException) throw (WcsException) e; else throw new WcsException(e); } }
public GridCoverage[] getCoverage(GetCoverageType request) { if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.finest(new StringBuffer("execute CoverageRequest response. Called request is: ").append(request).toString()); } WCSInfo wcs = getServiceInfo(); CoverageInfo meta = null; GridCoverage2D coverage = null; try { CodeType identifier = request.getIdentifier(); if (identifier == null) throw new WcsException("Internal error, the coverage identifier must not be null", InvalidParameterValue, "identifier"); meta = catalog.getCoverageByName(identifier.getValue()); if (meta == null) { throw new WcsException("No such coverage: " + request.getIdentifier().getValue()); } // first let's run some sanity checks on the inputs checkDomainSubset(meta, request.getDomainSubset(), wcs); checkRangeSubset(meta, request.getRangeSubset()); checkOutput(meta, request.getOutput()); // grab the format, the reader using the default params final AbstractGridCoverage2DReader reader = (AbstractGridCoverage2DReader) meta.getGridCoverageReader(null, WCSUtils.getReaderHints(wcs)); // handle spatial domain subset, if needed final GeneralEnvelope originalEnvelope = reader.getOriginalEnvelope(); final BoundingBoxType bbox = request.getDomainSubset().getBoundingBox(); final CoordinateReferenceSystem nativeCRS = originalEnvelope.getCoordinateReferenceSystem(); final GeneralEnvelope requestedEnvelopeInSourceCRS; final GeneralEnvelope requestedEnvelope; MathTransform bboxToNativeTx=null; if (bbox != null) { // first off, parse the envelope corners double[] lowerCorner = new double[bbox.getLowerCorner().size()]; double[] upperCorner = new double[bbox.getUpperCorner().size()]; for (int i = 0; i < lowerCorner.length; i++) { lowerCorner[i] = (Double) bbox.getLowerCorner().get(i); upperCorner[i] = (Double) bbox.getUpperCorner().get(i); } requestedEnvelope = new GeneralEnvelope(lowerCorner, upperCorner); // grab the native crs // if no crs has beens specified, the native one is assumed if (bbox.getCrs() == null) { requestedEnvelope.setCoordinateReferenceSystem(nativeCRS); requestedEnvelopeInSourceCRS = requestedEnvelope; } else { // otherwise we need to transform final CoordinateReferenceSystem bboxCRS = CRS.decode(bbox.getCrs()); requestedEnvelope.setCoordinateReferenceSystem(bboxCRS); bboxToNativeTx = CRS.findMathTransform(bboxCRS, nativeCRS,true); if(!bboxToNativeTx.isIdentity()){ requestedEnvelopeInSourceCRS = CRS.transform(bboxToNativeTx,requestedEnvelope); requestedEnvelopeInSourceCRS.setCoordinateReferenceSystem(nativeCRS); } else requestedEnvelopeInSourceCRS= new GeneralEnvelope(requestedEnvelope); } } else { requestedEnvelopeInSourceCRS = reader.getOriginalEnvelope(); requestedEnvelope = requestedEnvelopeInSourceCRS; } final GridCrsType gridCRS = request.getOutput().getGridCRS(); // Compute the target crs, the crs that the final coverage will be // served into final CoordinateReferenceSystem targetCRS; if (gridCRS == null) targetCRS = reader.getOriginalEnvelope().getCoordinateReferenceSystem(); else targetCRS = CRS.decode(gridCRS.getGridBaseCRS()); // // Raster destination size // int elevationLevels=0; double[] elevations = null; // grab the grid to world transformation MathTransform gridToCRS = reader.getOriginalGridToWorld(PixelInCell.CELL_CORNER); if (gridCRS != null) { Double[] origin = (Double[]) gridCRS.getGridOrigin(); Double[] offsets = (Double[]) gridCRS.getGridOffsets(); // from the specification if grid origin is omitted and the crs // is 2d the default it's 0,0 if (origin == null) { origin = new Double[] { 0.0, 0.0 }; } // if no offsets has been specified we try to default on the // native ones if (offsets == null) { if (!(gridToCRS instanceof AffineTransform2D)&& !(gridToCRS instanceof IdentityTransform)) throw new WcsException( "Internal error, the coverage we're playing with does not have an affine transform..."); if (gridToCRS instanceof IdentityTransform) { if (gridCRS.getGridType().equals(GridType.GT2dSimpleGrid.getXmlConstant()) || gridCRS.getGridType().equals(GridType.GT2dGridIn2dCrs.getXmlConstant())) offsets = new Double[] { 1.0, 1.0 }; else offsets = new Double[] { 1.0, 0.0, 0.0, 0.0, 1.0, 0.0 }; } else { AffineTransform2D affine = (AffineTransform2D) gridToCRS; if (gridCRS.getGridType().equals(GridType.GT2dSimpleGrid.getXmlConstant()) || gridCRS.getGridType().equals(GridType.GT2dGridIn2dCrs.getXmlConstant())) offsets = new Double[] { affine.getScaleX(), affine.getScaleY() }; else offsets = new Double[] { affine.getScaleX(), affine.getShearX(), affine.getShearY(), affine.getScaleY() }; } } // building the actual transform for the resulting grid geometry AffineTransform tx; if (gridCRS.getGridType().equals(GridType.GT2dSimpleGrid.getXmlConstant())) { tx = new AffineTransform( offsets[0], 0, 0, offsets[1], origin[0], origin[1] ); } else if(gridCRS.getGridType().equals(GridType.GT2dGridIn2dCrs.getXmlConstant())) { tx = new AffineTransform( offsets[0], offsets[1], offsets[2], offsets[3], origin[0], origin[1] ); } else { tx = new AffineTransform( offsets[0], offsets[4], offsets[1], offsets[3], origin[0], origin[1] ); if (origin.length != 3 || offsets.length != 6) throw new WcsException("", InvalidParameterValue, "GridCRS"); // // ELEVATIONS // // TODO: draft code ... it needs more study! elevationLevels = (int) Math.round(requestedEnvelope.getUpperCorner().getOrdinate(2) - requestedEnvelope.getLowerCorner().getOrdinate(2)); // compute the elevation levels, we have elevationLevels values if (elevationLevels > 0) { elevations=new double[elevationLevels]; elevations[0]=requestedEnvelope.getLowerCorner().getOrdinate(2); // TODO put the extrema elevations[elevationLevels-1]=requestedEnvelope.getUpperCorner().getOrdinate(2); if(elevationLevels>2){ final int adjustedLevelsNum=elevationLevels-1; double step = (elevations[elevationLevels-1]-elevations[0])/adjustedLevelsNum; for(int i=1;i<adjustedLevelsNum;i++) elevations[i]=elevations[i-1]+step; } } } gridToCRS = new AffineTransform2D(tx); } // // TIME Values // final List<Date> timeValues = new LinkedList<Date>(); TimeSequenceType temporalSubset = request.getDomainSubset().getTemporalSubset(); if (temporalSubset != null && temporalSubset.getTimePosition() != null && temporalSubset.getTimePosition().size() > 0) { for (Iterator it = temporalSubset.getTimePosition().iterator(); it.hasNext(); ) { Date tp = (Date) it.next(); timeValues.add(tp); } } else if (temporalSubset != null && temporalSubset.getTimePeriod() != null && temporalSubset.getTimePeriod().size() > 0) { for (Iterator it = temporalSubset.getTimePeriod().iterator(); it.hasNext(); ) { TimePeriodType tp = (TimePeriodType) it.next(); Date beginning = (Date)tp.getBeginPosition(); Date ending = (Date)tp.getEndPosition(); timeValues.add(beginning); timeValues.add(ending); } } // now we have enough info to read the coverage, grab the parameters // and add the grid geometry info final GeneralEnvelope intersectionEnvelopeInSourceCRS = new GeneralEnvelope(requestedEnvelopeInSourceCRS); intersectionEnvelopeInSourceCRS.intersect(originalEnvelope); final GeneralEnvelope intersectionEnvelope= bboxToNativeTx.isIdentity()? new GeneralEnvelope(intersectionEnvelopeInSourceCRS): CRS.transform(bboxToNativeTx.inverse(), intersectionEnvelopeInSourceCRS); intersectionEnvelope.setCoordinateReferenceSystem(targetCRS); final GridGeometry2D requestedGridGeometry = new GridGeometry2D(PixelInCell.CELL_CORNER, gridToCRS, intersectionEnvelopeInSourceCRS, null); final ParameterValueGroup readParametersDescriptor = reader.getFormat().getReadParameters(); GeneralParameterValue[] readParameters = CoverageUtils.getParameters(readParametersDescriptor, meta.getParameters()); readParameters = (readParameters != null ? readParameters : new GeneralParameterValue[0]); // // Setting coverage reading params. // final ParameterValue requestedGridGeometryParam = new DefaultParameterDescriptor(AbstractGridFormat.READ_GRIDGEOMETRY2D.getName().toString(), GeneralGridGeometry.class, null, requestedGridGeometry).createValue(); /* * Test if the parameter "TIME" is present in the WMS * request, and by the way in the reading parameters. If * it is the case, one can adds it to the request. If an * exception is thrown, we have nothing to do. */ final List<GeneralParameterDescriptor> parameterDescriptors = readParametersDescriptor.getDescriptor().descriptors(); ParameterValue time=null; boolean hasTime=timeValues.size()>0; ParameterValue elevation=null; boolean hasElevation=elevations != null && !Double.isNaN(elevations[0]); if(hasElevation||hasTime){ for(GeneralParameterDescriptor pd:parameterDescriptors){ final String code=pd.getName().getCode(); // // TIME // if(code.equalsIgnoreCase("TIME")){ time=(ParameterValue) pd.createValue(); time.setValue(timeValues); } // // ELEVATION // if(code.equalsIgnoreCase("ELEVATION")){ elevation=(ParameterValue) pd.createValue(); elevation.setValue(elevations[0]); } // leave? if((hasElevation&&elevation!=null&&hasTime&&time!=null)|| !hasElevation&&hasTime&&time!=null|| hasElevation&&elevation!=null&&!hasTime) break; } } // // add read parameters // int addedParams=1+(hasTime?1:0)+(hasElevation?1:0); // add to the list GeneralParameterValue[] readParametersClone = new GeneralParameterValue[readParameters.length+addedParams--]; System.arraycopy(readParameters, 0,readParametersClone , 0, readParameters.length); readParametersClone[readParameters.length+addedParams--]=requestedGridGeometryParam; if(hasTime) readParametersClone[readParameters.length+addedParams--]=time; if(hasElevation) readParametersClone[readParameters.length+addedParams--]=elevation; readParameters=readParametersClone; // Check we're not being requested to read too much data from input (first check, // guesses the grid size using the information contained in CoverageInfo) WCSUtils.checkInputLimits(wcs, meta, reader, requestedGridGeometry); // // perform Read ... // coverage = (GridCoverage2D) reader.read(readParameters); if ((coverage == null) || !(coverage instanceof GridCoverage2D)) { throw new IOException("The requested coverage could not be found."); } // now that we have read the coverage double check the input size WCSUtils.checkInputLimits(wcs, coverage); /** * Band Select (works on just one field) */ GridCoverage2D bandSelectedCoverage = coverage; String interpolationType = null; if (request.getRangeSubset() != null) { if (request.getRangeSubset().getFieldSubset().size() > 1) { throw new WcsException("Multi field coverages are not supported yet"); } FieldSubsetType field = (FieldSubsetType) request.getRangeSubset().getFieldSubset().get(0); interpolationType = field.getInterpolationType(); // handle axis subset if (field.getAxisSubset().size() > 1) { throw new WcsException("Multi axis coverages are not supported yet"); } if (field.getAxisSubset().size() == 1) { // prepare a support structure to quickly get the band index // of a // key List<CoverageDimensionInfo> dimensions = meta.getDimensions(); Map<String, Integer> dimensionMap = new HashMap<String, Integer>(); for (int i = 0; i < dimensions.size(); i++) { String keyName = dimensions.get(i).getName().replace(' ', '_'); dimensionMap.put(keyName, i); } // extract the band indexes AxisSubsetType axisSubset = (AxisSubsetType) field.getAxisSubset().get(0); List keys = axisSubset.getKey(); int[] bands = new int[keys.size()]; for (int j = 0; j < bands.length; j++) { final String key = (String) keys.get(j); Integer index = dimensionMap.get(key); if (index == null) throw new WcsException("Unknown field/axis/key combination " + field.getIdentifier().getValue() + "/" + axisSubset.getIdentifier() + "/" + key); bands[j] = index; } // finally execute the band select try { bandSelectedCoverage = (GridCoverage2D) WCSUtils .bandSelect(coverage, bands); } catch (WcsException e) { throw new WcsException(e.getLocalizedMessage()); } } } /** * Checking for supported Interpolation Methods */ Interpolation interpolation = Interpolation.getInstance(Interpolation.INTERP_NEAREST); if (interpolationType != null) { if (interpolationType.equalsIgnoreCase("bilinear")) { interpolation = Interpolation.getInstance(Interpolation.INTERP_BILINEAR); } else if (interpolationType.equalsIgnoreCase("bicubic")) { interpolation = Interpolation.getInstance(Interpolation.INTERP_BICUBIC); } else if (interpolationType.equalsIgnoreCase("nearest")) { interpolation = Interpolation.getInstance(Interpolation.INTERP_NEAREST); } } /** * Reproject */ // adjust the grid geometry to use the final bbox and crs final GridGeometry2D destinationGridGeometry = new GridGeometry2D(PixelInCell.CELL_CORNER, gridToCRS, intersectionEnvelope, null); // before extracting the output make sure it's not too big WCSUtils.checkOutputLimits(wcs, destinationGridGeometry.getGridRange2D(), bandSelectedCoverage.getRenderedImage().getSampleModel()); // reproject if necessary if(!CRS.equalsIgnoreMetadata(nativeCRS, targetCRS) || !bandSelectedCoverage.getGridGeometry().equals(destinationGridGeometry)) { final GridCoverage2D reprojectedCoverage = WCSUtils.resample( bandSelectedCoverage, nativeCRS, targetCRS, destinationGridGeometry,interpolation); return new GridCoverage[] { reprojectedCoverage }; } else { return new GridCoverage[] { bandSelectedCoverage }; } } catch (Throwable e) { if (e instanceof WcsException) throw (WcsException) e; else throw new WcsException(e); } }
diff --git a/src/main/java/org/knipsX/controller/projectview/PictureListClickOnController.java b/src/main/java/org/knipsX/controller/projectview/PictureListClickOnController.java index b2518ce7..24f0b201 100644 --- a/src/main/java/org/knipsX/controller/projectview/PictureListClickOnController.java +++ b/src/main/java/org/knipsX/controller/projectview/PictureListClickOnController.java @@ -1,190 +1,190 @@ package org.knipsX.controller.projectview; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import org.apache.log4j.Logger; import org.knipsX.controller.AbstractController; import org.knipsX.model.picturemanagement.PictureInterface; import org.knipsX.model.projectview.ProjectModel; import org.knipsX.view.projectview.JProjectView; /** * Represents the Actions which are done by klicking on the picturelist. * * Acts in harmony with a JProjectview. * * @param <M> * a model. * * @param <V> * a view. */ public class PictureListClickOnController<M extends ProjectModel, V extends JProjectView<M>> extends AbstractController<M, V> implements MouseListener, MouseMotionListener { private static final int MOUSE_LEFT = 1; private final Logger logger = Logger.getLogger(this.getClass()); private JFrame tooltipWindow; /** * Creates a new controller which is connected to a view and a model. * * @param model * the model. * @param view * the view. */ public PictureListClickOnController(final M model, final V view) { super(model, view); } @Override public void actionPerformed(final ActionEvent e) { } /** * If something was clicked on. * * @param mouseEvent * the event of the mouse. * * @throws IllegalArgumentException * if you connect the controller to no JList, you get this error. */ public void mouseClicked(final MouseEvent mouseEvent) throws IllegalArgumentException { if (mouseEvent.getButton() == PictureListClickOnController.MOUSE_LEFT) { if (mouseEvent.getSource() instanceof JList) { final JList theList = (JList) mouseEvent.getSource(); if (mouseEvent.getClickCount() == 1) { final int index = theList.locationToIndex(mouseEvent.getPoint()); if (index >= 0) { final PictureInterface pic = (PictureInterface) theList.getModel().getElementAt(index); this.model.setSelectedPicture(pic); } } } else { throw new IllegalArgumentException("This controller can only handle JLists."); } } } /** * If something was entered. * * @param mouseEvent * the event of the mouse. * @throws IllegalArgumentException * if you connect the controller to no JList, you get this error. */ public void mouseEntered(final MouseEvent mouseEvent) throws IllegalArgumentException { this.tooltipWindow = new JFrame(); this.drawTooltip(mouseEvent); } /** * If something was exited. * * @param mouseEvent * the event of the mouse. */ public void mouseExited(final MouseEvent mouseEvent) { if (this.tooltipWindow != null) { this.tooltipWindow.dispose(); } } /** * If something was pressed. * * @param mouseEvent * the event of the mouse. */ public void mousePressed(final MouseEvent mouseEvent) { } /** * If something was released. * * @param mouseEvent * the event of the mouse. */ public void mouseReleased(final MouseEvent mouseEvent) { } /** * If something was dragged. * * @param mouseEvent * the event of the mouse. */ public void mouseDragged(final MouseEvent mouseEvent) { } /** * If something was moved. * * @param mouseEvent * the event of the mouse. * @throws IllegalArgumentException * if you connect the controller to no JList, you get this error. */ public void mouseMoved(final MouseEvent mouseEvent) throws IllegalArgumentException { if (this.tooltipWindow != null) { this.drawTooltip(mouseEvent); } } /* * Draws the tooltip. * * @param mouseEvent * the event of the mouse. * * @throws IllegalArgumentException * if you connect the controller to no JList, you get this error. */ private void drawTooltip(final MouseEvent mouseEvent) throws IllegalArgumentException { if (mouseEvent.getSource() instanceof JList) { final JList theList = (JList) mouseEvent.getSource(); final int index = theList.locationToIndex(mouseEvent.getPoint()); if (index >= 0) { final PictureInterface pic = (PictureInterface) theList.getModel().getElementAt(index); final Point point = mouseEvent.getLocationOnScreen(); point.translate(10, 10); try { final ImageIcon image = new ImageIcon(pic.getBigThumbnail()); final JPanel panel = new JPanel(); panel.add(new JLabel(image)); this.tooltipWindow.setContentPane(panel); this.tooltipWindow.setLocation(point); - this.tooltipWindow.setSize(image.getIconHeight(), image.getIconWidth()); + this.tooltipWindow.setSize(image.getIconWidth(), image.getIconHeight()); this.tooltipWindow.setVisible(true); } catch (final NullPointerException e) { this.logger.info("Can not display the thumbnail because at this time it is not initialized."); } } } else { throw new IllegalArgumentException("This controller can only handle JLists."); } } }
true
true
private void drawTooltip(final MouseEvent mouseEvent) throws IllegalArgumentException { if (mouseEvent.getSource() instanceof JList) { final JList theList = (JList) mouseEvent.getSource(); final int index = theList.locationToIndex(mouseEvent.getPoint()); if (index >= 0) { final PictureInterface pic = (PictureInterface) theList.getModel().getElementAt(index); final Point point = mouseEvent.getLocationOnScreen(); point.translate(10, 10); try { final ImageIcon image = new ImageIcon(pic.getBigThumbnail()); final JPanel panel = new JPanel(); panel.add(new JLabel(image)); this.tooltipWindow.setContentPane(panel); this.tooltipWindow.setLocation(point); this.tooltipWindow.setSize(image.getIconHeight(), image.getIconWidth()); this.tooltipWindow.setVisible(true); } catch (final NullPointerException e) { this.logger.info("Can not display the thumbnail because at this time it is not initialized."); } } } else { throw new IllegalArgumentException("This controller can only handle JLists."); } }
private void drawTooltip(final MouseEvent mouseEvent) throws IllegalArgumentException { if (mouseEvent.getSource() instanceof JList) { final JList theList = (JList) mouseEvent.getSource(); final int index = theList.locationToIndex(mouseEvent.getPoint()); if (index >= 0) { final PictureInterface pic = (PictureInterface) theList.getModel().getElementAt(index); final Point point = mouseEvent.getLocationOnScreen(); point.translate(10, 10); try { final ImageIcon image = new ImageIcon(pic.getBigThumbnail()); final JPanel panel = new JPanel(); panel.add(new JLabel(image)); this.tooltipWindow.setContentPane(panel); this.tooltipWindow.setLocation(point); this.tooltipWindow.setSize(image.getIconWidth(), image.getIconHeight()); this.tooltipWindow.setVisible(true); } catch (final NullPointerException e) { this.logger.info("Can not display the thumbnail because at this time it is not initialized."); } } } else { throw new IllegalArgumentException("This controller can only handle JLists."); } }
diff --git a/javasvn/src/org/tigris/subversion/javahl/PromptAuthenticationProvider.java b/javasvn/src/org/tigris/subversion/javahl/PromptAuthenticationProvider.java index 00a6885a1..373c63f5f 100644 --- a/javasvn/src/org/tigris/subversion/javahl/PromptAuthenticationProvider.java +++ b/javasvn/src/org/tigris/subversion/javahl/PromptAuthenticationProvider.java @@ -1,41 +1,42 @@ /* * Created on 25.06.2005 */ package org.tigris.subversion.javahl; import org.tmatesoft.svn.core.wc.ISVNAuthenticationManager; import org.tmatesoft.svn.core.wc.ISVNAuthenticationProvider; import org.tmatesoft.svn.core.wc.SVNAuthentication; public class PromptAuthenticationProvider implements ISVNAuthenticationProvider { PromptUserPassword myPrompt; public PromptAuthenticationProvider(PromptUserPassword prompt){ myPrompt = prompt; } public SVNAuthentication requestClientAuthentication(String kind, String realm, String userName, ISVNAuthenticationManager manager) { if (myPrompt instanceof PromptUserPassword3) { PromptUserPassword3 prompt3 = (PromptUserPassword3) myPrompt; if(prompt3.prompt(realm, userName, manager.isAuthStorageEnabled())){ SVNAuthentication auth = new SVNAuthentication(kind, realm, prompt3.getUsername(), prompt3.getPassword()); auth.setStorageAllowed(prompt3.userAllowedSave()); + return auth; } }else{ if(myPrompt.prompt(realm, userName)){ SVNAuthentication auth = new SVNAuthentication(kind, realm, myPrompt.getUsername(), myPrompt.getPassword()); return auth; } } return null; } public int acceptServerAuthentication(SVNAuthentication authentication, ISVNAuthenticationManager manager) { return ISVNAuthenticationProvider.ACCEPTED; } }
true
true
public SVNAuthentication requestClientAuthentication(String kind, String realm, String userName, ISVNAuthenticationManager manager) { if (myPrompt instanceof PromptUserPassword3) { PromptUserPassword3 prompt3 = (PromptUserPassword3) myPrompt; if(prompt3.prompt(realm, userName, manager.isAuthStorageEnabled())){ SVNAuthentication auth = new SVNAuthentication(kind, realm, prompt3.getUsername(), prompt3.getPassword()); auth.setStorageAllowed(prompt3.userAllowedSave()); } }else{ if(myPrompt.prompt(realm, userName)){ SVNAuthentication auth = new SVNAuthentication(kind, realm, myPrompt.getUsername(), myPrompt.getPassword()); return auth; } } return null; }
public SVNAuthentication requestClientAuthentication(String kind, String realm, String userName, ISVNAuthenticationManager manager) { if (myPrompt instanceof PromptUserPassword3) { PromptUserPassword3 prompt3 = (PromptUserPassword3) myPrompt; if(prompt3.prompt(realm, userName, manager.isAuthStorageEnabled())){ SVNAuthentication auth = new SVNAuthentication(kind, realm, prompt3.getUsername(), prompt3.getPassword()); auth.setStorageAllowed(prompt3.userAllowedSave()); return auth; } }else{ if(myPrompt.prompt(realm, userName)){ SVNAuthentication auth = new SVNAuthentication(kind, realm, myPrompt.getUsername(), myPrompt.getPassword()); return auth; } } return null; }
diff --git a/src/main/java/cc/kune/core/client/actions/FolderNamesActionUtils.java b/src/main/java/cc/kune/core/client/actions/FolderNamesActionUtils.java index c51206561..e96f8d18f 100644 --- a/src/main/java/cc/kune/core/client/actions/FolderNamesActionUtils.java +++ b/src/main/java/cc/kune/core/client/actions/FolderNamesActionUtils.java @@ -1,40 +1,40 @@ /* * * Copyright (C) 2007-2012 The kune development team (see CREDITS for details) * This file is part of kune. * * 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 this program. If not, see <http://www.gnu.org/licenses/>. * */ package cc.kune.core.client.actions; import cc.kune.common.shared.i18n.I18n; import cc.kune.common.shared.utils.TextUtils; import cc.kune.core.client.resources.CoreMessages; import cc.kune.core.client.ui.dialogs.PromptTopDialog.Builder; public class FolderNamesActionUtils { public static void restrictToUnixName(final Builder builder, final String id) { // For the future: In Google Groups, the max group shorta name is 63 chars // (with dashes) builder.regex(TextUtils.UNIX_NAME).regexText( I18n.t("The name must contain only lowercase characters, numbers and dashes")).textboxId(id); builder.minLength(3).maxLength(15).allowBlank(false).minLengthText( - CoreMessages.FIELD_MUST_BE_BETWEEN_3_AND_15_NO_CHARS).maxLengthText( - CoreMessages.FIELD_MUST_BE_BETWEEN_3_AND_15_NO_CHARS); + I18n.t(CoreMessages.FIELD_MUST_BE_BETWEEN_3_AND_15_NO_CHARS)).maxLengthText( + I18n.t(CoreMessages.FIELD_MUST_BE_BETWEEN_3_AND_15_NO_CHARS)); } }
true
true
public static void restrictToUnixName(final Builder builder, final String id) { // For the future: In Google Groups, the max group shorta name is 63 chars // (with dashes) builder.regex(TextUtils.UNIX_NAME).regexText( I18n.t("The name must contain only lowercase characters, numbers and dashes")).textboxId(id); builder.minLength(3).maxLength(15).allowBlank(false).minLengthText( CoreMessages.FIELD_MUST_BE_BETWEEN_3_AND_15_NO_CHARS).maxLengthText( CoreMessages.FIELD_MUST_BE_BETWEEN_3_AND_15_NO_CHARS); }
public static void restrictToUnixName(final Builder builder, final String id) { // For the future: In Google Groups, the max group shorta name is 63 chars // (with dashes) builder.regex(TextUtils.UNIX_NAME).regexText( I18n.t("The name must contain only lowercase characters, numbers and dashes")).textboxId(id); builder.minLength(3).maxLength(15).allowBlank(false).minLengthText( I18n.t(CoreMessages.FIELD_MUST_BE_BETWEEN_3_AND_15_NO_CHARS)).maxLengthText( I18n.t(CoreMessages.FIELD_MUST_BE_BETWEEN_3_AND_15_NO_CHARS)); }
diff --git a/src/edu/lognet/reputation/experiments/Experiment1.java b/src/edu/lognet/reputation/experiments/Experiment1.java index a570d56..4ee6f42 100644 --- a/src/edu/lognet/reputation/experiments/Experiment1.java +++ b/src/edu/lognet/reputation/experiments/Experiment1.java @@ -1,103 +1,105 @@ package edu.lognet.reputation.experiments; import java.util.ArrayList; import java.util.List; import java.util.Random; import edu.lognet.reputation.controller.Reputation; import edu.lognet.reputation.model.Interaction; import edu.lognet.reputation.model.beans.experience.Experience; import edu.lognet.reputation.model.beans.service.Service; import edu.lognet.reputation.model.beans.user.IConsumer; import edu.lognet.reputation.model.beans.user.IProvider; import edu.lognet.reputation.model.beans.user.User; /** * @author lvanni */ public class Experiment1 extends AbstractExperiment { /* --------------------------------------------------------- */ /* Constructors */ /* --------------------------------------------------------- */ public Experiment1(int interactionNumber, int serviceNumber, int totalUserNumber, int goodUser, int badUser, int dataLostPercent) { super(interactionNumber, serviceNumber, totalUserNumber, goodUser, badUser, dataLostPercent); } /* --------------------------------------------------------- */ /* Implements IExperiment */ /* --------------------------------------------------------- */ /** * Starting the Experiements */ public void start() { // CREATE THE RANDOM FACTOR Random randomGenerator = new Random(); // CREATE THE SERVICES List<Service> services = getServiceSet(); // CREATE THE USERS List<User> users = getUserSet(services); // Launch the insteraction set List<Interaction> interactions = new ArrayList<Interaction>(); for (int i = 0; i < getInteractionNumber(); i++) { if(AbstractExperiment.LOG_ENABLED == 1) { System.out.println("\nINFO: BEGIN INTRACTION " + (i+1) + "/" + getInteractionNumber()); } // CHOOSE A RANDOM CONSUMER (AN USER WHO CONSUME A SERVICE) IConsumer consumer = users.get(randomGenerator.nextInt(users.size())); // CHOOSE A RANDOM SERVICE Service service = services.get(randomGenerator.nextInt(services.size())); // GET THE PROVIDER LIST OF THIS SERVICE List<IProvider> providers = service.getProviders(); // THE CONSUMER CHOOSE A PROVIDER IProvider provider = consumer.chooseProvider(providers, service, getDataLostPercent()); if(provider != null) { if(AbstractExperiment.LOG_ENABLED == 1) { System.out.println("INFO: " + ((User)consumer).getName() + " choose provider " + ((User)provider).getName()); } // THE CONSUMER GIVE A FEEDBACK double feedback = 0.0; - while((feedback = randomGenerator.nextDouble()) <= provider.getQoS()){} + while((feedback = randomGenerator.nextDouble()) > provider.getQoS()){ + System.out.println(feedback); + } if(AbstractExperiment.LOG_ENABLED == 1) { System.out.println("INFO: " + ((User)consumer).getName() + " give the feedback " + feedback); } // ADJUST THE CONSUMER EXPERIENCE Experience oldExp = consumer.getConsumerExp(provider, service); Experience newExp = new Experience(feedback); Experience currentExp = Reputation.adjustExperience(oldExp, newExp); consumer.setConsumerExp(provider, service, currentExp); // ADJUST CREDIBILITY Reputation.adjustCredibility(service.getRaters(provider), consumer.getCredibilityOfRater(service), currentExp); // UPDATE THE INTERACTION LIST interactions.add(new Interaction(provider, consumer, service, feedback)); } if(AbstractExperiment.LOG_ENABLED == 1) { System.out.println("INFO: END INTRACTION " + (i+1) + "/" + getInteractionNumber()); } } // PRINT ALL THE INTERACTION if(AbstractExperiment.LOG_ENABLED == 1) { System.out.println("INFO: Interaction List"); System.out.println("\tService\t\tProvider\tConsumer\tFeedback"); for(Interaction interaction : interactions){ System.out.println(interaction); } } } }
true
true
public void start() { // CREATE THE RANDOM FACTOR Random randomGenerator = new Random(); // CREATE THE SERVICES List<Service> services = getServiceSet(); // CREATE THE USERS List<User> users = getUserSet(services); // Launch the insteraction set List<Interaction> interactions = new ArrayList<Interaction>(); for (int i = 0; i < getInteractionNumber(); i++) { if(AbstractExperiment.LOG_ENABLED == 1) { System.out.println("\nINFO: BEGIN INTRACTION " + (i+1) + "/" + getInteractionNumber()); } // CHOOSE A RANDOM CONSUMER (AN USER WHO CONSUME A SERVICE) IConsumer consumer = users.get(randomGenerator.nextInt(users.size())); // CHOOSE A RANDOM SERVICE Service service = services.get(randomGenerator.nextInt(services.size())); // GET THE PROVIDER LIST OF THIS SERVICE List<IProvider> providers = service.getProviders(); // THE CONSUMER CHOOSE A PROVIDER IProvider provider = consumer.chooseProvider(providers, service, getDataLostPercent()); if(provider != null) { if(AbstractExperiment.LOG_ENABLED == 1) { System.out.println("INFO: " + ((User)consumer).getName() + " choose provider " + ((User)provider).getName()); } // THE CONSUMER GIVE A FEEDBACK double feedback = 0.0; while((feedback = randomGenerator.nextDouble()) <= provider.getQoS()){} if(AbstractExperiment.LOG_ENABLED == 1) { System.out.println("INFO: " + ((User)consumer).getName() + " give the feedback " + feedback); } // ADJUST THE CONSUMER EXPERIENCE Experience oldExp = consumer.getConsumerExp(provider, service); Experience newExp = new Experience(feedback); Experience currentExp = Reputation.adjustExperience(oldExp, newExp); consumer.setConsumerExp(provider, service, currentExp); // ADJUST CREDIBILITY Reputation.adjustCredibility(service.getRaters(provider), consumer.getCredibilityOfRater(service), currentExp); // UPDATE THE INTERACTION LIST interactions.add(new Interaction(provider, consumer, service, feedback)); } if(AbstractExperiment.LOG_ENABLED == 1) { System.out.println("INFO: END INTRACTION " + (i+1) + "/" + getInteractionNumber()); } } // PRINT ALL THE INTERACTION if(AbstractExperiment.LOG_ENABLED == 1) { System.out.println("INFO: Interaction List"); System.out.println("\tService\t\tProvider\tConsumer\tFeedback"); for(Interaction interaction : interactions){ System.out.println(interaction); } } }
public void start() { // CREATE THE RANDOM FACTOR Random randomGenerator = new Random(); // CREATE THE SERVICES List<Service> services = getServiceSet(); // CREATE THE USERS List<User> users = getUserSet(services); // Launch the insteraction set List<Interaction> interactions = new ArrayList<Interaction>(); for (int i = 0; i < getInteractionNumber(); i++) { if(AbstractExperiment.LOG_ENABLED == 1) { System.out.println("\nINFO: BEGIN INTRACTION " + (i+1) + "/" + getInteractionNumber()); } // CHOOSE A RANDOM CONSUMER (AN USER WHO CONSUME A SERVICE) IConsumer consumer = users.get(randomGenerator.nextInt(users.size())); // CHOOSE A RANDOM SERVICE Service service = services.get(randomGenerator.nextInt(services.size())); // GET THE PROVIDER LIST OF THIS SERVICE List<IProvider> providers = service.getProviders(); // THE CONSUMER CHOOSE A PROVIDER IProvider provider = consumer.chooseProvider(providers, service, getDataLostPercent()); if(provider != null) { if(AbstractExperiment.LOG_ENABLED == 1) { System.out.println("INFO: " + ((User)consumer).getName() + " choose provider " + ((User)provider).getName()); } // THE CONSUMER GIVE A FEEDBACK double feedback = 0.0; while((feedback = randomGenerator.nextDouble()) > provider.getQoS()){ System.out.println(feedback); } if(AbstractExperiment.LOG_ENABLED == 1) { System.out.println("INFO: " + ((User)consumer).getName() + " give the feedback " + feedback); } // ADJUST THE CONSUMER EXPERIENCE Experience oldExp = consumer.getConsumerExp(provider, service); Experience newExp = new Experience(feedback); Experience currentExp = Reputation.adjustExperience(oldExp, newExp); consumer.setConsumerExp(provider, service, currentExp); // ADJUST CREDIBILITY Reputation.adjustCredibility(service.getRaters(provider), consumer.getCredibilityOfRater(service), currentExp); // UPDATE THE INTERACTION LIST interactions.add(new Interaction(provider, consumer, service, feedback)); } if(AbstractExperiment.LOG_ENABLED == 1) { System.out.println("INFO: END INTRACTION " + (i+1) + "/" + getInteractionNumber()); } } // PRINT ALL THE INTERACTION if(AbstractExperiment.LOG_ENABLED == 1) { System.out.println("INFO: Interaction List"); System.out.println("\tService\t\tProvider\tConsumer\tFeedback"); for(Interaction interaction : interactions){ System.out.println(interaction); } } }
diff --git a/src/savant/format/ContinuousFormatterHelper.java b/src/savant/format/ContinuousFormatterHelper.java index 43e84ca4..5473bf98 100644 --- a/src/savant/format/ContinuousFormatterHelper.java +++ b/src/savant/format/ContinuousFormatterHelper.java @@ -1,257 +1,257 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package savant.format; import java.io.BufferedOutputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import savant.util.RAFUtils; import savant.util.SavantFileFormatterUtils; /** * * @author mfiume */ public class ContinuousFormatterHelper { // size of the output buffer protected static final int OUTPUT_BUFFER_SIZE = 1024 * 128; // 128K public static Map<String, String> makeMultiResolutionContinuousFiles(Map<String, String> referenceName2FilenameMap) throws FileNotFoundException, IOException { System.out.println("Making multi resolution continuous files..."); Map<String, String> referenceNameToIndexMap = new HashMap<String, String>(); for (String refname : referenceName2FilenameMap.keySet()) { System.out.println("Making multi resolution continuous file for " + refname); String infile = referenceName2FilenameMap.get(refname); String indexpath = infile + SavantFileFormatter.indexExtension; List<Level> levels = new ArrayList<Level>(); // start making levels Mode m = new FixedMode(1, 1, 1); Level l1 = new Level( 0, new File(infile).length(), SavantFileFormatterUtils.FLOAT_FIELD_SIZE, 1, m); levels.add(l1); // end make levels // write index file writeLevelsToFile(refname, levels, indexpath); referenceNameToIndexMap.put(refname, indexpath); } return referenceNameToIndexMap; } private static void writeLevelsToFile(String refname, List<Level> levels, String filename) throws IOException { DataOutputStream outfile = new DataOutputStream( new BufferedOutputStream( new FileOutputStream(filename), OUTPUT_BUFFER_SIZE)); System.out.println("Writing header for " + refname + " with " + levels.size() + " levels"); outfile.writeInt(levels.size()); for (Level l : levels) { writeLevelToFile(refname, l, outfile); } outfile.close(); } private static void writeLevelToFile(String refname, Level l, DataOutputStream o) throws IOException { o.writeLong(l.offset); o.writeLong(l.size); o.writeLong(l.recordSize); o.writeLong(l.resolution); o.writeInt(l.mode.type.ordinal()); if (l.mode.type == Mode.ModeType.FIXED) { FixedMode m = (FixedMode) l.mode; o.writeInt(m.start); o.writeInt(m.step); o.writeInt(m.span); } else if (l.mode.type == Mode.ModeType.VARIABLESTEP) { throw new UnsupportedOperationException("Variable step writing not implemented"); } } public static Map<String,List<Level>> readLevelHeadersFromBinaryFile(SavantFile savantFile) throws IOException { // read the refname -> index position map Map<String,Long[]> refMap = RAFUtils.readReferenceMap(savantFile); //System.out.println("\n=== DONE PARSING REF<->DATA MAP ==="); //System.out.println(); // change the offset savantFile.headerOffset = savantFile.getFilePointerSuper(); /* for (String s : refMap.keySet()) { Long[] vals = refMap.get(s); //System.out.println("Reference " + s + " at " + vals[0] + " of length " + vals[1]); } */ Map<String,List<Level>> headers = new HashMap<String,List<Level>>(); int headerNum = 0; System.out.println("Number of headers to get: " + refMap.keySet().size()); // keep track of the maximum end of tree position // (IMPORTANT NOTE: order of elements returned by keySet() is not gauranteed!!!) long maxend = Long.MIN_VALUE; for (String refname : refMap.keySet()) { Long[] v = refMap.get(refname); System.out.println("Getting header for refname: " + refname); - //System.out.println("========== Reading header for reference " + refname + " =========="); + System.out.println("========== Reading header for reference " + refname + " =========="); savantFile.seek(v[0]); - //System.out.println("Starting header at (super): " + savantFile.getFilePointerSuper()); + System.out.println("Starting header at (super): " + savantFile.getFilePointerSuper()); List<Level> header = readLevelHeaderFromBinaryFile(savantFile); - //System.out.println("Finished header at (super): " + savantFile.getFilePointerSuper()); + System.out.println("Finished header at (super): " + savantFile.getFilePointerSuper()); maxend = Math.max(maxend,savantFile.getFilePointerSuper()); headers.put(refname, header); headerNum++; } /* System.out.println("Read " + treenum + " trees (i.e. indicies)"); System.out.println("\n=== DONE PARSING REF<->INDEX MAP ==="); System.out.println("Changing offset from " + dFile.getHeaderOffset() + " to " + (dFile.getFilePointer()+dFile.getHeaderOffset())); System.out.println(); */ // set the header offset appropriately savantFile.headerOffset = maxend; return headers; } public static List<Level> readLevelHeaderFromBinaryFile(SavantFile savantFile) throws IOException { List<Level> header = new ArrayList<Level>(); int numLevels = savantFile.readInt(); //System.out.println("Number of levels in header: " + numLevels); for (int i = 0; i < numLevels; i++) { Level l = readLevelFromBinaryFile(savantFile); header.add(l); } return header; } private static Level readLevelFromBinaryFile(SavantFile savantFile) throws IOException { // need to use readBinaryRecord! long offset = savantFile.readLong(); long size = savantFile.readLong(); long recordSize = savantFile.readLong(); long resolution = savantFile.readLong(); Mode.ModeType type = Mode.ModeType.class.getEnumConstants()[savantFile.readInt()]; Mode m = null; if (type == Mode.ModeType.FIXED) { int start = savantFile.readInt(); int step = savantFile.readInt(); int span = savantFile.readInt(); m = new FixedMode(start, step, span); } else { throw new UnsupportedOperationException("Reading other mode types not implemented"); } Level l = new Level(offset, size, recordSize, resolution, m); return l; } public static class Mode { public enum ModeType { FIXED, VARIABLESTEP }; public ModeType type; public Mode(ModeType t) { this.type = t; } } public static class Level { public long offset; public long size; public long recordSize; public long resolution; public Mode mode; public Level(long offset, long size, long recordSize, long resolution, Mode m) { this.offset = offset; this.size = size; this.recordSize = recordSize; this.resolution = resolution; this.mode = m; } } public static class FixedMode extends Mode { public int start; public int step; public int span; public FixedMode(int start, int step, int span) { super(Mode.ModeType.FIXED); this.start = start; this.step = step; this.span = span; } } public static class VariableStepMode extends Mode { public int start; public int step; public int span; public VariableStepMode(int start, int step, int span) { super(Mode.ModeType.VARIABLESTEP); this.start = start; this.step = step; this.span = span; } } }
false
true
public static Map<String,List<Level>> readLevelHeadersFromBinaryFile(SavantFile savantFile) throws IOException { // read the refname -> index position map Map<String,Long[]> refMap = RAFUtils.readReferenceMap(savantFile); //System.out.println("\n=== DONE PARSING REF<->DATA MAP ==="); //System.out.println(); // change the offset savantFile.headerOffset = savantFile.getFilePointerSuper(); /* for (String s : refMap.keySet()) { Long[] vals = refMap.get(s); //System.out.println("Reference " + s + " at " + vals[0] + " of length " + vals[1]); } */ Map<String,List<Level>> headers = new HashMap<String,List<Level>>(); int headerNum = 0; System.out.println("Number of headers to get: " + refMap.keySet().size()); // keep track of the maximum end of tree position // (IMPORTANT NOTE: order of elements returned by keySet() is not gauranteed!!!) long maxend = Long.MIN_VALUE; for (String refname : refMap.keySet()) { Long[] v = refMap.get(refname); System.out.println("Getting header for refname: " + refname); //System.out.println("========== Reading header for reference " + refname + " =========="); savantFile.seek(v[0]); //System.out.println("Starting header at (super): " + savantFile.getFilePointerSuper()); List<Level> header = readLevelHeaderFromBinaryFile(savantFile); //System.out.println("Finished header at (super): " + savantFile.getFilePointerSuper()); maxend = Math.max(maxend,savantFile.getFilePointerSuper()); headers.put(refname, header); headerNum++; } /* System.out.println("Read " + treenum + " trees (i.e. indicies)"); System.out.println("\n=== DONE PARSING REF<->INDEX MAP ==="); System.out.println("Changing offset from " + dFile.getHeaderOffset() + " to " + (dFile.getFilePointer()+dFile.getHeaderOffset())); System.out.println(); */ // set the header offset appropriately savantFile.headerOffset = maxend; return headers; }
public static Map<String,List<Level>> readLevelHeadersFromBinaryFile(SavantFile savantFile) throws IOException { // read the refname -> index position map Map<String,Long[]> refMap = RAFUtils.readReferenceMap(savantFile); //System.out.println("\n=== DONE PARSING REF<->DATA MAP ==="); //System.out.println(); // change the offset savantFile.headerOffset = savantFile.getFilePointerSuper(); /* for (String s : refMap.keySet()) { Long[] vals = refMap.get(s); //System.out.println("Reference " + s + " at " + vals[0] + " of length " + vals[1]); } */ Map<String,List<Level>> headers = new HashMap<String,List<Level>>(); int headerNum = 0; System.out.println("Number of headers to get: " + refMap.keySet().size()); // keep track of the maximum end of tree position // (IMPORTANT NOTE: order of elements returned by keySet() is not gauranteed!!!) long maxend = Long.MIN_VALUE; for (String refname : refMap.keySet()) { Long[] v = refMap.get(refname); System.out.println("Getting header for refname: " + refname); System.out.println("========== Reading header for reference " + refname + " =========="); savantFile.seek(v[0]); System.out.println("Starting header at (super): " + savantFile.getFilePointerSuper()); List<Level> header = readLevelHeaderFromBinaryFile(savantFile); System.out.println("Finished header at (super): " + savantFile.getFilePointerSuper()); maxend = Math.max(maxend,savantFile.getFilePointerSuper()); headers.put(refname, header); headerNum++; } /* System.out.println("Read " + treenum + " trees (i.e. indicies)"); System.out.println("\n=== DONE PARSING REF<->INDEX MAP ==="); System.out.println("Changing offset from " + dFile.getHeaderOffset() + " to " + (dFile.getFilePointer()+dFile.getHeaderOffset())); System.out.println(); */ // set the header offset appropriately savantFile.headerOffset = maxend; return headers; }
diff --git a/trunk/CruxScannotation/src/br/com/sysmap/crux/scannotation/AbstractScanner.java b/trunk/CruxScannotation/src/br/com/sysmap/crux/scannotation/AbstractScanner.java index 84bfe7808..eeab085c4 100644 --- a/trunk/CruxScannotation/src/br/com/sysmap/crux/scannotation/AbstractScanner.java +++ b/trunk/CruxScannotation/src/br/com/sysmap/crux/scannotation/AbstractScanner.java @@ -1,199 +1,206 @@ /* * Copyright 2009 Sysmap Solutions Software e Consultoria Ltda. * * 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.sysmap.crux.scannotation; import java.net.URL; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; /** * @author Thiago da Rosa de Bustamante * */ public abstract class AbstractScanner { protected Set<String> ignoredPackages = new LinkedHashSet<String>(); protected Set<String> allowedPackages = new LinkedHashSet<String>(); protected Set<String> requiredPackages = new LinkedHashSet<String>(); protected String[] DEFAULT_IGNORED_PACKAGES = {"javax", "java", "sun", "com.sun", "org.apache", "net.sf.saxon", "javassist", "junit"}; /** * */ public AbstractScanner() { initializeDefaultIgnoredPackages(); } /** * */ private void initializeDefaultIgnoredPackages() { for (String pkg : DEFAULT_IGNORED_PACKAGES) { ignoredPackages.add(pkg); } } /** * * @return */ public String[] getIgnoredPackages() { return ignoredPackages.toArray(new String[ignoredPackages.size()]); } /** * * @param ignoredPackages */ public void setIgnoredPackages(String[] ignoredPackages) { this.ignoredPackages = new HashSet<String>(); if (ignoredPackages != null) { for (String pkg : ignoredPackages) { this.ignoredPackages.add(pkg); } } } /** * @param ignoredPackage */ public void addIgnoredPackage(String ignoredPackage) { this.ignoredPackages.add(ignoredPackage); } /** * * @return */ public String[] getAllowedPackages() { return allowedPackages.toArray(new String[allowedPackages.size()]); } /** * * @param ignoredPackages */ public void setAllowedPackages(String[] allowedPackages) { this.allowedPackages = new HashSet<String>(); if (allowedPackages != null) { for (String pkg : allowedPackages) { this.allowedPackages.add(pkg); } } } /** * @param ignoredPackage */ public void addAllowedPackage(String allowedPackage) { this.allowedPackages.add(allowedPackage); } /** * * @return */ public String[] getRequiredPackages() { return requiredPackages.toArray(new String[requiredPackages.size()]); } /** * * @param ignoredPackages */ public void setRequiredPackages(String[] requiredPackages) { this.requiredPackages = new HashSet<String>(); if (requiredPackages != null) { for (String pkg : requiredPackages) { this.requiredPackages.add(pkg); } } } /** * @param ignoredPackage */ public void addRequiredPackage(String requiredPackages) { this.requiredPackages.add(requiredPackages); } /** * * @param intf * @return */ protected boolean ignoreScan(URL baseURL, String intf) { String urlString = baseURL.toString(); if (intf.startsWith(urlString)) { intf = intf.substring(urlString.length()); } + else if (intf.startsWith("jar:") || intf.startsWith("zip:")) + { + if (intf.indexOf("!/") > 0) + { + intf = intf.substring(intf.indexOf("!/")+2); + } + } if (intf.startsWith("/")) intf = intf.substring(1); intf = intf.replace('/', '.'); if (allowedPackages.size() > 0) { for (String allowed : allowedPackages) { if (intf.startsWith(allowed + ".")) { return false; } } for (String allowed : requiredPackages) { if (intf.startsWith(allowed + ".")) { return false; } } return true; } for (String ignored : ignoredPackages) { if (intf.startsWith(ignored + ".")) { return true; } } return false; } }
true
true
protected boolean ignoreScan(URL baseURL, String intf) { String urlString = baseURL.toString(); if (intf.startsWith(urlString)) { intf = intf.substring(urlString.length()); } if (intf.startsWith("/")) intf = intf.substring(1); intf = intf.replace('/', '.'); if (allowedPackages.size() > 0) { for (String allowed : allowedPackages) { if (intf.startsWith(allowed + ".")) { return false; } } for (String allowed : requiredPackages) { if (intf.startsWith(allowed + ".")) { return false; } } return true; } for (String ignored : ignoredPackages) { if (intf.startsWith(ignored + ".")) { return true; } } return false; }
protected boolean ignoreScan(URL baseURL, String intf) { String urlString = baseURL.toString(); if (intf.startsWith(urlString)) { intf = intf.substring(urlString.length()); } else if (intf.startsWith("jar:") || intf.startsWith("zip:")) { if (intf.indexOf("!/") > 0) { intf = intf.substring(intf.indexOf("!/")+2); } } if (intf.startsWith("/")) intf = intf.substring(1); intf = intf.replace('/', '.'); if (allowedPackages.size() > 0) { for (String allowed : allowedPackages) { if (intf.startsWith(allowed + ".")) { return false; } } for (String allowed : requiredPackages) { if (intf.startsWith(allowed + ".")) { return false; } } return true; } for (String ignored : ignoredPackages) { if (intf.startsWith(ignored + ".")) { return true; } } return false; }
diff --git a/examples/org.eclipse.rap.demo.controls/src/org/eclipse/rap/demo/controls/MnemonicsTab.java b/examples/org.eclipse.rap.demo.controls/src/org/eclipse/rap/demo/controls/MnemonicsTab.java index 351b22ebd..4faa3e8b1 100644 --- a/examples/org.eclipse.rap.demo.controls/src/org/eclipse/rap/demo/controls/MnemonicsTab.java +++ b/examples/org.eclipse.rap.demo.controls/src/org/eclipse/rap/demo/controls/MnemonicsTab.java @@ -1,318 +1,324 @@ /******************************************************************************* * Copyright (c) 2013 Innoopract Informationssysteme GmbH 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: * Innoopract Informationssysteme GmbH - initial API and implementation * EclipseSource - ongoing development ******************************************************************************/ package org.eclipse.rap.demo.controls; import org.eclipse.rap.rwt.RWT; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CLabel; import org.eclipse.swt.custom.CTabFolder; import org.eclipse.swt.custom.CTabItem; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.RowData; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TabFolder; import org.eclipse.swt.widgets.TabItem; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.swt.widgets.ToolItem; public class MnemonicsTab extends ExampleTab { private static final String DEFAULT_ACTIVATOR = "CTRL+ALT"; private static final String[] DEFAULT_SHORTCUT = new String[]{ "CTRL+ALT+Y" }; protected boolean useCTabFolder; public MnemonicsTab() { super( "Mnemonics" ); } @Override protected void createStyleControls( Composite parent ) { createActivatorControls( parent ); createShortcutControls( parent ); createCTabFolderButton( parent ); } private void createShortcutControls( Composite parent ) { final Display display = parent.getDisplay(); display.setData( RWT.ACTIVE_KEYS, DEFAULT_SHORTCUT ); display.setData( RWT.CANCEL_KEYS, DEFAULT_SHORTCUT ); final Text shortcutText = new Text( parent, SWT.BORDER ); shortcutText.setText( DEFAULT_SHORTCUT[ 0 ] ); shortcutText.setLayoutData( new RowData( 110, SWT.DEFAULT ) ); Button setShortcut = new Button( parent, SWT.PUSH ); setShortcut.setText( "set global shortcut" ); setShortcut.addListener( SWT.Selection, new Listener() { public void handleEvent( Event event ) { String[] shortcut = new String[]{ shortcutText.getText() }; display.setData( RWT.ACTIVE_KEYS, shortcut ); display.setData( RWT.CANCEL_KEYS, shortcut ); } } ); display.addFilter( SWT.KeyDown, new Listener() { public void handleEvent( Event event ) { log( event.toString() ); } } ); } private void createActivatorControls( Composite parent ) { final Display display = parent.getDisplay(); display.setData( RWT.MNEMONIC_ACTIVATOR, DEFAULT_ACTIVATOR ); final Text activatorText = new Text( parent, SWT.BORDER ); activatorText.setText( DEFAULT_ACTIVATOR ); activatorText.setLayoutData( new RowData( 110, SWT.DEFAULT ) ); Button setActivator = new Button( parent, SWT.PUSH ); setActivator.setText( "set activator" ); setActivator.addListener( SWT.Selection, new Listener() { public void handleEvent( Event event ) { display.setData( RWT.MNEMONIC_ACTIVATOR, activatorText.getText() ); } } ); } private void createCTabFolderButton( Composite parent ) { final Button ctabFolderButton = new Button( parent, SWT.TOGGLE ); ctabFolderButton.setText( "use CTabFolder" ); ctabFolderButton.addListener( SWT.Selection, new Listener() { public void handleEvent( Event event ) { useCTabFolder = ctabFolderButton.getSelection(); createNew(); } } ); } @Override protected void createExampleControls( Composite parent ) { parent.setLayout( new FillLayout() ); int tabCount = 4; if( useCTabFolder ) { CTabFolder folder = new CTabFolder( parent, getStyle() ); CTabItem[] tabItems = new CTabItem[ tabCount ]; for( int i = 0; i < tabCount; i++ ) { tabItems[ i ] = new CTabItem( folder, SWT.NONE ); tabItems[ i ].setText( "CTabItem &" + ( i + 1) ); Composite content = createItemContent( folder, i ); tabItems[ i ].setControl( content ); } folder.setSelection( 0 ); } else { TabFolder folder = new TabFolder( parent, getStyle() ); TabItem[] tabItems = new TabItem[ tabCount ]; for( int i = 0; i < tabCount; i++ ) { tabItems[ i ] = new TabItem( folder, SWT.NONE ); tabItems[ i ].setText( "TabItem &" + ( i + 1 ) ); Composite content = createItemContent( folder, i ); tabItems[ i ].setControl( content ); } } } private Composite createItemContent( Composite folder, int index ) { Composite content = new Composite( folder, SWT.NONE ); content.setLayout( new GridLayout( 4, false ) ); switch( index ) { case 0: createButtonExample( content ); break; case 1: createToolBarExample( content ); createLabelExample( content ); break; case 2: createGroupExample( content ); break; case 3: createMenuExample( content ); break; } return content; } private void createMenuExample( final Composite content ) { final Button button = new Button( content, SWT.PUSH ); button.setText( "Open Shell with Menu" ); button.addListener( SWT.Selection, new Listener() { public void handleEvent( Event event ) { createShellWithMenu( content ); } } ); } private void createShellWithMenu( final Composite content ) { Shell shell = new Shell( content.getShell(), SWT.BORDER ); shell.setLayout( new GridLayout() ); createMenuBar( shell ); // Bug? - Without a widget in the shell it doesn't get correctly focused Button test = new Button( shell, SWT.PUSH ); test.setText( "foo" ); test.setLayoutData( new GridData( 100, 100 ) ); shell.setLocation( content.toDisplay( 0, 0 ) ); shell.setSize( content.getSize() ); shell.open(); } private void createMenuBar( final Shell shell) { String[] items = new String[] { "&File", "&Edit", "&Lazy", "E&xit" }; Menu bar = new Menu( shell, SWT.BAR ); shell.setMenuBar( bar ); for( String text : items ) { MenuItem menuItem = new MenuItem( bar, SWT.CASCADE ); menuItem.setText( text ); Menu dropdown = new Menu( shell, SWT.DROP_DOWN ); menuItem.setMenu( dropdown ); } - createMenuItem( bar.getItem( 0 ).getMenu(), SWT.PUSH, "Push &One" ); - createMenuItem( bar.getItem( 0 ).getMenu(), SWT.PUSH, "Push &Two" ); - createMenuItem( bar.getItem( 0 ).getMenu(), SWT.CHECK, "&Check" ); + MenuItem pushOne + = createMenuItem( bar.getItem( 0 ).getMenu(), SWT.PUSH, "Push &One\tCtrl+Shift+1" ); + pushOne.setAccelerator( SWT.CTRL | SWT.SHIFT | '1' ); + MenuItem pushTwo + = createMenuItem( bar.getItem( 0 ).getMenu(), SWT.PUSH, "Push &Two\tCtrl+Shift+2" ); + pushTwo.setAccelerator( SWT.CTRL | SWT.SHIFT | '2' ); + MenuItem check + = createMenuItem( bar.getItem( 0 ).getMenu(), SWT.CHECK, "&Check\tCtrl+C" ); + check.setAccelerator( SWT.CTRL | 'c' ); createMenuItem( bar.getItem( 0 ).getMenu(), SWT.RADIO, "Radio &X" ); createMenuItem( bar.getItem( 0 ).getMenu(), SWT.RADIO, "Radio &Y" ); createMenuItem( bar.getItem( 0 ).getMenu(), SWT.RADIO, "Radio &Z" ); createMenuItem( bar.getItem( 1 ).getMenu(), SWT.PUSH, "Push &Three" ); MenuItem casc = createMenuItem( bar.getItem( 1 ).getMenu(), SWT.CASCADE, "&Submenu" ); Menu submenu = new Menu( shell, SWT.DROP_DOWN ); casc.setMenu( submenu ); createMenuItem( submenu, SWT.CHECK, "Ch&eck" ); createMenuItem( submenu, SWT.RADIO, "Radio &8" ); createMenuItem( submenu, SWT.RADIO, "Radio &9" ); createMenuItem( bar.getItem( 2 ).getMenu(), SWT.PUSH, "Default &Item" ); crateLazyMenu( bar.getItem( 2 ) ); MenuItem close = createMenuItem( bar.getItem( 3 ).getMenu(), SWT.PUSH, "Close &Shell" ); close.addListener( SWT.Selection, new Listener() { public void handleEvent( Event event ) { shell.dispose(); } } ); } private void crateLazyMenu( MenuItem item ) { final Menu menu = item.getMenu(); menu.addListener( SWT.Show, new Listener() { public void handleEvent( Event event ) { menu.getItem( 0 ).dispose(); createMenuItem( menu, SWT.PUSH, "&Generated Item" ); } } ); } private MenuItem createMenuItem( Menu menu, int style, String text ) { final MenuItem item = new MenuItem( menu, style ); item.setText( text ); item.addListener( SWT.Selection, new Listener() { public void handleEvent( Event e ) { log( item.getText() ); } } ); return item; } private void createButtonExample( Composite content ) { createButton( content, SWT.PUSH, "Push &One" ); createButton( content, SWT.PUSH, "Push &Two" ); createButton( content, SWT.TOGGLE, "To&ggle" ); createButton( content, SWT.CHECK, "&Checkbox" ); createButton( content, SWT.RADIO, "Radio &X" ); createButton( content, SWT.RADIO, "Radio &Y" ); createButton( content, SWT.RADIO, "Radio &Z" ); } private void createToolBarExample( Composite content ) { Label label = new Label( content, SWT.NONE ); label.setText( "ToolBar:" ); ToolBar bar = new ToolBar( content, SWT.BORDER ); createToolItem( bar, SWT.PUSH, "Push &Three" ); createToolItem( bar, SWT.CHECK, "Toggl&e" ); createToolItem( bar, SWT.RADIO, "Radio &8" ); createToolItem( bar, SWT.RADIO, "Radio &9" ); GridData layoutData = new GridData(); layoutData.horizontalSpan = 3; bar.setLayoutData( layoutData ); } private void createGroupExample( Composite content ) { content.setLayout(new GridLayout( 3, false ) ); Group groupA = new Group( content, SWT.SHADOW_IN ); groupA.setText( "Group &A" ); groupA.setLayout( new GridLayout() ); groupA.setLayoutData( new GridData( SWT.FILL, SWT.FILL, false, false ) ); createText( groupA ); Group groupB = new Group( content, SWT.SHADOW_IN ); groupB.setText( "Group &B with Composite" ); groupB.setLayoutData( new GridData( SWT.FILL, SWT.FILL, false, false ) ); groupB.setLayout( new FillLayout() ); Composite comp = new Composite( groupB, SWT.BORDER ); comp.setLayout( new GridLayout() ); createText( comp ); Group groupC = new Group( content, SWT.SHADOW_IN ); groupC.setText( "Group &C" ); groupC.setLayout( new GridLayout() ); groupC.setLayoutData( new GridData( SWT.FILL, SWT.FILL, false, false ) ); createText( groupC ).setEnabled( false ); createText( groupC ).setVisible( false ); createText( groupC ); } private void createLabelExample( Composite content ) { Label label = new Label( content, SWT.NONE ); label.setText( "L&abel:" ); createText( content ); CLabel clabel = new CLabel( content, SWT.NONE ); clabel.setText( "&CLabel:" ); Button button = new Button( content, SWT.CHECK ); button.setText( "Button" ); Label labelForDisabled = new Label( content, SWT.NONE ); labelForDisabled.setText( "D&isabled:" ); createText( content ).setEnabled( false ); Label labelForInvisible = new Label( content, SWT.NONE ); labelForInvisible.setText( "In&visible:" ); createText( content ).setVisible( false ); } private Text createText( Composite content ) { Text text = new Text( content, SWT.BORDER ); text.setText( "Text" ); return text; } private void createButton( Composite content, int style, String text ) { final Button button = new Button( content, style ); button.setText( text ); button.addListener( SWT.Selection, new Listener() { public void handleEvent( Event event ) { log( button.getText() ); } } ); } private void createToolItem( ToolBar bar, int style, String text ) { final ToolItem item = new ToolItem( bar, style ); item.setText( text ); item.addListener( SWT.Selection, new Listener() { public void handleEvent( Event event ) { log( item.getText() ); } } ); } }
true
true
private void createMenuBar( final Shell shell) { String[] items = new String[] { "&File", "&Edit", "&Lazy", "E&xit" }; Menu bar = new Menu( shell, SWT.BAR ); shell.setMenuBar( bar ); for( String text : items ) { MenuItem menuItem = new MenuItem( bar, SWT.CASCADE ); menuItem.setText( text ); Menu dropdown = new Menu( shell, SWT.DROP_DOWN ); menuItem.setMenu( dropdown ); } createMenuItem( bar.getItem( 0 ).getMenu(), SWT.PUSH, "Push &One" ); createMenuItem( bar.getItem( 0 ).getMenu(), SWT.PUSH, "Push &Two" ); createMenuItem( bar.getItem( 0 ).getMenu(), SWT.CHECK, "&Check" ); createMenuItem( bar.getItem( 0 ).getMenu(), SWT.RADIO, "Radio &X" ); createMenuItem( bar.getItem( 0 ).getMenu(), SWT.RADIO, "Radio &Y" ); createMenuItem( bar.getItem( 0 ).getMenu(), SWT.RADIO, "Radio &Z" ); createMenuItem( bar.getItem( 1 ).getMenu(), SWT.PUSH, "Push &Three" ); MenuItem casc = createMenuItem( bar.getItem( 1 ).getMenu(), SWT.CASCADE, "&Submenu" ); Menu submenu = new Menu( shell, SWT.DROP_DOWN ); casc.setMenu( submenu ); createMenuItem( submenu, SWT.CHECK, "Ch&eck" ); createMenuItem( submenu, SWT.RADIO, "Radio &8" ); createMenuItem( submenu, SWT.RADIO, "Radio &9" ); createMenuItem( bar.getItem( 2 ).getMenu(), SWT.PUSH, "Default &Item" ); crateLazyMenu( bar.getItem( 2 ) ); MenuItem close = createMenuItem( bar.getItem( 3 ).getMenu(), SWT.PUSH, "Close &Shell" ); close.addListener( SWT.Selection, new Listener() { public void handleEvent( Event event ) { shell.dispose(); } } ); }
private void createMenuBar( final Shell shell) { String[] items = new String[] { "&File", "&Edit", "&Lazy", "E&xit" }; Menu bar = new Menu( shell, SWT.BAR ); shell.setMenuBar( bar ); for( String text : items ) { MenuItem menuItem = new MenuItem( bar, SWT.CASCADE ); menuItem.setText( text ); Menu dropdown = new Menu( shell, SWT.DROP_DOWN ); menuItem.setMenu( dropdown ); } MenuItem pushOne = createMenuItem( bar.getItem( 0 ).getMenu(), SWT.PUSH, "Push &One\tCtrl+Shift+1" ); pushOne.setAccelerator( SWT.CTRL | SWT.SHIFT | '1' ); MenuItem pushTwo = createMenuItem( bar.getItem( 0 ).getMenu(), SWT.PUSH, "Push &Two\tCtrl+Shift+2" ); pushTwo.setAccelerator( SWT.CTRL | SWT.SHIFT | '2' ); MenuItem check = createMenuItem( bar.getItem( 0 ).getMenu(), SWT.CHECK, "&Check\tCtrl+C" ); check.setAccelerator( SWT.CTRL | 'c' ); createMenuItem( bar.getItem( 0 ).getMenu(), SWT.RADIO, "Radio &X" ); createMenuItem( bar.getItem( 0 ).getMenu(), SWT.RADIO, "Radio &Y" ); createMenuItem( bar.getItem( 0 ).getMenu(), SWT.RADIO, "Radio &Z" ); createMenuItem( bar.getItem( 1 ).getMenu(), SWT.PUSH, "Push &Three" ); MenuItem casc = createMenuItem( bar.getItem( 1 ).getMenu(), SWT.CASCADE, "&Submenu" ); Menu submenu = new Menu( shell, SWT.DROP_DOWN ); casc.setMenu( submenu ); createMenuItem( submenu, SWT.CHECK, "Ch&eck" ); createMenuItem( submenu, SWT.RADIO, "Radio &8" ); createMenuItem( submenu, SWT.RADIO, "Radio &9" ); createMenuItem( bar.getItem( 2 ).getMenu(), SWT.PUSH, "Default &Item" ); crateLazyMenu( bar.getItem( 2 ) ); MenuItem close = createMenuItem( bar.getItem( 3 ).getMenu(), SWT.PUSH, "Close &Shell" ); close.addListener( SWT.Selection, new Listener() { public void handleEvent( Event event ) { shell.dispose(); } } ); }
diff --git a/robocode/robocode/manager/ImageManager.java b/robocode/robocode/manager/ImageManager.java index 53f1c505b..67792ae4d 100644 --- a/robocode/robocode/manager/ImageManager.java +++ b/robocode/robocode/manager/ImageManager.java @@ -1,217 +1,217 @@ /******************************************************************************* * Copyright (c) 2001, 2007 Mathew A. Nelson and Robocode contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://robocode.sourceforge.net/license/cpl-v10.html * * Contributors: * Mathew A. Nelson * - Initial API and implementation * Flemming N. Larsen * - Rewritten to support new rendering engine and to use dynamic coloring * instead of static color index * Titus Chen * - Added and integrated RenderCache which removes the eldest image from the * cache of rendered robot images when max. capacity (MAX_NUM_COLORS) of * images has been reached *******************************************************************************/ package robocode.manager; import java.awt.Color; import java.awt.Image; import java.util.*; import robocode.render.ImageUtil; import robocode.render.RenderImage; /** * @author Mathew A. Nelson (original) * @author Flemming N. Larsen (contributor) * @author Titus Chen (contributor) */ public class ImageManager { private Image[] groundImages = new Image[5]; private RenderImage[][] explosionRenderImages; private RenderImage debriseRenderImage; private Image bodyImage; private Image gunImage; private Image radarImage; private static final int MAX_NUM_COLORS = 256; private HashMap<Color, RenderImage> robotBodyImageCache = new RenderCache<Color, RenderImage>(); private HashMap<Color, RenderImage> robotGunImageCache = new RenderCache<Color, RenderImage>(); private HashMap<Color, RenderImage> robotRadarImageCache = new RenderCache<Color, RenderImage>(); public ImageManager() { initialize(); } public void initialize() { getBodyImage(); getGunImage(); getRadarImage(); getExplosionRenderImage(0, 0); } public Image getGroundTileImage(int index) { if (groundImages[index] == null) { groundImages[index] = ImageUtil.getImage("/resources/images/ground/blue_metal/blue_metal_" + index + ".png"); } return groundImages[index]; } public RenderImage getExplosionRenderImage(int which, int frame) { if (explosionRenderImages == null) { int numExplosion, numFrame; String filename; List<List<RenderImage>> explosions = new ArrayList<List<RenderImage>>(); boolean done = false; for (numExplosion = 1; !done; numExplosion++) { List<RenderImage> frames = new ArrayList<RenderImage>(); for (numFrame = 1;; numFrame++) { filename = "/resources/images/explosion/explosion" + numExplosion + '-' + numFrame + ".png"; - if (getClass().getResource(filename) == null) { + if (ClassLoader.class.getResource(filename) == null) { if (numFrame == 1) { done = true; } else { explosions.add(frames); } break; } frames.add(new RenderImage(ImageUtil.getImage(filename))); } } numExplosion = explosions.size(); explosionRenderImages = new RenderImage[numExplosion][]; for (int i = numExplosion - 1; i >= 0; i--) { - explosionRenderImages[i] = explosions.get(i).toArray(new RenderImage[0]); + explosionRenderImages[i] = explosions.get(i).toArray(new RenderImage[explosions.size()]); } } return explosionRenderImages[which][frame]; } public RenderImage getExplosionDebriseRenderImage() { if (debriseRenderImage == null) { debriseRenderImage = new RenderImage(ImageUtil.getImage("/resources/images/ground/explode_debris.png")); } return debriseRenderImage; } /** * Gets the body image * Loads from disk if necessary. * @return the body image */ private Image getBodyImage() { if (bodyImage == null) { bodyImage = ImageUtil.getImage("/resources/images/body.png"); } return bodyImage; } /** * Gets the gun image * Loads from disk if necessary. * @return the gun image */ private Image getGunImage() { if (gunImage == null) { gunImage = ImageUtil.getImage("/resources/images/turret.png"); } return gunImage; } /** * Gets the radar image * Loads from disk if necessary. * @return the radar image */ private Image getRadarImage() { if (radarImage == null) { radarImage = ImageUtil.getImage("/resources/images/radar.png"); } return radarImage; } public RenderImage getColoredBodyRenderImage(Color color) { RenderImage img = robotBodyImageCache.get(color); if (img == null) { img = new RenderImage(ImageUtil.createColouredRobotImage(getBodyImage(), color)); robotBodyImageCache.put(color, img); } return img; } public RenderImage getColoredGunRenderImage(Color color) { RenderImage img = robotGunImageCache.get(color); if (img == null) { img = new RenderImage(ImageUtil.createColouredRobotImage(getGunImage(), color)); robotGunImageCache.put(color, img); } return img; } public RenderImage getColoredRadarRenderImage(Color color) { RenderImage img = robotRadarImageCache.get(color); if (img == null) { img = new RenderImage(ImageUtil.createColouredRobotImage(getRadarImage(), color)); robotRadarImageCache.put(color, img); } return img; } /** * Class used for caching rendered robot parts in various colors. * * @author Titus Chen */ @SuppressWarnings("serial") private static class RenderCache<K, V> extends LinkedHashMap<K, V> { /* Note about initial capacity: * To avoid rehashing (inefficient though probably unavoidable), initial * capacity must be at least 1 greater than the maximum capacity. * However, initial capacities are set to the smallest power of 2 greater * than or equal to the passed argument, resulting in 512 with this code. * I was not aware of this before, but notice: the current implementation * behaves similarly. The simple solution would be to set maximum capacity * to 255, but the problem with doing so is that in a battle of 256 robots * of different colors, the net result would end up being real-time * rendering due to the nature of access ordering. However, 256 robot * battles are rarely fought. */ private static final int INITIAL_CAPACITY = MAX_NUM_COLORS + 1; private static final float LOAD_FACTOR = 1; public RenderCache() { /* The "true" parameter needed for access-order: * when cache fills, the least recently accessed entry is removed */ super(INITIAL_CAPACITY, LOAD_FACTOR, true); } @Override protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { return size() > MAX_NUM_COLORS; } } }
false
true
public RenderImage getExplosionRenderImage(int which, int frame) { if (explosionRenderImages == null) { int numExplosion, numFrame; String filename; List<List<RenderImage>> explosions = new ArrayList<List<RenderImage>>(); boolean done = false; for (numExplosion = 1; !done; numExplosion++) { List<RenderImage> frames = new ArrayList<RenderImage>(); for (numFrame = 1;; numFrame++) { filename = "/resources/images/explosion/explosion" + numExplosion + '-' + numFrame + ".png"; if (getClass().getResource(filename) == null) { if (numFrame == 1) { done = true; } else { explosions.add(frames); } break; } frames.add(new RenderImage(ImageUtil.getImage(filename))); } } numExplosion = explosions.size(); explosionRenderImages = new RenderImage[numExplosion][]; for (int i = numExplosion - 1; i >= 0; i--) { explosionRenderImages[i] = explosions.get(i).toArray(new RenderImage[0]); } } return explosionRenderImages[which][frame]; }
public RenderImage getExplosionRenderImage(int which, int frame) { if (explosionRenderImages == null) { int numExplosion, numFrame; String filename; List<List<RenderImage>> explosions = new ArrayList<List<RenderImage>>(); boolean done = false; for (numExplosion = 1; !done; numExplosion++) { List<RenderImage> frames = new ArrayList<RenderImage>(); for (numFrame = 1;; numFrame++) { filename = "/resources/images/explosion/explosion" + numExplosion + '-' + numFrame + ".png"; if (ClassLoader.class.getResource(filename) == null) { if (numFrame == 1) { done = true; } else { explosions.add(frames); } break; } frames.add(new RenderImage(ImageUtil.getImage(filename))); } } numExplosion = explosions.size(); explosionRenderImages = new RenderImage[numExplosion][]; for (int i = numExplosion - 1; i >= 0; i--) { explosionRenderImages[i] = explosions.get(i).toArray(new RenderImage[explosions.size()]); } } return explosionRenderImages[which][frame]; }
diff --git a/org.eclipse.mylyn.tasks.core/src/org/eclipse/mylyn/tasks/core/TaskRepositoryManager.java b/org.eclipse.mylyn.tasks.core/src/org/eclipse/mylyn/tasks/core/TaskRepositoryManager.java index 4ab4ea2ad..58935660f 100644 --- a/org.eclipse.mylyn.tasks.core/src/org/eclipse/mylyn/tasks/core/TaskRepositoryManager.java +++ b/org.eclipse.mylyn.tasks.core/src/org/eclipse/mylyn/tasks/core/TaskRepositoryManager.java @@ -1,355 +1,357 @@ /******************************************************************************* * Copyright (c) 2004 - 2006 University Of British Columbia and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * University Of British Columbia - initial API and implementation *******************************************************************************/ package org.eclipse.mylar.tasks.core; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.Platform; import org.eclipse.mylar.context.core.MylarStatusHandler; import org.eclipse.mylar.internal.tasks.core.TaskRepositoriesExternalizer; /** * @author Mik Kersten * @author Rob Elves */ public class TaskRepositoryManager { public static final String OLD_REPOSITORIES_FILE = "repositories.xml"; public static final String DEFAULT_REPOSITORIES_FILE = "repositories.xml.zip"; public static final String PREF_REPOSITORIES = "org.eclipse.mylar.tasklist.repositories."; private Map<String, AbstractRepositoryConnector> repositoryConnectors = new HashMap<String, AbstractRepositoryConnector>(); private Map<String, Set<TaskRepository>> repositoryMap = new HashMap<String, Set<TaskRepository>>(); private Set<ITaskRepositoryListener> listeners = new HashSet<ITaskRepositoryListener>(); private Set<TaskRepository> orphanedRepositories = new HashSet<TaskRepository>(); public static final String MESSAGE_NO_REPOSITORY = "No repository available, please add one using the Task Repositories view."; public static final String PREFIX_LOCAL = "local-"; private TaskRepositoriesExternalizer externalizer = new TaskRepositoriesExternalizer(); private TaskList taskList; public TaskRepositoryManager(TaskList taskList) { this.taskList = taskList; } public Collection<AbstractRepositoryConnector> getRepositoryConnectors() { return Collections.unmodifiableCollection(repositoryConnectors.values()); } public AbstractRepositoryConnector getRepositoryConnector(String kind) { return repositoryConnectors.get(kind); } public AbstractRepositoryConnector getRepositoryConnector(AbstractRepositoryTask task) { return getRepositoryConnector(task.getRepositoryKind()); } public void addRepositoryConnector(AbstractRepositoryConnector repositoryConnector) { if (!repositoryConnectors.values().contains(repositoryConnector)) { repositoryConnector.init(taskList); repositoryConnectors.put(repositoryConnector.getRepositoryType(), repositoryConnector); } } public void addRepository(TaskRepository repository, String repositoryFilePath) { Set<TaskRepository> repositories; if (!repositoryMap.containsKey(repository.getKind())) { repositories = new HashSet<TaskRepository>(); repositoryMap.put(repository.getKind(), repositories); } else { repositories = repositoryMap.get(repository.getKind()); } repositories.add(repository); saveRepositories(repositoryFilePath); for (ITaskRepositoryListener listener : listeners) { listener.repositoryAdded(repository); } } public void removeRepository(TaskRepository repository, String repositoryFilePath) { Set<TaskRepository> repositories = repositoryMap.get(repository.getKind()); if (repositories != null) { repository.flushAuthenticationCredentials(); repositories.remove(repository); } saveRepositories(repositoryFilePath); for (ITaskRepositoryListener listener : listeners) { listener.repositoryRemoved(repository); } } public void addListener(ITaskRepositoryListener listener) { listeners.add(listener); } public void removeListener(ITaskRepositoryListener listener) { listeners.remove(listener); } public TaskRepository getRepository(String kind, String urlString) { if (repositoryMap.containsKey(kind)) { for (TaskRepository repository : repositoryMap.get(kind)) { if (repository.getUrl().equals(urlString)) { return repository; } } } return null; } /** * @return first repository that matches the given url */ public TaskRepository getRepository(String urlString) { for (String kind : repositoryMap.keySet()) { for (TaskRepository repository : repositoryMap.get(kind)) { if (repository.getUrl().equals(urlString)) { return repository; } } } return null; } /** * @return the first connector to accept the URL */ public AbstractRepositoryConnector getConnectorForRepositoryTaskUrl(String url) { for (AbstractRepositoryConnector connector : getRepositoryConnectors()) { if (connector.getRepositoryUrlFromTaskUrl(url) != null) { return connector; } } return null; } public Set<TaskRepository> getRepositories(String kind) { if (repositoryMap.containsKey(kind)) { return repositoryMap.get(kind); } else { return Collections.emptySet(); } } public List<TaskRepository> getAllRepositories() { List<TaskRepository> repositories = new ArrayList<TaskRepository>(); for (AbstractRepositoryConnector repositoryConnector : repositoryConnectors.values()) { if (repositoryMap.containsKey(repositoryConnector.getRepositoryType())) { repositories.addAll(repositoryMap.get(repositoryConnector.getRepositoryType())); } } return repositories; } public TaskRepository getRepositoryForActiveTask(String repositoryKind, TaskList taskList) { List<ITask> activeTasks = taskList.getActiveTasks(); if (activeTasks.size() == 1) { ITask activeTask = activeTasks.get(0); if (activeTask instanceof AbstractRepositoryTask) { String repositoryUrl = AbstractRepositoryTask.getRepositoryUrl(activeTask.getHandleIdentifier()); for (TaskRepository repository : getRepositories(repositoryKind)) { if (repository.getUrl().equals(repositoryUrl)) { return repository; } } } } return null; } /** * TODO: implement default support, this just returns first found */ public TaskRepository getDefaultRepository(String kind) { // HACK: returns first repository found if (repositoryMap.containsKey(kind)) { for (TaskRepository repository : repositoryMap.get(kind)) { return repository; } } else { Collection<Set<TaskRepository>> values = repositoryMap.values(); if (!values.isEmpty()) { Set<TaskRepository> repoistorySet = values.iterator().next(); return (TaskRepository) repoistorySet.iterator().next(); } } return null; } public Map<String, Set<TaskRepository>> readRepositories(String repositoriesFilePath) { repositoryMap.clear(); orphanedRepositories.clear(); loadRepositories(repositoriesFilePath); for (ITaskRepositoryListener listener : listeners) { listener.repositoriesRead(); } return repositoryMap; } private void loadRepositories(String repositoriesFilePath) { try { // String dataDirectory = // TasksUiPlugin.getDefault().getDataDirectory(); File repositoriesFile = new File(repositoriesFilePath); // Will only load repositories for which a connector exists for (AbstractRepositoryConnector repositoryConnector : repositoryConnectors.values()) { repositoryMap.put(repositoryConnector.getRepositoryType(), new HashSet<TaskRepository>()); } if (repositoriesFile.exists()) { Set<TaskRepository> repositories = externalizer.readRepositoriesFromXML(repositoriesFile); if (repositories != null && repositories.size() > 0) { for (TaskRepository repository : repositories) { if (repositoryMap.containsKey(repository.getKind())) { repositoryMap.get(repository.getKind()).add(repository); } else { orphanedRepositories.add(repository); } } } } } catch (Throwable t) { MylarStatusHandler.fail(t, "could not load repositories", false); } } /** * for testing purposes */ public void setVersion(TaskRepository repository, String version, String repositoriesFilePath) { repository.setVersion(version); saveRepositories(repositoriesFilePath); } /** * for testing purposes */ public void setEncoding(TaskRepository repository, String encoding, String repositoriesFilePath) { repository.setCharacterEncoding(encoding); saveRepositories(repositoriesFilePath); } /** * for testing purposes */ public void setTimeZoneId(TaskRepository repository, String timeZoneId, String repositoriesFilePath) { repository.setTimeZoneId(timeZoneId); saveRepositories(repositoriesFilePath); } public void setSyncTime(TaskRepository repository, String syncTime, String repositoriesFilePath) { repository.setSyncTimeStamp(syncTime); saveRepositories(repositoriesFilePath); // String prefIdSyncTime = repository.getUrl() + PROPERTY_DELIM + // PROPERTY_SYNCTIMESTAMP; // if (repository.getSyncTimeStamp() != null) { // MylarTaskListPlugin.getMylarCorePrefs().setValue(prefIdSyncTime, // repository.getSyncTimeStamp()); // } } public boolean saveRepositories(String destinationPath) { if (!Platform.isRunning()) {// || TasksUiPlugin.getDefault() == null) { return false; } Set<TaskRepository> repositoriesToWrite = new HashSet<TaskRepository>(getAllRepositories()); // if for some reason a repository is added/changed to equal one in the // orphaned set the orphan is discarded for (TaskRepository repository : orphanedRepositories) { if (!repositoriesToWrite.contains(repository)) { repositoriesToWrite.add(repository); } } try { // String dataDirectory = // TasksUiPlugin.getDefault().getDataDirectory(); // File repositoriesFile = new File(dataDirectory + File.separator + // TasksUiPlugin.DEFAULT_REPOSITORIES_FILE); File repositoriesFile = new File(destinationPath); externalizer.writeRepositoriesToXML(repositoriesToWrite, repositoriesFile); } catch (Throwable t) { MylarStatusHandler.fail(t, "could not save repositories", false); return false; } return true; } /** * For testing. */ public void clearRepositories(String repositoriesFilePath) { repositoryMap.clear(); orphanedRepositories.clear(); saveRepositories(repositoriesFilePath); // for (AbstractRepositoryConnector repositoryConnector : // repositoryConnectors.values()) { // String prefId = PREF_REPOSITORIES + // repositoryConnector.getRepositoryType(); // MylarTaskListPlugin.getMylarCorePrefs().setValue(prefId, ""); // } } public void notifyRepositorySettingsChagned(TaskRepository repository) { for (ITaskRepositoryListener listener : listeners) { listener.repositorySettingsChanged(repository); } } // TODO: run with progress public String getAttachmentContents(RepositoryAttachment attachment) { StringBuffer contents = new StringBuffer(); try { AbstractRepositoryConnector connector = getRepositoryConnector( attachment.getRepository().getKind()); IAttachmentHandler handler = connector.getAttachmentHandler(); InputStream stream; stream = new ByteArrayInputStream(handler.getAttachmentData(attachment.getRepository(), "" + attachment.getId())); int c; while ((c = stream.read()) != -1) { /* TODO jpound - handle non-text */ contents.append((char) c); } stream.close(); } catch (CoreException e) { MylarStatusHandler.fail(e.getStatus().getException(), "Retrieval of attachment data failed.", false); + return null; } catch (IOException e) { MylarStatusHandler.fail(e, "Retrieval of attachment data failed.", false); + return null; } return contents.toString(); } }
false
true
public boolean saveRepositories(String destinationPath) { if (!Platform.isRunning()) {// || TasksUiPlugin.getDefault() == null) { return false; } Set<TaskRepository> repositoriesToWrite = new HashSet<TaskRepository>(getAllRepositories()); // if for some reason a repository is added/changed to equal one in the // orphaned set the orphan is discarded for (TaskRepository repository : orphanedRepositories) { if (!repositoriesToWrite.contains(repository)) { repositoriesToWrite.add(repository); } } try { // String dataDirectory = // TasksUiPlugin.getDefault().getDataDirectory(); // File repositoriesFile = new File(dataDirectory + File.separator + // TasksUiPlugin.DEFAULT_REPOSITORIES_FILE); File repositoriesFile = new File(destinationPath); externalizer.writeRepositoriesToXML(repositoriesToWrite, repositoriesFile); } catch (Throwable t) { MylarStatusHandler.fail(t, "could not save repositories", false); return false; } return true; } /** * For testing. */ public void clearRepositories(String repositoriesFilePath) { repositoryMap.clear(); orphanedRepositories.clear(); saveRepositories(repositoriesFilePath); // for (AbstractRepositoryConnector repositoryConnector : // repositoryConnectors.values()) { // String prefId = PREF_REPOSITORIES + // repositoryConnector.getRepositoryType(); // MylarTaskListPlugin.getMylarCorePrefs().setValue(prefId, ""); // } } public void notifyRepositorySettingsChagned(TaskRepository repository) { for (ITaskRepositoryListener listener : listeners) { listener.repositorySettingsChanged(repository); } } // TODO: run with progress public String getAttachmentContents(RepositoryAttachment attachment) { StringBuffer contents = new StringBuffer(); try { AbstractRepositoryConnector connector = getRepositoryConnector( attachment.getRepository().getKind()); IAttachmentHandler handler = connector.getAttachmentHandler(); InputStream stream; stream = new ByteArrayInputStream(handler.getAttachmentData(attachment.getRepository(), "" + attachment.getId())); int c; while ((c = stream.read()) != -1) { /* TODO jpound - handle non-text */ contents.append((char) c); } stream.close(); } catch (CoreException e) { MylarStatusHandler.fail(e.getStatus().getException(), "Retrieval of attachment data failed.", false); } catch (IOException e) { MylarStatusHandler.fail(e, "Retrieval of attachment data failed.", false); } return contents.toString(); } }
public boolean saveRepositories(String destinationPath) { if (!Platform.isRunning()) {// || TasksUiPlugin.getDefault() == null) { return false; } Set<TaskRepository> repositoriesToWrite = new HashSet<TaskRepository>(getAllRepositories()); // if for some reason a repository is added/changed to equal one in the // orphaned set the orphan is discarded for (TaskRepository repository : orphanedRepositories) { if (!repositoriesToWrite.contains(repository)) { repositoriesToWrite.add(repository); } } try { // String dataDirectory = // TasksUiPlugin.getDefault().getDataDirectory(); // File repositoriesFile = new File(dataDirectory + File.separator + // TasksUiPlugin.DEFAULT_REPOSITORIES_FILE); File repositoriesFile = new File(destinationPath); externalizer.writeRepositoriesToXML(repositoriesToWrite, repositoriesFile); } catch (Throwable t) { MylarStatusHandler.fail(t, "could not save repositories", false); return false; } return true; } /** * For testing. */ public void clearRepositories(String repositoriesFilePath) { repositoryMap.clear(); orphanedRepositories.clear(); saveRepositories(repositoriesFilePath); // for (AbstractRepositoryConnector repositoryConnector : // repositoryConnectors.values()) { // String prefId = PREF_REPOSITORIES + // repositoryConnector.getRepositoryType(); // MylarTaskListPlugin.getMylarCorePrefs().setValue(prefId, ""); // } } public void notifyRepositorySettingsChagned(TaskRepository repository) { for (ITaskRepositoryListener listener : listeners) { listener.repositorySettingsChanged(repository); } } // TODO: run with progress public String getAttachmentContents(RepositoryAttachment attachment) { StringBuffer contents = new StringBuffer(); try { AbstractRepositoryConnector connector = getRepositoryConnector( attachment.getRepository().getKind()); IAttachmentHandler handler = connector.getAttachmentHandler(); InputStream stream; stream = new ByteArrayInputStream(handler.getAttachmentData(attachment.getRepository(), "" + attachment.getId())); int c; while ((c = stream.read()) != -1) { /* TODO jpound - handle non-text */ contents.append((char) c); } stream.close(); } catch (CoreException e) { MylarStatusHandler.fail(e.getStatus().getException(), "Retrieval of attachment data failed.", false); return null; } catch (IOException e) { MylarStatusHandler.fail(e, "Retrieval of attachment data failed.", false); return null; } return contents.toString(); } }
diff --git a/signserver/src/java/org/signserver/server/PropertyFileStore.java b/signserver/src/java/org/signserver/server/PropertyFileStore.java index 3db99ff39..94b8ed1bf 100644 --- a/signserver/src/java/org/signserver/server/PropertyFileStore.java +++ b/signserver/src/java/org/signserver/server/PropertyFileStore.java @@ -1,260 +1,260 @@ /************************************************************************* * * * SignServer: The OpenSource Automated Signing Server * * * * This software 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 any later version. * * * * See terms of license at gnu.org. * * * *************************************************************************/ package org.signserver.server; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Iterator; import java.util.Properties; import org.apache.log4j.Logger; import org.signserver.common.GlobalConfiguration; import org.signserver.common.WorkerConfig; /** * Class in charge of storing/loading the current configuration from file * in a Property format. This is used in the MailSigner build. * * It manages GlobalConfiguration and WorkerConfigurations in much the same way * as the EJB variant, but in the back-end stores everything to file. * * @author Philip Vendil * @version $Id: PropertyFileStore.java,v 1.1 2007-10-28 12:26:12 herrvendil Exp $ */ public class PropertyFileStore { /** Log4j instance for actual implementation class */ public static transient Logger log = Logger.getLogger(PropertyFileStore.class); private static PropertyFileStore instance = null; private final String fileLocation; private Properties propertyStore; /** * Method used to retrieve the PropertyFileStore. * * @return the singleton instance of the PropertyFileStore */ public static PropertyFileStore getInstance(){ if(instance == null){ String phoenixhome = System.getenv("PHOENIX_HOME"); File confDir = new File(phoenixhome +"/conf"); if(phoenixhome != null && confDir.exists()){ - instance = new PropertyFileStore(phoenixhome +"/james/conf/mailsignerdata.properties"); + instance = new PropertyFileStore(phoenixhome +"/conf/mailsignerdata.properties"); } } if(instance == null){ String signserverhome = System.getenv("SIGNSERVER_HOME"); if(signserverhome == null){ log.error("Error: Environment variable SIGNSERVER_HOME isn't set"); } instance = new PropertyFileStore(signserverhome +"/extapps/james/conf/mailsignerdata.properties"); } return instance; } /** * Method used to retrieve the PropertyFileStore from a specified (non-default) * storage location. This method should only be used from automated testscripts. * * @param fileLocation the path to the property file to use. * @return the singleton instance of the PropertyFileStore */ public static PropertyFileStore getInstance(String fileLocation){ if(instance == null){ instance = new PropertyFileStore(fileLocation); } return instance; } private PropertyFileStore(String fileLocation) { this.fileLocation = fileLocation; init(); } /** * Method that reads the property file and initializes the current properties. */ private void init() { propertyStore = new Properties(); File file = new File(fileLocation); if(file.exists() && !file.isDirectory()){ try { propertyStore.load(new FileInputStream(file)); } catch (Exception e) { log.error("Error reading global property file : " + fileLocation + ", Exception :" ,e ); } } } /** * Method used to reload the current configuration. */ public void reload(){ init(); } /** * Method used to reload the current configuration. */ private void save(){ try { FileOutputStream fos = new FileOutputStream(fileLocation); propertyStore.store(fos, "SignServer/MailServer Configuration Store. Only edit this file if you know what you are doing."); } catch (IOException e) { log.error("Error saving global property file : " + fileLocation + ", Exception :" ,e ); } } /** * Method used to set a global property value to the backed property file. * * @param scope scope one of GlobalConfiguration.SCOPE_ constants * @param key the key used * @param value of the configuration. */ public void setGlobalProperty(String scope, String key, String value){ propertyStore.setProperty(propertyKeyHelper(scope, key), value); save(); } /** * Method used to remove a global property value to the backed property file. * * @param scope scope one of GlobalConfiguration.SCOPE_ constants * @param key the key used */ public void removeGlobalProperty(String scope, String key){ propertyStore.remove(propertyKeyHelper(scope, key)); save(); reload(); } /** * Returns the current GlobalConfiguration read from file. * */ public GlobalConfiguration getGlobalConfiguration(){ Properties properties = new Properties(); Iterator<Object> iter = propertyStore.keySet().iterator(); while(iter.hasNext()){ String rawkey = (String) iter.next(); if(rawkey.startsWith(GlobalConfiguration.SCOPE_NODE)){ String key = rawkey.replaceFirst(WorkerConfig.getNodeId() + ".", ""); properties.setProperty(key, propertyStore.getProperty(rawkey)); }else{ if(rawkey.startsWith(GlobalConfiguration.SCOPE_GLOBAL)){ properties.setProperty(rawkey, propertyStore.getProperty(rawkey)); } } } GlobalConfiguration retval = new GlobalConfiguration(properties, GlobalConfiguration.STATE_INSYNC); return retval; } /** * Method returning the WorkerConfig for the given workerID * @param workerId unique Id of the worker * @return the WorkerConfig if the given Id isn't configured in the global * configuration never null. */ public WorkerConfig getWorkerProperties(int workerId){ WorkerConfig workerConfig = new WorkerConfig(); Iterator<Object> iter = propertyStore.keySet().iterator(); String workerPrefix = GlobalConfiguration.WORKERPROPERTY_BASE + workerId+ "."; while(iter.hasNext()){ String rawkey = (String) iter.next(); if(rawkey.startsWith(workerPrefix)){ String key = rawkey.substring(workerPrefix.length()); workerConfig.setProperty(key, propertyStore.getProperty(rawkey)); } } return workerConfig; } /** * Method used to set a specific worker property. * */ public void setWorkerProperty(int workerId, String key, String value){ propertyStore.setProperty(GlobalConfiguration.WORKERPROPERTY_BASE + workerId + "." + key.toUpperCase(), value); save(); } /** * Method used to remove a specific worker property. * */ public void removeWorkerProperty(int workerId, String key){ propertyStore.remove(GlobalConfiguration.WORKERPROPERTY_BASE + workerId + "." + key.toUpperCase()); save(); } /** * Method used to remove all properties associated to a workerId * @param workerId unique id of worker to remove all properties for. */ public void removeAllWorkerProperties(int workerId){ Iterator<Object> iter = propertyStore.keySet().iterator(); String workerPrefix = GlobalConfiguration.WORKERPROPERTY_BASE + workerId+ "."; while(iter.hasNext()){ String rawkey = (String) iter.next(); if(rawkey.startsWith(workerPrefix)){ propertyStore.remove(rawkey); } } save(); } /** * Help method used to set the correct key naming in the global properites * @param scope one of GlobalConfiguration.SCOPE_ constants * @param key the key value * @return the raw key value to store in the property file. */ private String propertyKeyHelper(String scope, String key){ String retval = null; String tempKey = key.toUpperCase(); if(scope.equals(GlobalConfiguration.SCOPE_NODE)){ retval = GlobalConfiguration.SCOPE_NODE + WorkerConfig.getNodeId() + "." + tempKey; }else{ if(scope.equals(GlobalConfiguration.SCOPE_GLOBAL)){ retval = GlobalConfiguration.SCOPE_GLOBAL + tempKey; }else{ log.error("Error : Invalid scope " + scope ); } } return retval; } }
true
true
public static PropertyFileStore getInstance(){ if(instance == null){ String phoenixhome = System.getenv("PHOENIX_HOME"); File confDir = new File(phoenixhome +"/conf"); if(phoenixhome != null && confDir.exists()){ instance = new PropertyFileStore(phoenixhome +"/james/conf/mailsignerdata.properties"); } } if(instance == null){ String signserverhome = System.getenv("SIGNSERVER_HOME"); if(signserverhome == null){ log.error("Error: Environment variable SIGNSERVER_HOME isn't set"); } instance = new PropertyFileStore(signserverhome +"/extapps/james/conf/mailsignerdata.properties"); } return instance; }
public static PropertyFileStore getInstance(){ if(instance == null){ String phoenixhome = System.getenv("PHOENIX_HOME"); File confDir = new File(phoenixhome +"/conf"); if(phoenixhome != null && confDir.exists()){ instance = new PropertyFileStore(phoenixhome +"/conf/mailsignerdata.properties"); } } if(instance == null){ String signserverhome = System.getenv("SIGNSERVER_HOME"); if(signserverhome == null){ log.error("Error: Environment variable SIGNSERVER_HOME isn't set"); } instance = new PropertyFileStore(signserverhome +"/extapps/james/conf/mailsignerdata.properties"); } return instance; }
diff --git a/src/main/java/org/spout/api/inventory/ItemStack.java b/src/main/java/org/spout/api/inventory/ItemStack.java index 0aa4e85d1..cc534b190 100644 --- a/src/main/java/org/spout/api/inventory/ItemStack.java +++ b/src/main/java/org/spout/api/inventory/ItemStack.java @@ -1,390 +1,391 @@ /* * This file is part of SpoutAPI. * * Copyright (c) 2011-2012, Spout LLC <http://www.spout.org/> * SpoutAPI is licensed under the Spout License Version 1. * * SpoutAPI 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. * * SpoutAPI 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://spout.in/licensev1> for the full license, including * the MIT license. */ package org.spout.api.inventory; import java.io.IOException; import java.io.Serializable; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.spout.api.datatable.ManagedHashMap; import org.spout.api.datatable.SerializableMap; import org.spout.api.map.DefaultedMap; import org.spout.api.material.Material; import org.spout.api.material.MaterialRegistry; import org.spout.api.material.source.DataSource; import org.spout.api.material.source.GenericMaterialAccess; import org.spout.api.material.source.MaterialSource; import org.spout.api.util.LogicUtil; import org.spout.nbt.CompoundMap; import org.spout.nbt.CompoundTag; import org.spout.nbt.stream.NBTInputStream; import org.spout.nbt.stream.NBTOutputStream; /** * Represents a stack of items */ public class ItemStack extends GenericMaterialAccess implements Serializable, Cloneable { private static final long serialVersionUID = 1L; private int amount; private CompoundMap nbtData = null; private SerializableMap auxData; /** * Creates a new ItemStack from the specified Material of the specified * amount */ public ItemStack(Material material, int amount) { this(material, material.getData(), amount); } /** * Creates a new ItemStack from the specified Material and data of the * specified amount */ public ItemStack(Material material, int data, int amount) { this(material, data, amount, null); } /** * Creates a new ItemStack from the specified Material and data of the * specified amount, with the specified aux data */ public ItemStack(Material material, int data, int amount, SerializableMap auxData) { super(material, data); this.amount = amount; if (auxData != null) { this.auxData = auxData; } else { this.auxData = new ManagedHashMap(); } } /** * Gets the Material of the stack * @return the material */ @Override public Material getMaterial() { return super.getMaterial(); } /** * Gets the amount of the Material contained in the item stack * @return the amount */ public int getAmount() { return amount; } /** * Sets amount of the Material contained in the item stack * @param amount the amount */ public ItemStack setAmount(int amount) { this.amount = amount; return this; } /** * Gets whether this item stack is empty * @return whether the amount equals zero */ public boolean isEmpty() { return this.amount == 0; } @Override public boolean isMaterial(Material... materials) { if (this.material == null) { for (Material material : materials) { if (material == null) { return true; } } return false; } else { return this.material.isMaterial(materials); } } @Override public ItemStack setMaterial(MaterialSource material) { return (ItemStack) super.setMaterial(material); } @Override public ItemStack setMaterial(MaterialSource material, DataSource datasource) { return (ItemStack) super.setMaterial(material, datasource); } @Override public ItemStack setMaterial(MaterialSource material, int data) { return (ItemStack) super.setMaterial(material, data); } /** * Gets the map containing the aux data for this stack * @return the aux data */ public DefaultedMap<Serializable> getAuxData() { return auxData; } /** * returns a copy of the map containing the aux data for this stack * @return the aux data */ public CompoundMap getNBTData() { if (nbtData == null) { return null; } return new CompoundMap(nbtData); } /** * Sets the aux data for this stack * @return the item stack */ public ItemStack setNBTData(CompoundMap nbtData) { if (nbtData == null) { this.nbtData = null; } else { this.nbtData = new CompoundMap(nbtData); } return this; } /** * If the item is null or empty, null is returned, otherwise the item is * cloned * @param item to clone * @return null, or the cloned item */ public static ItemStack cloneSpecial(ItemStack item) { return item == null || item.isEmpty() ? null : item.clone(); } @Override public ItemStack clone() { ItemStack newStack = new ItemStack(material, data, amount, auxData); newStack.setNBTData(nbtData); return newStack; } @Override public int hashCode() { return new HashCodeBuilder(91, 15).append(material).append(auxData).append(nbtData).append(amount).toHashCode(); } @Override public boolean equals(Object other) { if (!(other instanceof ItemStack)) { return false; } ItemStack stack = (ItemStack) other; return equalsIgnoreSize(stack) && amount == stack.amount; } public boolean equalsIgnoreSize(ItemStack other) { if (other == null) { return false; } return material.equals(other.material) && data == other.data && auxData.equals(other.auxData) && LogicUtil.bothNullOrEqual(nbtData, other.nbtData); } @Override public String toString() { return "ItemStack{" + "material=" + material + ",id=" + material.getId() + ",data=" + data + ",amount=" + amount + ",nbtData=" + nbtData + '}'; } @Override public ItemStack setData(DataSource datasource) { return this.setData(datasource.getData()); } @Override public ItemStack setData(int data) { this.data = (short) data; this.material = this.material.getRoot().getSubMaterial(this.data); return this; } @Override public short getData() { return this.data; } /** * Gets this item stack limited by the maximum stacking size<br> * The amount of this item stack is set to contain the remaining amount<br> * The amount of the returned stack is set to be this amount or the maximum * stacking size<br><br> * <p/> * For example, limiting a stack of amount 120 to a max stacking size of 64 * will: * <ul> * <li>Set the amount of this item stack to 56 * <li>Return an item stack with amount 64 * </ul> * @return the limited stack */ public ItemStack limitStackSize() { return this.limitSize(this.getMaxStackSize()); } /** * Gets this item stack limited by the maximum size specified<br> * The amount of this item stack is set to contain the remaining amount<br> * The amount of the returned stack is set to be this amount or the maximum * amount<br><br> * <p/> * For example, limiting a stack of amount 5 to a max size of 2 will: * <ul> * <li>Set the amount of this item stack to 3 * <li>Return an item stack with amount 2 * </ul> * @return the limited stack */ public ItemStack limitSize(int maxSize) { ItemStack stack = this.clone(); if (stack.getAmount() <= maxSize) { this.setAmount(0); } else { stack.setAmount(maxSize); this.setAmount(this.getAmount() - maxSize); } return stack; } /** * Tries to stack an item on top of this item<br> * The item must have the same properties as this item stack<br> * The amount of this item is kept below the max stacking size<br><br> * <p/> * The input item amount is affected<br> * If true is returned, this amount is 0, otherwise it is the amount it * didn't stack into this item * @param item to stack * @return True if stacking was successful, False otherwise */ public boolean stack(ItemStack item) { if (!this.equalsIgnoreSize(item)) { return false; } final int maxsize = this.getMaxStackSize(); final int combinedSize = this.getAmount() + item.getAmount(); if (combinedSize > maxsize) { this.setAmount(maxsize); item.setAmount(combinedSize - maxsize); return false; } this.setAmount(combinedSize); item.setAmount(0); return true; } /** * Gets the maximum size this {@link ItemStack} can be using the material * it has * @return the max stack size */ public int getMaxStackSize() { if (!auxData.isEmpty() || (nbtData != null && !nbtData.isEmpty())) { return 1; } return this.getMaterial().getMaxStackSize(); } /** * Gets the maximum data this {@link ItemStack} can have using the material * it has * @return the max data */ public short getMaxData() { return this.getMaterial().getMaxData(); } //Custom serialization logic because material & auxData can not be made // serializable private void writeObject(java.io.ObjectOutputStream out) throws IOException { out.writeShort(material.getId()); out.writeShort(material.getData()); out.writeInt(amount); out.writeShort(data); byte[] auxData = this.auxData.serialize(); if (auxData != null) { out.writeInt(auxData.length); out.write(auxData); } else { out.writeInt(0); } if (nbtData != null && !nbtData.isEmpty()) { out.writeBoolean(true); NBTOutputStream os = new NBTOutputStream(out, false); os.writeTag(new CompoundTag("nbtData", nbtData)); os.close(); } else { out.writeBoolean(false); } } private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { short matId = in.readShort(); short matData = in.readShort(); material = MaterialRegistry.get(matId); if (matData != 0 && material != null) { material = material.getSubMaterial(matData); } amount = in.readInt(); data = in.readShort(); int auxDataSize = in.readInt(); if (auxDataSize > 0) { byte[] auxData = new byte[auxDataSize]; + in.read(auxData); ManagedHashMap map = new ManagedHashMap(); map.deserialize(auxData); this.auxData = map; } boolean hasNBTData = in.readBoolean(); if (hasNBTData) { NBTInputStream is = new NBTInputStream(in, false); CompoundTag tag = (CompoundTag) is.readTag(); nbtData = tag.getValue(); is.close(); } if (material == null) { throw new ClassNotFoundException("No material matching {" + matId + ", " + matData + "} was found!"); } } }
true
true
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { short matId = in.readShort(); short matData = in.readShort(); material = MaterialRegistry.get(matId); if (matData != 0 && material != null) { material = material.getSubMaterial(matData); } amount = in.readInt(); data = in.readShort(); int auxDataSize = in.readInt(); if (auxDataSize > 0) { byte[] auxData = new byte[auxDataSize]; ManagedHashMap map = new ManagedHashMap(); map.deserialize(auxData); this.auxData = map; } boolean hasNBTData = in.readBoolean(); if (hasNBTData) { NBTInputStream is = new NBTInputStream(in, false); CompoundTag tag = (CompoundTag) is.readTag(); nbtData = tag.getValue(); is.close(); } if (material == null) { throw new ClassNotFoundException("No material matching {" + matId + ", " + matData + "} was found!"); } }
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { short matId = in.readShort(); short matData = in.readShort(); material = MaterialRegistry.get(matId); if (matData != 0 && material != null) { material = material.getSubMaterial(matData); } amount = in.readInt(); data = in.readShort(); int auxDataSize = in.readInt(); if (auxDataSize > 0) { byte[] auxData = new byte[auxDataSize]; in.read(auxData); ManagedHashMap map = new ManagedHashMap(); map.deserialize(auxData); this.auxData = map; } boolean hasNBTData = in.readBoolean(); if (hasNBTData) { NBTInputStream is = new NBTInputStream(in, false); CompoundTag tag = (CompoundTag) is.readTag(); nbtData = tag.getValue(); is.close(); } if (material == null) { throw new ClassNotFoundException("No material matching {" + matId + ", " + matData + "} was found!"); } }
diff --git a/app/src/edu/gatech/oftentimes2000/Subscription.java b/app/src/edu/gatech/oftentimes2000/Subscription.java index 13022c0..a04cea9 100644 --- a/app/src/edu/gatech/oftentimes2000/Subscription.java +++ b/app/src/edu/gatech/oftentimes2000/Subscription.java @@ -1,120 +1,120 @@ package edu.gatech.oftentimes2000; import edu.gatech.oftentimes2000.gcm.GCMManager; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.CheckBox; public class Subscription extends Activity implements OnClickListener { private final String TAG = "Subscription"; private CheckBox cbAdvertisement; private CheckBox cbPSA; private CheckBox cbEvent; private ServerPinger pinger; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.subscription); // Init view this.cbAdvertisement = (CheckBox) findViewById(R.id.cbSubscribeAdvertisement); this.cbAdvertisement.setOnClickListener(this); this.cbPSA = (CheckBox) findViewById(R.id.cbSubscribePSA); this.cbPSA.setOnClickListener(this); this.cbEvent = (CheckBox) findViewById(R.id.cbSubscribeEvent); this.cbEvent.setOnClickListener(this); // Load settings Context appContext = this.getApplicationContext(); SharedPreferences settings = appContext.getSharedPreferences(Settings.SETTING_PREFERENCE, Context.MODE_PRIVATE); boolean advertisement = settings.getBoolean("sub_advertisement", false); boolean psa = settings.getBoolean("sub_psa", false); boolean event = settings.getBoolean("sub_event", false); this.cbAdvertisement.setChecked(advertisement); this.cbPSA.setChecked(psa); this.cbEvent.setChecked(event); } @Override public void onClick(View view) { Context appContext = this.getApplicationContext(); SharedPreferences settings = appContext.getSharedPreferences(Settings.SETTING_PREFERENCE, Context.MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); String subscription = ""; boolean delete = false; switch (view.getId()) { case R.id.cbSubscribeAdvertisement: editor.putBoolean("sub_advertisement", this.cbAdvertisement.isChecked()); subscription = "advertisement"; if (!this.cbAdvertisement.isChecked()) delete = true; break; case R.id.cbSubscribePSA: editor.putBoolean("sub_psa", this.cbPSA.isChecked()); subscription = "psa"; - if (!this.cbAdvertisement.isChecked()) + if (!this.cbPSA.isChecked()) delete = true; break; case R.id.cbSubscribeEvent: editor.putBoolean("sub_event", this.cbEvent.isChecked()); subscription = "event"; - if (!this.cbAdvertisement.isChecked()) + if (!this.cbEvent.isChecked()) delete = true; break; } editor.commit(); // Notify the server try { if (this.pinger == null || this.pinger.getStatus() == AsyncTask.Status.FINISHED) { this.pinger = this.new ServerPinger(); String q = "add"; if (delete) q = "delete"; this.pinger.execute(new String[]{q, subscription}); } else { Log.d(TAG, "An existing server pinger is running!"); } } catch (Exception e) { Log.e(TAG, e.getMessage()); } } public class ServerPinger extends AsyncTask<String, Void, Void> { @Override protected Void doInBackground(String... params) { String q = params[0]; if (q.equals("add")) GCMManager.updateSubscription(Subscription.this, params[1]); else if (q.equals("delete")) GCMManager.deleteSubscription(Subscription.this, params[1]); return null; } } }
false
true
public void onClick(View view) { Context appContext = this.getApplicationContext(); SharedPreferences settings = appContext.getSharedPreferences(Settings.SETTING_PREFERENCE, Context.MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); String subscription = ""; boolean delete = false; switch (view.getId()) { case R.id.cbSubscribeAdvertisement: editor.putBoolean("sub_advertisement", this.cbAdvertisement.isChecked()); subscription = "advertisement"; if (!this.cbAdvertisement.isChecked()) delete = true; break; case R.id.cbSubscribePSA: editor.putBoolean("sub_psa", this.cbPSA.isChecked()); subscription = "psa"; if (!this.cbAdvertisement.isChecked()) delete = true; break; case R.id.cbSubscribeEvent: editor.putBoolean("sub_event", this.cbEvent.isChecked()); subscription = "event"; if (!this.cbAdvertisement.isChecked()) delete = true; break; } editor.commit(); // Notify the server try { if (this.pinger == null || this.pinger.getStatus() == AsyncTask.Status.FINISHED) { this.pinger = this.new ServerPinger(); String q = "add"; if (delete) q = "delete"; this.pinger.execute(new String[]{q, subscription}); } else { Log.d(TAG, "An existing server pinger is running!"); } } catch (Exception e) { Log.e(TAG, e.getMessage()); } }
public void onClick(View view) { Context appContext = this.getApplicationContext(); SharedPreferences settings = appContext.getSharedPreferences(Settings.SETTING_PREFERENCE, Context.MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); String subscription = ""; boolean delete = false; switch (view.getId()) { case R.id.cbSubscribeAdvertisement: editor.putBoolean("sub_advertisement", this.cbAdvertisement.isChecked()); subscription = "advertisement"; if (!this.cbAdvertisement.isChecked()) delete = true; break; case R.id.cbSubscribePSA: editor.putBoolean("sub_psa", this.cbPSA.isChecked()); subscription = "psa"; if (!this.cbPSA.isChecked()) delete = true; break; case R.id.cbSubscribeEvent: editor.putBoolean("sub_event", this.cbEvent.isChecked()); subscription = "event"; if (!this.cbEvent.isChecked()) delete = true; break; } editor.commit(); // Notify the server try { if (this.pinger == null || this.pinger.getStatus() == AsyncTask.Status.FINISHED) { this.pinger = this.new ServerPinger(); String q = "add"; if (delete) q = "delete"; this.pinger.execute(new String[]{q, subscription}); } else { Log.d(TAG, "An existing server pinger is running!"); } } catch (Exception e) { Log.e(TAG, e.getMessage()); } }
diff --git a/src/org/mozilla/javascript/Parser.java b/src/org/mozilla/javascript/Parser.java index 493fb09d..3aa68efd 100644 --- a/src/org/mozilla/javascript/Parser.java +++ b/src/org/mozilla/javascript/Parser.java @@ -1,2020 +1,2020 @@ /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Mike Ang * Igor Bukanov * Yuh-Ruey Chen * Ethan Hugg * Terry Lucas * Mike McCabe * Milen Nankov * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript; import java.io.Reader; import java.io.IOException; import java.util.Hashtable; /** * This class implements the JavaScript parser. * * It is based on the C source files jsparse.c and jsparse.h * in the jsref package. * * @see TokenStream * * @author Mike McCabe * @author Brendan Eich */ public class Parser { // TokenInformation flags : currentFlaggedToken stores them together // with token type final static int CLEAR_TI_MASK = 0xFFFF, // mask to clear token information bits TI_AFTER_EOL = 1 << 16, // first token of the source line TI_CHECK_LABEL = 1 << 17; // indicates to check for label CompilerEnvirons compilerEnv; private ErrorReporter errorReporter; private String sourceURI; boolean calledByCompileFunction; private TokenStream ts; private int currentFlaggedToken; private int syntaxErrorCount; private IRFactory nf; private int nestingOfFunction; private Decompiler decompiler; private String encodedSource; // The following are per function variables and should be saved/restored // during function parsing. // XXX Move to separated class? ScriptOrFnNode currentScriptOrFn; private int nestingOfWith; private Hashtable labelSet; // map of label names into nodes private ObjArray loopSet; private ObjArray loopAndSwitchSet; // end of per function variables // Exception to unwind private static class ParserException extends RuntimeException { static final long serialVersionUID = 5882582646773765630L; } public Parser(CompilerEnvirons compilerEnv, ErrorReporter errorReporter) { this.compilerEnv = compilerEnv; this.errorReporter = errorReporter; } protected Decompiler createDecompiler(CompilerEnvirons compilerEnv) { return new Decompiler(); } void addWarning(String messageId, String messageArg) { String message = ScriptRuntime.getMessage1(messageId, messageArg); errorReporter.warning(message, sourceURI, ts.getLineno(), ts.getLine(), ts.getOffset()); } void addError(String messageId) { ++syntaxErrorCount; String message = ScriptRuntime.getMessage0(messageId); errorReporter.error(message, sourceURI, ts.getLineno(), ts.getLine(), ts.getOffset()); } RuntimeException reportError(String messageId) { addError(messageId); // Throw a ParserException exception to unwind the recursive descent // parse. throw new ParserException(); } private int peekToken() throws IOException { int tt = currentFlaggedToken; if (tt == Token.EOF) { tt = ts.getToken(); if (tt == Token.EOL) { do { tt = ts.getToken(); } while (tt == Token.EOL); tt |= TI_AFTER_EOL; } currentFlaggedToken = tt; } return tt & CLEAR_TI_MASK; } private int peekFlaggedToken() throws IOException { peekToken(); return currentFlaggedToken; } private void consumeToken() { currentFlaggedToken = Token.EOF; } private int nextToken() throws IOException { int tt = peekToken(); consumeToken(); return tt; } private int nextFlaggedToken() throws IOException { peekToken(); int ttFlagged = currentFlaggedToken; consumeToken(); return ttFlagged; } private boolean matchToken(int toMatch) throws IOException { int tt = peekToken(); if (tt != toMatch) { return false; } consumeToken(); return true; } private int peekTokenOrEOL() throws IOException { int tt = peekToken(); // Check for last peeked token flags if ((currentFlaggedToken & TI_AFTER_EOL) != 0) { tt = Token.EOL; } return tt; } private void setCheckForLabel() { if ((currentFlaggedToken & CLEAR_TI_MASK) != Token.NAME) throw Kit.codeBug(); currentFlaggedToken |= TI_CHECK_LABEL; } private void mustMatchToken(int toMatch, String messageId) throws IOException, ParserException { if (!matchToken(toMatch)) { reportError(messageId); } } private void mustHaveXML() { if (!compilerEnv.isXmlAvailable()) { reportError("msg.XML.not.available"); } } public String getEncodedSource() { return encodedSource; } public boolean eof() { return ts.eof(); } boolean insideFunction() { return nestingOfFunction != 0; } private Node enterLoop(Node loopLabel) { Node loop = nf.createLoopNode(loopLabel, ts.getLineno()); if (loopSet == null) { loopSet = new ObjArray(); if (loopAndSwitchSet == null) { loopAndSwitchSet = new ObjArray(); } } loopSet.push(loop); loopAndSwitchSet.push(loop); return loop; } private void exitLoop() { loopSet.pop(); loopAndSwitchSet.pop(); } private Node enterSwitch(Node switchSelector, int lineno) { Node switchNode = nf.createSwitch(switchSelector, lineno); if (loopAndSwitchSet == null) { loopAndSwitchSet = new ObjArray(); } loopAndSwitchSet.push(switchNode); return switchNode; } private void exitSwitch() { loopAndSwitchSet.pop(); } /* * Build a parse tree from the given sourceString. * * @return an Object representing the parsed * program. If the parse fails, null will be returned. (The * parse failure will result in a call to the ErrorReporter from * CompilerEnvirons.) */ public ScriptOrFnNode parse(String sourceString, String sourceURI, int lineno) { this.sourceURI = sourceURI; this.ts = new TokenStream(this, null, sourceString, lineno); try { return parse(); } catch (IOException ex) { // Should never happen throw new IllegalStateException(); } } /* * Build a parse tree from the given sourceString. * * @return an Object representing the parsed * program. If the parse fails, null will be returned. (The * parse failure will result in a call to the ErrorReporter from * CompilerEnvirons.) */ public ScriptOrFnNode parse(Reader sourceReader, String sourceURI, int lineno) throws IOException { this.sourceURI = sourceURI; this.ts = new TokenStream(this, sourceReader, null, lineno); return parse(); } private ScriptOrFnNode parse() throws IOException { this.decompiler = createDecompiler(compilerEnv); this.nf = new IRFactory(this); currentScriptOrFn = nf.createScript(); int sourceStartOffset = decompiler.getCurrentOffset(); this.encodedSource = null; decompiler.addToken(Token.SCRIPT); this.currentFlaggedToken = Token.EOF; this.syntaxErrorCount = 0; int baseLineno = ts.getLineno(); // line number where source starts /* so we have something to add nodes to until * we've collected all the source */ Node pn = nf.createLeaf(Token.BLOCK); try { for (;;) { int tt = peekToken(); if (tt <= Token.EOF) { break; } Node n; if (tt == Token.FUNCTION) { consumeToken(); try { n = function(calledByCompileFunction ? FunctionNode.FUNCTION_EXPRESSION : FunctionNode.FUNCTION_STATEMENT); } catch (ParserException e) { break; } } else { n = statement(); } nf.addChildToBack(pn, n); } } catch (StackOverflowError ex) { String msg = ScriptRuntime.getMessage0( "msg.too.deep.parser.recursion"); throw Context.reportRuntimeError(msg, sourceURI, ts.getLineno(), null, 0); } if (this.syntaxErrorCount != 0) { String msg = String.valueOf(this.syntaxErrorCount); msg = ScriptRuntime.getMessage1("msg.got.syntax.errors", msg); throw errorReporter.runtimeError(msg, sourceURI, baseLineno, null, 0); } currentScriptOrFn.setSourceName(sourceURI); currentScriptOrFn.setBaseLineno(baseLineno); currentScriptOrFn.setEndLineno(ts.getLineno()); int sourceEndOffset = decompiler.getCurrentOffset(); currentScriptOrFn.setEncodedSourceBounds(sourceStartOffset, sourceEndOffset); nf.initScript(currentScriptOrFn, pn); if (compilerEnv.isGeneratingSource()) { encodedSource = decompiler.getEncodedSource(); } this.decompiler = null; // It helps GC return currentScriptOrFn; } /* * The C version of this function takes an argument list, * which doesn't seem to be needed for tree generation... * it'd only be useful for checking argument hiding, which * I'm not doing anyway... */ private Node parseFunctionBody() throws IOException { ++nestingOfFunction; Node pn = nf.createBlock(ts.getLineno()); try { bodyLoop: for (;;) { Node n; int tt = peekToken(); switch (tt) { case Token.ERROR: case Token.EOF: case Token.RC: break bodyLoop; case Token.FUNCTION: consumeToken(); n = function(FunctionNode.FUNCTION_STATEMENT); break; default: n = statement(); break; } nf.addChildToBack(pn, n); } } catch (ParserException e) { // Ignore it } finally { --nestingOfFunction; } return pn; } private Node function(int functionType) throws IOException, ParserException { int syntheticType = functionType; int baseLineno = ts.getLineno(); // line number where source starts int functionSourceStart = decompiler.markFunctionStart(functionType); String name; Node memberExprNode = null; if (matchToken(Token.NAME)) { name = ts.getString(); decompiler.addName(name); if (!matchToken(Token.LP)) { if (compilerEnv.isAllowMemberExprAsFunctionName()) { // Extension to ECMA: if 'function <name>' does not follow // by '(', assume <name> starts memberExpr Node memberExprHead = nf.createName(name); name = ""; memberExprNode = memberExprTail(false, memberExprHead); } mustMatchToken(Token.LP, "msg.no.paren.parms"); } } else if (matchToken(Token.LP)) { // Anonymous function name = ""; } else { name = ""; if (compilerEnv.isAllowMemberExprAsFunctionName()) { // Note that memberExpr can not start with '(' like // in function (1+2).toString(), because 'function (' already // processed as anonymous function memberExprNode = memberExpr(false); } mustMatchToken(Token.LP, "msg.no.paren.parms"); } if (memberExprNode != null) { syntheticType = FunctionNode.FUNCTION_EXPRESSION; } boolean nested = insideFunction(); FunctionNode fnNode = nf.createFunction(name); if (nested || nestingOfWith > 0) { // 1. Nested functions are not affected by the dynamic scope flag // as dynamic scope is already a parent of their scope. // 2. Functions defined under the with statement also immune to // this setup, in which case dynamic scope is ignored in favor // of with object. fnNode.itsIgnoreDynamicScope = true; } int functionIndex = currentScriptOrFn.addFunction(fnNode); int functionSourceEnd; ScriptOrFnNode savedScriptOrFn = currentScriptOrFn; currentScriptOrFn = fnNode; int savedNestingOfWith = nestingOfWith; nestingOfWith = 0; Hashtable savedLabelSet = labelSet; labelSet = null; ObjArray savedLoopSet = loopSet; loopSet = null; ObjArray savedLoopAndSwitchSet = loopAndSwitchSet; loopAndSwitchSet = null; Node body; try { decompiler.addToken(Token.LP); if (!matchToken(Token.RP)) { boolean first = true; do { if (!first) decompiler.addToken(Token.COMMA); first = false; mustMatchToken(Token.NAME, "msg.no.parm"); String s = ts.getString(); if (fnNode.hasParamOrVar(s)) { addWarning("msg.dup.parms", s); } fnNode.addParam(s); decompiler.addName(s); } while (matchToken(Token.COMMA)); mustMatchToken(Token.RP, "msg.no.paren.after.parms"); } decompiler.addToken(Token.RP); mustMatchToken(Token.LC, "msg.no.brace.body"); decompiler.addEOL(Token.LC); body = parseFunctionBody(); mustMatchToken(Token.RC, "msg.no.brace.after.body"); decompiler.addToken(Token.RC); functionSourceEnd = decompiler.markFunctionEnd(functionSourceStart); if (functionType != FunctionNode.FUNCTION_EXPRESSION) { if (compilerEnv.getLanguageVersion() >= Context.VERSION_1_2) { // function f() {} function g() {} is not allowed in 1.2 // or later but for compatibility with old scripts // the check is done only if language is // explicitly set. // XXX warning needed if version == VERSION_DEFAULT ? int tt = peekTokenOrEOL(); if (tt == Token.FUNCTION) { reportError("msg.no.semi.stmt"); } } // Add EOL only if function is not part of expression // since it gets SEMI + EOL from Statement in that case decompiler.addToken(Token.EOL); } } finally { loopAndSwitchSet = savedLoopAndSwitchSet; loopSet = savedLoopSet; labelSet = savedLabelSet; nestingOfWith = savedNestingOfWith; currentScriptOrFn = savedScriptOrFn; } fnNode.setEncodedSourceBounds(functionSourceStart, functionSourceEnd); fnNode.setSourceName(sourceURI); fnNode.setBaseLineno(baseLineno); fnNode.setEndLineno(ts.getLineno()); Node pn = nf.initFunction(fnNode, functionIndex, body, syntheticType); if (memberExprNode != null) { pn = nf.createAssignment(Token.ASSIGN, memberExprNode, pn); if (functionType != FunctionNode.FUNCTION_EXPRESSION) { // XXX check JScript behavior: should it be createExprStatement? pn = nf.createExprStatementNoReturn(pn, baseLineno); } } return pn; } private Node statements() throws IOException { Node pn = nf.createBlock(ts.getLineno()); int tt; while((tt = peekToken()) > Token.EOF && tt != Token.RC) { nf.addChildToBack(pn, statement()); } return pn; } private Node condition() throws IOException, ParserException { Node pn; mustMatchToken(Token.LP, "msg.no.paren.cond"); decompiler.addToken(Token.LP); pn = expr(false); mustMatchToken(Token.RP, "msg.no.paren.after.cond"); decompiler.addToken(Token.RP); // there's a check here in jsparse.c that corrects = to == return pn; } // match a NAME; return null if no match. private Node matchJumpLabelName() throws IOException, ParserException { Node label = null; int tt = peekTokenOrEOL(); if (tt == Token.NAME) { consumeToken(); String name = ts.getString(); decompiler.addName(name); if (labelSet != null) { label = (Node)labelSet.get(name); } if (label == null) { reportError("msg.undef.label"); } } return label; } private Node statement() throws IOException { try { Node pn = statementHelper(null); if (pn != null) { return pn; } } catch (ParserException e) { } // skip to end of statement int lineno = ts.getLineno(); guessingStatementEnd: for (;;) { int tt = peekTokenOrEOL(); consumeToken(); switch (tt) { case Token.ERROR: case Token.EOF: case Token.EOL: case Token.SEMI: break guessingStatementEnd; } } return nf.createExprStatement(nf.createName("error"), lineno); } /** * Whether the "catch (e: e instanceof Exception) { ... }" syntax * is implemented. */ private Node statementHelper(Node statementLabel) throws IOException, ParserException { Node pn = null; int tt; tt = peekToken(); switch(tt) { case Token.IF: { consumeToken(); decompiler.addToken(Token.IF); int lineno = ts.getLineno(); Node cond = condition(); decompiler.addEOL(Token.LC); Node ifTrue = statement(); Node ifFalse = null; if (matchToken(Token.ELSE)) { decompiler.addToken(Token.RC); decompiler.addToken(Token.ELSE); decompiler.addEOL(Token.LC); ifFalse = statement(); } decompiler.addEOL(Token.RC); pn = nf.createIf(cond, ifTrue, ifFalse, lineno); return pn; } case Token.SWITCH: { consumeToken(); decompiler.addToken(Token.SWITCH); int lineno = ts.getLineno(); mustMatchToken(Token.LP, "msg.no.paren.switch"); decompiler.addToken(Token.LP); pn = enterSwitch(expr(false), lineno); try { mustMatchToken(Token.RP, "msg.no.paren.after.switch"); decompiler.addToken(Token.RP); mustMatchToken(Token.LC, "msg.no.brace.switch"); decompiler.addEOL(Token.LC); boolean hasDefault = false; switchLoop: for (;;) { tt = nextToken(); Node caseExpression; switch (tt) { case Token.RC: break switchLoop; case Token.CASE: decompiler.addToken(Token.CASE); caseExpression = expr(false); mustMatchToken(Token.COLON, "msg.no.colon.case"); decompiler.addEOL(Token.COLON); break; case Token.DEFAULT: if (hasDefault) { reportError("msg.double.switch.default"); } decompiler.addToken(Token.DEFAULT); hasDefault = true; caseExpression = null; mustMatchToken(Token.COLON, "msg.no.colon.case"); decompiler.addEOL(Token.COLON); break; default: reportError("msg.bad.switch"); break switchLoop; } Node block = nf.createLeaf(Token.BLOCK); while ((tt = peekToken()) != Token.RC && tt != Token.CASE && tt != Token.DEFAULT && tt != Token.EOF) { nf.addChildToBack(block, statement()); } // caseExpression == null => add default lable nf.addSwitchCase(pn, caseExpression, block); } decompiler.addEOL(Token.RC); nf.closeSwitch(pn); } finally { exitSwitch(); } return pn; } case Token.WHILE: { consumeToken(); decompiler.addToken(Token.WHILE); Node loop = enterLoop(statementLabel); try { Node cond = condition(); decompiler.addEOL(Token.LC); Node body = statement(); decompiler.addEOL(Token.RC); pn = nf.createWhile(loop, cond, body); } finally { exitLoop(); } return pn; } case Token.DO: { consumeToken(); decompiler.addToken(Token.DO); decompiler.addEOL(Token.LC); Node loop = enterLoop(statementLabel); try { Node body = statement(); decompiler.addToken(Token.RC); mustMatchToken(Token.WHILE, "msg.no.while.do"); decompiler.addToken(Token.WHILE); Node cond = condition(); pn = nf.createDoWhile(loop, body, cond); } finally { exitLoop(); } // Always auto-insert semicon to follow SpiderMonkey: // It is required by EMAScript but is ignored by the rest of // world, see bug 238945 matchToken(Token.SEMI); decompiler.addEOL(Token.SEMI); return pn; } case Token.FOR: { consumeToken(); boolean isForEach = false; decompiler.addToken(Token.FOR); Node loop = enterLoop(statementLabel); try { Node init; // Node init is also foo in 'foo in Object' Node cond; // Node cond is also object in 'foo in Object' Node incr = null; // to kill warning Node body; // See if this is a for each () instead of just a for () if (matchToken(Token.NAME)) { decompiler.addName(ts.getString()); if (ts.getString().equals("each")) { isForEach = true; } else { reportError("msg.no.paren.for"); } } mustMatchToken(Token.LP, "msg.no.paren.for"); decompiler.addToken(Token.LP); tt = peekToken(); if (tt == Token.SEMI) { init = nf.createLeaf(Token.EMPTY); } else { if (tt == Token.VAR) { // set init to a var list or initial consumeToken(); // consume the 'var' token init = variables(true); } else { init = expr(true); } } if (matchToken(Token.IN)) { decompiler.addToken(Token.IN); // 'cond' is the object over which we're iterating cond = expr(false); } else { // ordinary for loop mustMatchToken(Token.SEMI, "msg.no.semi.for"); decompiler.addToken(Token.SEMI); if (peekToken() == Token.SEMI) { // no loop condition cond = nf.createLeaf(Token.EMPTY); } else { cond = expr(false); } mustMatchToken(Token.SEMI, "msg.no.semi.for.cond"); decompiler.addToken(Token.SEMI); if (peekToken() == Token.RP) { incr = nf.createLeaf(Token.EMPTY); } else { incr = expr(false); } } mustMatchToken(Token.RP, "msg.no.paren.for.ctrl"); decompiler.addToken(Token.RP); decompiler.addEOL(Token.LC); body = statement(); decompiler.addEOL(Token.RC); if (incr == null) { // cond could be null if 'in obj' got eaten // by the init node. pn = nf.createForIn(loop, init, cond, body, isForEach); } else { pn = nf.createFor(loop, init, cond, incr, body); } } finally { exitLoop(); } return pn; } case Token.TRY: { consumeToken(); int lineno = ts.getLineno(); Node tryblock; Node catchblocks = null; Node finallyblock = null; decompiler.addToken(Token.TRY); decompiler.addEOL(Token.LC); tryblock = statement(); decompiler.addEOL(Token.RC); catchblocks = nf.createLeaf(Token.BLOCK); boolean sawDefaultCatch = false; int peek = peekToken(); if (peek == Token.CATCH) { while (matchToken(Token.CATCH)) { if (sawDefaultCatch) { reportError("msg.catch.unreachable"); } decompiler.addToken(Token.CATCH); mustMatchToken(Token.LP, "msg.no.paren.catch"); decompiler.addToken(Token.LP); mustMatchToken(Token.NAME, "msg.bad.catchcond"); String varName = ts.getString(); decompiler.addName(varName); Node catchCond = null; if (matchToken(Token.IF)) { decompiler.addToken(Token.IF); catchCond = expr(false); } else { sawDefaultCatch = true; } mustMatchToken(Token.RP, "msg.bad.catchcond"); decompiler.addToken(Token.RP); mustMatchToken(Token.LC, "msg.no.brace.catchblock"); decompiler.addEOL(Token.LC); nf.addChildToBack(catchblocks, nf.createCatch(varName, catchCond, statements(), ts.getLineno())); mustMatchToken(Token.RC, "msg.no.brace.after.body"); decompiler.addEOL(Token.RC); } } else if (peek != Token.FINALLY) { mustMatchToken(Token.FINALLY, "msg.try.no.catchfinally"); } if (matchToken(Token.FINALLY)) { decompiler.addToken(Token.FINALLY); decompiler.addEOL(Token.LC); finallyblock = statement(); decompiler.addEOL(Token.RC); } pn = nf.createTryCatchFinally(tryblock, catchblocks, finallyblock, lineno); return pn; } case Token.THROW: { consumeToken(); if (peekTokenOrEOL() == Token.EOL) { // ECMAScript does not allow new lines before throw expression, // see bug 256617 reportError("msg.bad.throw.eol"); } int lineno = ts.getLineno(); decompiler.addToken(Token.THROW); pn = nf.createThrow(expr(false), lineno); break; } case Token.BREAK: { consumeToken(); int lineno = ts.getLineno(); decompiler.addToken(Token.BREAK); // matchJumpLabelName only matches if there is one Node breakStatement = matchJumpLabelName(); if (breakStatement == null) { if (loopAndSwitchSet == null || loopAndSwitchSet.size() == 0) { reportError("msg.bad.break"); return null; } breakStatement = (Node)loopAndSwitchSet.peek(); } pn = nf.createBreak(breakStatement, lineno); break; } case Token.CONTINUE: { consumeToken(); int lineno = ts.getLineno(); decompiler.addToken(Token.CONTINUE); Node loop; // matchJumpLabelName only matches if there is one Node label = matchJumpLabelName(); if (label == null) { if (loopSet == null || loopSet.size() == 0) { reportError("msg.continue.outside"); return null; } loop = (Node)loopSet.peek(); } else { loop = nf.getLabelLoop(label); if (loop == null) { reportError("msg.continue.nonloop"); return null; } } pn = nf.createContinue(loop, lineno); break; } case Token.WITH: { consumeToken(); decompiler.addToken(Token.WITH); int lineno = ts.getLineno(); mustMatchToken(Token.LP, "msg.no.paren.with"); decompiler.addToken(Token.LP); Node obj = expr(false); mustMatchToken(Token.RP, "msg.no.paren.after.with"); decompiler.addToken(Token.RP); decompiler.addEOL(Token.LC); ++nestingOfWith; Node body; try { body = statement(); } finally { --nestingOfWith; } decompiler.addEOL(Token.RC); pn = nf.createWith(obj, body, lineno); return pn; } case Token.VAR: { consumeToken(); pn = variables(false); break; } case Token.RETURN: { if (!insideFunction()) { reportError("msg.bad.return"); } consumeToken(); decompiler.addToken(Token.RETURN); int lineno = ts.getLineno(); Node retExpr; /* This is ugly, but we don't want to require a semicolon. */ tt = peekTokenOrEOL(); switch (tt) { case Token.SEMI: case Token.RC: case Token.EOF: case Token.EOL: case Token.ERROR: retExpr = null; break; default: retExpr = expr(false); } pn = nf.createReturn(retExpr, lineno); break; } case Token.LC: consumeToken(); if (statementLabel != null) { decompiler.addToken(Token.LC); } pn = statements(); mustMatchToken(Token.RC, "msg.no.brace.block"); if (statementLabel != null) { decompiler.addEOL(Token.RC); } return pn; case Token.ERROR: // Fall thru, to have a node for error recovery to work on case Token.SEMI: consumeToken(); pn = nf.createLeaf(Token.EMPTY); return pn; case Token.FUNCTION: { consumeToken(); pn = function(FunctionNode.FUNCTION_EXPRESSION_STATEMENT); return pn; } case Token.DEFAULT : consumeToken(); mustHaveXML(); decompiler.addToken(Token.DEFAULT); int nsLine = ts.getLineno(); if (!(matchToken(Token.NAME) && ts.getString().equals("xml"))) { reportError("msg.bad.namespace"); } - decompiler.addName(ts.getString()); + decompiler.addName(" xml"); if (!(matchToken(Token.NAME) && ts.getString().equals("namespace"))) { reportError("msg.bad.namespace"); } - decompiler.addName(ts.getString()); + decompiler.addName(" namespace"); if (!matchToken(Token.ASSIGN)) { reportError("msg.bad.namespace"); } decompiler.addToken(Token.ASSIGN); Node expr = expr(false); pn = nf.createDefaultNamespace(expr, nsLine); break; case Token.NAME: { int lineno = ts.getLineno(); String name = ts.getString(); setCheckForLabel(); pn = expr(false); if (pn.getType() != Token.LABEL) { pn = nf.createExprStatement(pn, lineno); } else { // Parsed the label: push back token should be // colon that primaryExpr left untouched. if (peekToken() != Token.COLON) Kit.codeBug(); consumeToken(); // depend on decompiling lookahead to guess that that // last name was a label. decompiler.addName(name); decompiler.addEOL(Token.COLON); if (labelSet == null) { labelSet = new Hashtable(); } else if (labelSet.containsKey(name)) { reportError("msg.dup.label"); } boolean firstLabel; if (statementLabel == null) { firstLabel = true; statementLabel = pn; } else { // Discard multiple label nodes and use only // the first: it allows to simplify IRFactory firstLabel = false; } labelSet.put(name, statementLabel); try { pn = statementHelper(statementLabel); } finally { labelSet.remove(name); } if (firstLabel) { pn = nf.createLabeledStatement(statementLabel, pn); } return pn; } break; } default: { int lineno = ts.getLineno(); pn = expr(false); pn = nf.createExprStatement(pn, lineno); break; } } int ttFlagged = peekFlaggedToken(); switch (ttFlagged & CLEAR_TI_MASK) { case Token.SEMI: // Consume ';' as a part of expression consumeToken(); break; case Token.ERROR: case Token.EOF: case Token.RC: // Autoinsert ; break; default: if ((ttFlagged & TI_AFTER_EOL) == 0) { // Report error if no EOL or autoinsert ; otherwise reportError("msg.no.semi.stmt"); } break; } decompiler.addEOL(Token.SEMI); return pn; } private Node variables(boolean inForInit) throws IOException, ParserException { Node pn = nf.createVariables(ts.getLineno()); boolean first = true; decompiler.addToken(Token.VAR); for (;;) { Node name; Node init; mustMatchToken(Token.NAME, "msg.bad.var"); String s = ts.getString(); if (!first) decompiler.addToken(Token.COMMA); first = false; decompiler.addName(s); currentScriptOrFn.addVar(s); name = nf.createName(s); // omitted check for argument hiding if (matchToken(Token.ASSIGN)) { decompiler.addToken(Token.ASSIGN); init = assignExpr(inForInit); nf.addChildToBack(name, init); } nf.addChildToBack(pn, name); if (!matchToken(Token.COMMA)) break; } return pn; } private Node expr(boolean inForInit) throws IOException, ParserException { Node pn = assignExpr(inForInit); while (matchToken(Token.COMMA)) { decompiler.addToken(Token.COMMA); pn = nf.createBinary(Token.COMMA, pn, assignExpr(inForInit)); } return pn; } private Node assignExpr(boolean inForInit) throws IOException, ParserException { Node pn = condExpr(inForInit); int tt = peekToken(); if (Token.FIRST_ASSIGN <= tt && tt <= Token.LAST_ASSIGN) { consumeToken(); decompiler.addToken(tt); pn = nf.createAssignment(tt, pn, assignExpr(inForInit)); } return pn; } private Node condExpr(boolean inForInit) throws IOException, ParserException { Node ifTrue; Node ifFalse; Node pn = orExpr(inForInit); if (matchToken(Token.HOOK)) { decompiler.addToken(Token.HOOK); ifTrue = assignExpr(false); mustMatchToken(Token.COLON, "msg.no.colon.cond"); decompiler.addToken(Token.COLON); ifFalse = assignExpr(inForInit); return nf.createCondExpr(pn, ifTrue, ifFalse); } return pn; } private Node orExpr(boolean inForInit) throws IOException, ParserException { Node pn = andExpr(inForInit); if (matchToken(Token.OR)) { decompiler.addToken(Token.OR); pn = nf.createBinary(Token.OR, pn, orExpr(inForInit)); } return pn; } private Node andExpr(boolean inForInit) throws IOException, ParserException { Node pn = bitOrExpr(inForInit); if (matchToken(Token.AND)) { decompiler.addToken(Token.AND); pn = nf.createBinary(Token.AND, pn, andExpr(inForInit)); } return pn; } private Node bitOrExpr(boolean inForInit) throws IOException, ParserException { Node pn = bitXorExpr(inForInit); while (matchToken(Token.BITOR)) { decompiler.addToken(Token.BITOR); pn = nf.createBinary(Token.BITOR, pn, bitXorExpr(inForInit)); } return pn; } private Node bitXorExpr(boolean inForInit) throws IOException, ParserException { Node pn = bitAndExpr(inForInit); while (matchToken(Token.BITXOR)) { decompiler.addToken(Token.BITXOR); pn = nf.createBinary(Token.BITXOR, pn, bitAndExpr(inForInit)); } return pn; } private Node bitAndExpr(boolean inForInit) throws IOException, ParserException { Node pn = eqExpr(inForInit); while (matchToken(Token.BITAND)) { decompiler.addToken(Token.BITAND); pn = nf.createBinary(Token.BITAND, pn, eqExpr(inForInit)); } return pn; } private Node eqExpr(boolean inForInit) throws IOException, ParserException { Node pn = relExpr(inForInit); for (;;) { int tt = peekToken(); switch (tt) { case Token.EQ: case Token.NE: case Token.SHEQ: case Token.SHNE: consumeToken(); int decompilerToken = tt; int parseToken = tt; if (compilerEnv.getLanguageVersion() == Context.VERSION_1_2) { // JavaScript 1.2 uses shallow equality for == and != . // In addition, convert === and !== for decompiler into // == and != since the decompiler is supposed to show // canonical source and in 1.2 ===, !== are allowed // only as an alias to ==, !=. switch (tt) { case Token.EQ: parseToken = Token.SHEQ; break; case Token.NE: parseToken = Token.SHNE; break; case Token.SHEQ: decompilerToken = Token.EQ; break; case Token.SHNE: decompilerToken = Token.NE; break; } } decompiler.addToken(decompilerToken); pn = nf.createBinary(parseToken, pn, relExpr(inForInit)); continue; } break; } return pn; } private Node relExpr(boolean inForInit) throws IOException, ParserException { Node pn = shiftExpr(); for (;;) { int tt = peekToken(); switch (tt) { case Token.IN: if (inForInit) break; // fall through case Token.INSTANCEOF: case Token.LE: case Token.LT: case Token.GE: case Token.GT: consumeToken(); decompiler.addToken(tt); pn = nf.createBinary(tt, pn, shiftExpr()); continue; } break; } return pn; } private Node shiftExpr() throws IOException, ParserException { Node pn = addExpr(); for (;;) { int tt = peekToken(); switch (tt) { case Token.LSH: case Token.URSH: case Token.RSH: consumeToken(); decompiler.addToken(tt); pn = nf.createBinary(tt, pn, addExpr()); continue; } break; } return pn; } private Node addExpr() throws IOException, ParserException { Node pn = mulExpr(); for (;;) { int tt = peekToken(); if (tt == Token.ADD || tt == Token.SUB) { consumeToken(); decompiler.addToken(tt); // flushNewLines pn = nf.createBinary(tt, pn, mulExpr()); continue; } break; } return pn; } private Node mulExpr() throws IOException, ParserException { Node pn = unaryExpr(); for (;;) { int tt = peekToken(); switch (tt) { case Token.MUL: case Token.DIV: case Token.MOD: consumeToken(); decompiler.addToken(tt); pn = nf.createBinary(tt, pn, unaryExpr()); continue; } break; } return pn; } private Node unaryExpr() throws IOException, ParserException { int tt; tt = peekToken(); switch(tt) { case Token.VOID: case Token.NOT: case Token.BITNOT: case Token.TYPEOF: consumeToken(); decompiler.addToken(tt); return nf.createUnary(tt, unaryExpr()); case Token.ADD: consumeToken(); // Convert to special POS token in decompiler and parse tree decompiler.addToken(Token.POS); return nf.createUnary(Token.POS, unaryExpr()); case Token.SUB: consumeToken(); // Convert to special NEG token in decompiler and parse tree decompiler.addToken(Token.NEG); return nf.createUnary(Token.NEG, unaryExpr()); case Token.INC: case Token.DEC: consumeToken(); decompiler.addToken(tt); return nf.createIncDec(tt, false, memberExpr(true)); case Token.DELPROP: consumeToken(); decompiler.addToken(Token.DELPROP); return nf.createUnary(Token.DELPROP, unaryExpr()); case Token.ERROR: consumeToken(); break; // XML stream encountered in expression. case Token.LT: if (compilerEnv.isXmlAvailable()) { consumeToken(); Node pn = xmlInitializer(); return memberExprTail(true, pn); } // Fall thru to the default handling of RELOP default: Node pn = memberExpr(true); // Don't look across a newline boundary for a postfix incop. tt = peekTokenOrEOL(); if (tt == Token.INC || tt == Token.DEC) { consumeToken(); decompiler.addToken(tt); return nf.createIncDec(tt, true, pn); } return pn; } return nf.createName("err"); // Only reached on error. Try to continue. } private Node xmlInitializer() throws IOException { int tt = ts.getFirstXMLToken(); if (tt != Token.XML && tt != Token.XMLEND) { reportError("msg.syntax"); return null; } /* Make a NEW node to append to. */ Node pnXML = nf.createLeaf(Token.NEW); String xml = ts.getString(); boolean fAnonymous = xml.trim().startsWith("<>"); Node pn = nf.createName(fAnonymous ? "XMLList" : "XML"); nf.addChildToBack(pnXML, pn); pn = null; Node expr; for (;;tt = ts.getNextXMLToken()) { switch (tt) { case Token.XML: xml = ts.getString(); decompiler.addName(xml); mustMatchToken(Token.LC, "msg.syntax"); decompiler.addToken(Token.LC); expr = (peekToken() == Token.RC) ? nf.createString("") : expr(false); mustMatchToken(Token.RC, "msg.syntax"); decompiler.addToken(Token.RC); if (pn == null) { pn = nf.createString(xml); } else { pn = nf.createBinary(Token.ADD, pn, nf.createString(xml)); } int nodeType; if (ts.isXMLAttribute()) { nodeType = Token.ESCXMLATTR; } else { nodeType = Token.ESCXMLTEXT; } expr = nf.createUnary(nodeType, expr); pn = nf.createBinary(Token.ADD, pn, expr); break; case Token.XMLEND: xml = ts.getString(); decompiler.addName(xml); if (pn == null) { pn = nf.createString(xml); } else { pn = nf.createBinary(Token.ADD, pn, nf.createString(xml)); } nf.addChildToBack(pnXML, pn); return pnXML; default: reportError("msg.syntax"); return null; } } } private void argumentList(Node listNode) throws IOException, ParserException { boolean matched; matched = matchToken(Token.RP); if (!matched) { boolean first = true; do { if (!first) decompiler.addToken(Token.COMMA); first = false; nf.addChildToBack(listNode, assignExpr(false)); } while (matchToken(Token.COMMA)); mustMatchToken(Token.RP, "msg.no.paren.arg"); } decompiler.addToken(Token.RP); } private Node memberExpr(boolean allowCallSyntax) throws IOException, ParserException { int tt; Node pn; /* Check for new expressions. */ tt = peekToken(); if (tt == Token.NEW) { /* Eat the NEW token. */ consumeToken(); decompiler.addToken(Token.NEW); /* Make a NEW node to append to. */ pn = nf.createCallOrNew(Token.NEW, memberExpr(false)); if (matchToken(Token.LP)) { decompiler.addToken(Token.LP); /* Add the arguments to pn, if any are supplied. */ argumentList(pn); } /* XXX there's a check in the C source against * "too many constructor arguments" - how many * do we claim to support? */ /* Experimental syntax: allow an object literal to follow a new expression, * which will mean a kind of anonymous class built with the JavaAdapter. * the object literal will be passed as an additional argument to the constructor. */ tt = peekToken(); if (tt == Token.LC) { nf.addChildToBack(pn, primaryExpr()); } } else { pn = primaryExpr(); } return memberExprTail(allowCallSyntax, pn); } private Node memberExprTail(boolean allowCallSyntax, Node pn) throws IOException, ParserException { tailLoop: for (;;) { int tt = peekToken(); switch (tt) { case Token.DOT: case Token.DOTDOT: { int memberTypeFlags; String s; consumeToken(); decompiler.addToken(tt); memberTypeFlags = 0; if (tt == Token.DOTDOT) { mustHaveXML(); memberTypeFlags = Node.DESCENDANTS_FLAG; } if (!compilerEnv.isXmlAvailable()) { mustMatchToken(Token.NAME, "msg.no.name.after.dot"); s = ts.getString(); decompiler.addName(s); pn = nf.createPropertyGet(pn, null, s, memberTypeFlags); break; } tt = nextToken(); switch (tt) { // handles: name, ns::name, ns::*, ns::[expr] case Token.NAME: s = ts.getString(); decompiler.addName(s); pn = propertyName(pn, s, memberTypeFlags); break; // handles: *, *::name, *::*, *::[expr] case Token.MUL: decompiler.addName("*"); pn = propertyName(pn, "*", memberTypeFlags); break; // handles: '@attr', '@ns::attr', '@ns::*', '@ns::*', // '@::attr', '@::*', '@*', '@*::attr', '@*::*' case Token.XMLATTR: decompiler.addToken(Token.XMLATTR); pn = attributeAccess(pn, memberTypeFlags); break; default: reportError("msg.no.name.after.dot"); } } break; case Token.DOTQUERY: consumeToken(); mustHaveXML(); decompiler.addToken(Token.DOTQUERY); pn = nf.createDotQuery(pn, expr(false), ts.getLineno()); mustMatchToken(Token.RP, "msg.no.paren"); decompiler.addToken(Token.RP); break; case Token.LB: consumeToken(); decompiler.addToken(Token.LB); pn = nf.createElementGet(pn, null, expr(false), 0); mustMatchToken(Token.RB, "msg.no.bracket.index"); decompiler.addToken(Token.RB); break; case Token.LP: if (!allowCallSyntax) { break tailLoop; } consumeToken(); decompiler.addToken(Token.LP); pn = nf.createCallOrNew(Token.CALL, pn); /* Add the arguments to pn, if any are supplied. */ argumentList(pn); break; default: break tailLoop; } } return pn; } /* * Xml attribute expression: * '@attr', '@ns::attr', '@ns::*', '@ns::*', '@*', '@*::attr', '@*::*' */ private Node attributeAccess(Node pn, int memberTypeFlags) throws IOException { memberTypeFlags |= Node.ATTRIBUTE_FLAG; int tt = nextToken(); switch (tt) { // handles: @name, @ns::name, @ns::*, @ns::[expr] case Token.NAME: { String s = ts.getString(); decompiler.addName(s); pn = propertyName(pn, s, memberTypeFlags); } break; // handles: @*, @*::name, @*::*, @*::[expr] case Token.MUL: decompiler.addName("*"); pn = propertyName(pn, "*", memberTypeFlags); break; // handles @[expr] case Token.LB: decompiler.addToken(Token.LB); pn = nf.createElementGet(pn, null, expr(false), memberTypeFlags); mustMatchToken(Token.RB, "msg.no.bracket.index"); decompiler.addToken(Token.RB); break; default: reportError("msg.no.name.after.xmlAttr"); pn = nf.createPropertyGet(pn, null, "?", memberTypeFlags); break; } return pn; } /** * Check if :: follows name in which case it becomes qualified name */ private Node propertyName(Node pn, String name, int memberTypeFlags) throws IOException, ParserException { String namespace = null; if (matchToken(Token.COLONCOLON)) { decompiler.addToken(Token.COLONCOLON); namespace = name; int tt = nextToken(); switch (tt) { // handles name::name case Token.NAME: name = ts.getString(); decompiler.addName(name); break; // handles name::* case Token.MUL: decompiler.addName("*"); name = "*"; break; // handles name::[expr] case Token.LB: decompiler.addToken(Token.LB); pn = nf.createElementGet(pn, namespace, expr(false), memberTypeFlags); mustMatchToken(Token.RB, "msg.no.bracket.index"); decompiler.addToken(Token.RB); return pn; default: reportError("msg.no.name.after.coloncolon"); name = "?"; } } pn = nf.createPropertyGet(pn, namespace, name, memberTypeFlags); return pn; } private Node primaryExpr() throws IOException, ParserException { Node pn; int ttFlagged = nextFlaggedToken(); int tt = ttFlagged & CLEAR_TI_MASK; switch(tt) { case Token.FUNCTION: return function(FunctionNode.FUNCTION_EXPRESSION); case Token.LB: { ObjArray elems = new ObjArray(); int skipCount = 0; decompiler.addToken(Token.LB); boolean after_lb_or_comma = true; for (;;) { tt = peekToken(); if (tt == Token.COMMA) { consumeToken(); decompiler.addToken(Token.COMMA); if (!after_lb_or_comma) { after_lb_or_comma = true; } else { elems.add(null); ++skipCount; } } else if (tt == Token.RB) { consumeToken(); decompiler.addToken(Token.RB); break; } else { if (!after_lb_or_comma) { reportError("msg.no.bracket.arg"); } elems.add(assignExpr(false)); after_lb_or_comma = false; } } return nf.createArrayLiteral(elems, skipCount); } case Token.LC: { ObjArray elems = new ObjArray(); decompiler.addToken(Token.LC); if (!matchToken(Token.RC)) { boolean first = true; commaloop: do { Object property; if (!first) decompiler.addToken(Token.COMMA); else first = false; tt = peekToken(); switch(tt) { case Token.NAME: case Token.STRING: consumeToken(); // map NAMEs to STRINGs in object literal context // but tell the decompiler the proper type String s = ts.getString(); if (tt == Token.NAME) { decompiler.addName(s); } else { decompiler.addString(s); } property = ScriptRuntime.getIndexObject(s); break; case Token.NUMBER: consumeToken(); double n = ts.getNumber(); decompiler.addNumber(n); property = ScriptRuntime.getIndexObject(n); break; case Token.RC: // trailing comma is OK. break commaloop; default: reportError("msg.bad.prop"); break commaloop; } mustMatchToken(Token.COLON, "msg.no.colon.prop"); // OBJLIT is used as ':' in object literal for // decompilation to solve spacing ambiguity. decompiler.addToken(Token.OBJECTLIT); elems.add(property); elems.add(assignExpr(false)); } while (matchToken(Token.COMMA)); mustMatchToken(Token.RC, "msg.no.brace.prop"); } decompiler.addToken(Token.RC); return nf.createObjectLiteral(elems); } case Token.LP: /* Brendan's IR-jsparse.c makes a new node tagged with * TOK_LP here... I'm not sure I understand why. Isn't * the grouping already implicit in the structure of the * parse tree? also TOK_LP is already overloaded (I * think) in the C IR as 'function call.' */ decompiler.addToken(Token.LP); pn = expr(false); decompiler.addToken(Token.RP); mustMatchToken(Token.RP, "msg.no.paren"); return pn; case Token.XMLATTR: mustHaveXML(); decompiler.addToken(Token.XMLATTR); pn = attributeAccess(null, 0); return pn; case Token.NAME: { String name = ts.getString(); if ((ttFlagged & TI_CHECK_LABEL) != 0) { if (peekToken() == Token.COLON) { // Do not consume colon, it is used as unwind indicator // to return to statementHelper. // XXX Better way? return nf.createLabel(ts.getLineno()); } } decompiler.addName(name); if (compilerEnv.isXmlAvailable()) { pn = propertyName(null, name, 0); } else { pn = nf.createName(name); } return pn; } case Token.NUMBER: { double n = ts.getNumber(); decompiler.addNumber(n); return nf.createNumber(n); } case Token.STRING: { String s = ts.getString(); decompiler.addString(s); return nf.createString(s); } case Token.DIV: case Token.ASSIGN_DIV: { // Got / or /= which should be treated as regexp in fact ts.readRegExp(tt); String flags = ts.regExpFlags; ts.regExpFlags = null; String re = ts.getString(); decompiler.addRegexp(re, flags); int index = currentScriptOrFn.addRegexp(re, flags); return nf.createRegExp(index); } case Token.NULL: case Token.THIS: case Token.FALSE: case Token.TRUE: decompiler.addToken(tt); return nf.createLeaf(tt); case Token.RESERVED: reportError("msg.reserved.id"); break; case Token.ERROR: /* the scanner or one of its subroutines reported the error. */ break; case Token.EOF: reportError("msg.unexpected.eof"); break; default: reportError("msg.syntax"); break; } return null; // should never reach here } }
false
true
private Node statementHelper(Node statementLabel) throws IOException, ParserException { Node pn = null; int tt; tt = peekToken(); switch(tt) { case Token.IF: { consumeToken(); decompiler.addToken(Token.IF); int lineno = ts.getLineno(); Node cond = condition(); decompiler.addEOL(Token.LC); Node ifTrue = statement(); Node ifFalse = null; if (matchToken(Token.ELSE)) { decompiler.addToken(Token.RC); decompiler.addToken(Token.ELSE); decompiler.addEOL(Token.LC); ifFalse = statement(); } decompiler.addEOL(Token.RC); pn = nf.createIf(cond, ifTrue, ifFalse, lineno); return pn; } case Token.SWITCH: { consumeToken(); decompiler.addToken(Token.SWITCH); int lineno = ts.getLineno(); mustMatchToken(Token.LP, "msg.no.paren.switch"); decompiler.addToken(Token.LP); pn = enterSwitch(expr(false), lineno); try { mustMatchToken(Token.RP, "msg.no.paren.after.switch"); decompiler.addToken(Token.RP); mustMatchToken(Token.LC, "msg.no.brace.switch"); decompiler.addEOL(Token.LC); boolean hasDefault = false; switchLoop: for (;;) { tt = nextToken(); Node caseExpression; switch (tt) { case Token.RC: break switchLoop; case Token.CASE: decompiler.addToken(Token.CASE); caseExpression = expr(false); mustMatchToken(Token.COLON, "msg.no.colon.case"); decompiler.addEOL(Token.COLON); break; case Token.DEFAULT: if (hasDefault) { reportError("msg.double.switch.default"); } decompiler.addToken(Token.DEFAULT); hasDefault = true; caseExpression = null; mustMatchToken(Token.COLON, "msg.no.colon.case"); decompiler.addEOL(Token.COLON); break; default: reportError("msg.bad.switch"); break switchLoop; } Node block = nf.createLeaf(Token.BLOCK); while ((tt = peekToken()) != Token.RC && tt != Token.CASE && tt != Token.DEFAULT && tt != Token.EOF) { nf.addChildToBack(block, statement()); } // caseExpression == null => add default lable nf.addSwitchCase(pn, caseExpression, block); } decompiler.addEOL(Token.RC); nf.closeSwitch(pn); } finally { exitSwitch(); } return pn; } case Token.WHILE: { consumeToken(); decompiler.addToken(Token.WHILE); Node loop = enterLoop(statementLabel); try { Node cond = condition(); decompiler.addEOL(Token.LC); Node body = statement(); decompiler.addEOL(Token.RC); pn = nf.createWhile(loop, cond, body); } finally { exitLoop(); } return pn; } case Token.DO: { consumeToken(); decompiler.addToken(Token.DO); decompiler.addEOL(Token.LC); Node loop = enterLoop(statementLabel); try { Node body = statement(); decompiler.addToken(Token.RC); mustMatchToken(Token.WHILE, "msg.no.while.do"); decompiler.addToken(Token.WHILE); Node cond = condition(); pn = nf.createDoWhile(loop, body, cond); } finally { exitLoop(); } // Always auto-insert semicon to follow SpiderMonkey: // It is required by EMAScript but is ignored by the rest of // world, see bug 238945 matchToken(Token.SEMI); decompiler.addEOL(Token.SEMI); return pn; } case Token.FOR: { consumeToken(); boolean isForEach = false; decompiler.addToken(Token.FOR); Node loop = enterLoop(statementLabel); try { Node init; // Node init is also foo in 'foo in Object' Node cond; // Node cond is also object in 'foo in Object' Node incr = null; // to kill warning Node body; // See if this is a for each () instead of just a for () if (matchToken(Token.NAME)) { decompiler.addName(ts.getString()); if (ts.getString().equals("each")) { isForEach = true; } else { reportError("msg.no.paren.for"); } } mustMatchToken(Token.LP, "msg.no.paren.for"); decompiler.addToken(Token.LP); tt = peekToken(); if (tt == Token.SEMI) { init = nf.createLeaf(Token.EMPTY); } else { if (tt == Token.VAR) { // set init to a var list or initial consumeToken(); // consume the 'var' token init = variables(true); } else { init = expr(true); } } if (matchToken(Token.IN)) { decompiler.addToken(Token.IN); // 'cond' is the object over which we're iterating cond = expr(false); } else { // ordinary for loop mustMatchToken(Token.SEMI, "msg.no.semi.for"); decompiler.addToken(Token.SEMI); if (peekToken() == Token.SEMI) { // no loop condition cond = nf.createLeaf(Token.EMPTY); } else { cond = expr(false); } mustMatchToken(Token.SEMI, "msg.no.semi.for.cond"); decompiler.addToken(Token.SEMI); if (peekToken() == Token.RP) { incr = nf.createLeaf(Token.EMPTY); } else { incr = expr(false); } } mustMatchToken(Token.RP, "msg.no.paren.for.ctrl"); decompiler.addToken(Token.RP); decompiler.addEOL(Token.LC); body = statement(); decompiler.addEOL(Token.RC); if (incr == null) { // cond could be null if 'in obj' got eaten // by the init node. pn = nf.createForIn(loop, init, cond, body, isForEach); } else { pn = nf.createFor(loop, init, cond, incr, body); } } finally { exitLoop(); } return pn; } case Token.TRY: { consumeToken(); int lineno = ts.getLineno(); Node tryblock; Node catchblocks = null; Node finallyblock = null; decompiler.addToken(Token.TRY); decompiler.addEOL(Token.LC); tryblock = statement(); decompiler.addEOL(Token.RC); catchblocks = nf.createLeaf(Token.BLOCK); boolean sawDefaultCatch = false; int peek = peekToken(); if (peek == Token.CATCH) { while (matchToken(Token.CATCH)) { if (sawDefaultCatch) { reportError("msg.catch.unreachable"); } decompiler.addToken(Token.CATCH); mustMatchToken(Token.LP, "msg.no.paren.catch"); decompiler.addToken(Token.LP); mustMatchToken(Token.NAME, "msg.bad.catchcond"); String varName = ts.getString(); decompiler.addName(varName); Node catchCond = null; if (matchToken(Token.IF)) { decompiler.addToken(Token.IF); catchCond = expr(false); } else { sawDefaultCatch = true; } mustMatchToken(Token.RP, "msg.bad.catchcond"); decompiler.addToken(Token.RP); mustMatchToken(Token.LC, "msg.no.brace.catchblock"); decompiler.addEOL(Token.LC); nf.addChildToBack(catchblocks, nf.createCatch(varName, catchCond, statements(), ts.getLineno())); mustMatchToken(Token.RC, "msg.no.brace.after.body"); decompiler.addEOL(Token.RC); } } else if (peek != Token.FINALLY) { mustMatchToken(Token.FINALLY, "msg.try.no.catchfinally"); } if (matchToken(Token.FINALLY)) { decompiler.addToken(Token.FINALLY); decompiler.addEOL(Token.LC); finallyblock = statement(); decompiler.addEOL(Token.RC); } pn = nf.createTryCatchFinally(tryblock, catchblocks, finallyblock, lineno); return pn; } case Token.THROW: { consumeToken(); if (peekTokenOrEOL() == Token.EOL) { // ECMAScript does not allow new lines before throw expression, // see bug 256617 reportError("msg.bad.throw.eol"); } int lineno = ts.getLineno(); decompiler.addToken(Token.THROW); pn = nf.createThrow(expr(false), lineno); break; } case Token.BREAK: { consumeToken(); int lineno = ts.getLineno(); decompiler.addToken(Token.BREAK); // matchJumpLabelName only matches if there is one Node breakStatement = matchJumpLabelName(); if (breakStatement == null) { if (loopAndSwitchSet == null || loopAndSwitchSet.size() == 0) { reportError("msg.bad.break"); return null; } breakStatement = (Node)loopAndSwitchSet.peek(); } pn = nf.createBreak(breakStatement, lineno); break; } case Token.CONTINUE: { consumeToken(); int lineno = ts.getLineno(); decompiler.addToken(Token.CONTINUE); Node loop; // matchJumpLabelName only matches if there is one Node label = matchJumpLabelName(); if (label == null) { if (loopSet == null || loopSet.size() == 0) { reportError("msg.continue.outside"); return null; } loop = (Node)loopSet.peek(); } else { loop = nf.getLabelLoop(label); if (loop == null) { reportError("msg.continue.nonloop"); return null; } } pn = nf.createContinue(loop, lineno); break; } case Token.WITH: { consumeToken(); decompiler.addToken(Token.WITH); int lineno = ts.getLineno(); mustMatchToken(Token.LP, "msg.no.paren.with"); decompiler.addToken(Token.LP); Node obj = expr(false); mustMatchToken(Token.RP, "msg.no.paren.after.with"); decompiler.addToken(Token.RP); decompiler.addEOL(Token.LC); ++nestingOfWith; Node body; try { body = statement(); } finally { --nestingOfWith; } decompiler.addEOL(Token.RC); pn = nf.createWith(obj, body, lineno); return pn; } case Token.VAR: { consumeToken(); pn = variables(false); break; } case Token.RETURN: { if (!insideFunction()) { reportError("msg.bad.return"); } consumeToken(); decompiler.addToken(Token.RETURN); int lineno = ts.getLineno(); Node retExpr; /* This is ugly, but we don't want to require a semicolon. */ tt = peekTokenOrEOL(); switch (tt) { case Token.SEMI: case Token.RC: case Token.EOF: case Token.EOL: case Token.ERROR: retExpr = null; break; default: retExpr = expr(false); } pn = nf.createReturn(retExpr, lineno); break; } case Token.LC: consumeToken(); if (statementLabel != null) { decompiler.addToken(Token.LC); } pn = statements(); mustMatchToken(Token.RC, "msg.no.brace.block"); if (statementLabel != null) { decompiler.addEOL(Token.RC); } return pn; case Token.ERROR: // Fall thru, to have a node for error recovery to work on case Token.SEMI: consumeToken(); pn = nf.createLeaf(Token.EMPTY); return pn; case Token.FUNCTION: { consumeToken(); pn = function(FunctionNode.FUNCTION_EXPRESSION_STATEMENT); return pn; } case Token.DEFAULT : consumeToken(); mustHaveXML(); decompiler.addToken(Token.DEFAULT); int nsLine = ts.getLineno(); if (!(matchToken(Token.NAME) && ts.getString().equals("xml"))) { reportError("msg.bad.namespace"); } decompiler.addName(ts.getString()); if (!(matchToken(Token.NAME) && ts.getString().equals("namespace"))) { reportError("msg.bad.namespace"); } decompiler.addName(ts.getString()); if (!matchToken(Token.ASSIGN)) { reportError("msg.bad.namespace"); } decompiler.addToken(Token.ASSIGN); Node expr = expr(false); pn = nf.createDefaultNamespace(expr, nsLine); break; case Token.NAME: { int lineno = ts.getLineno(); String name = ts.getString(); setCheckForLabel(); pn = expr(false); if (pn.getType() != Token.LABEL) { pn = nf.createExprStatement(pn, lineno); } else { // Parsed the label: push back token should be // colon that primaryExpr left untouched. if (peekToken() != Token.COLON) Kit.codeBug(); consumeToken(); // depend on decompiling lookahead to guess that that // last name was a label. decompiler.addName(name); decompiler.addEOL(Token.COLON); if (labelSet == null) { labelSet = new Hashtable(); } else if (labelSet.containsKey(name)) { reportError("msg.dup.label"); } boolean firstLabel; if (statementLabel == null) { firstLabel = true; statementLabel = pn; } else { // Discard multiple label nodes and use only // the first: it allows to simplify IRFactory firstLabel = false; } labelSet.put(name, statementLabel); try { pn = statementHelper(statementLabel); } finally { labelSet.remove(name); } if (firstLabel) { pn = nf.createLabeledStatement(statementLabel, pn); } return pn; } break; } default: { int lineno = ts.getLineno(); pn = expr(false); pn = nf.createExprStatement(pn, lineno); break; } } int ttFlagged = peekFlaggedToken(); switch (ttFlagged & CLEAR_TI_MASK) { case Token.SEMI: // Consume ';' as a part of expression consumeToken(); break; case Token.ERROR: case Token.EOF: case Token.RC: // Autoinsert ; break; default: if ((ttFlagged & TI_AFTER_EOL) == 0) { // Report error if no EOL or autoinsert ; otherwise reportError("msg.no.semi.stmt"); } break; } decompiler.addEOL(Token.SEMI); return pn; }
private Node statementHelper(Node statementLabel) throws IOException, ParserException { Node pn = null; int tt; tt = peekToken(); switch(tt) { case Token.IF: { consumeToken(); decompiler.addToken(Token.IF); int lineno = ts.getLineno(); Node cond = condition(); decompiler.addEOL(Token.LC); Node ifTrue = statement(); Node ifFalse = null; if (matchToken(Token.ELSE)) { decompiler.addToken(Token.RC); decompiler.addToken(Token.ELSE); decompiler.addEOL(Token.LC); ifFalse = statement(); } decompiler.addEOL(Token.RC); pn = nf.createIf(cond, ifTrue, ifFalse, lineno); return pn; } case Token.SWITCH: { consumeToken(); decompiler.addToken(Token.SWITCH); int lineno = ts.getLineno(); mustMatchToken(Token.LP, "msg.no.paren.switch"); decompiler.addToken(Token.LP); pn = enterSwitch(expr(false), lineno); try { mustMatchToken(Token.RP, "msg.no.paren.after.switch"); decompiler.addToken(Token.RP); mustMatchToken(Token.LC, "msg.no.brace.switch"); decompiler.addEOL(Token.LC); boolean hasDefault = false; switchLoop: for (;;) { tt = nextToken(); Node caseExpression; switch (tt) { case Token.RC: break switchLoop; case Token.CASE: decompiler.addToken(Token.CASE); caseExpression = expr(false); mustMatchToken(Token.COLON, "msg.no.colon.case"); decompiler.addEOL(Token.COLON); break; case Token.DEFAULT: if (hasDefault) { reportError("msg.double.switch.default"); } decompiler.addToken(Token.DEFAULT); hasDefault = true; caseExpression = null; mustMatchToken(Token.COLON, "msg.no.colon.case"); decompiler.addEOL(Token.COLON); break; default: reportError("msg.bad.switch"); break switchLoop; } Node block = nf.createLeaf(Token.BLOCK); while ((tt = peekToken()) != Token.RC && tt != Token.CASE && tt != Token.DEFAULT && tt != Token.EOF) { nf.addChildToBack(block, statement()); } // caseExpression == null => add default lable nf.addSwitchCase(pn, caseExpression, block); } decompiler.addEOL(Token.RC); nf.closeSwitch(pn); } finally { exitSwitch(); } return pn; } case Token.WHILE: { consumeToken(); decompiler.addToken(Token.WHILE); Node loop = enterLoop(statementLabel); try { Node cond = condition(); decompiler.addEOL(Token.LC); Node body = statement(); decompiler.addEOL(Token.RC); pn = nf.createWhile(loop, cond, body); } finally { exitLoop(); } return pn; } case Token.DO: { consumeToken(); decompiler.addToken(Token.DO); decompiler.addEOL(Token.LC); Node loop = enterLoop(statementLabel); try { Node body = statement(); decompiler.addToken(Token.RC); mustMatchToken(Token.WHILE, "msg.no.while.do"); decompiler.addToken(Token.WHILE); Node cond = condition(); pn = nf.createDoWhile(loop, body, cond); } finally { exitLoop(); } // Always auto-insert semicon to follow SpiderMonkey: // It is required by EMAScript but is ignored by the rest of // world, see bug 238945 matchToken(Token.SEMI); decompiler.addEOL(Token.SEMI); return pn; } case Token.FOR: { consumeToken(); boolean isForEach = false; decompiler.addToken(Token.FOR); Node loop = enterLoop(statementLabel); try { Node init; // Node init is also foo in 'foo in Object' Node cond; // Node cond is also object in 'foo in Object' Node incr = null; // to kill warning Node body; // See if this is a for each () instead of just a for () if (matchToken(Token.NAME)) { decompiler.addName(ts.getString()); if (ts.getString().equals("each")) { isForEach = true; } else { reportError("msg.no.paren.for"); } } mustMatchToken(Token.LP, "msg.no.paren.for"); decompiler.addToken(Token.LP); tt = peekToken(); if (tt == Token.SEMI) { init = nf.createLeaf(Token.EMPTY); } else { if (tt == Token.VAR) { // set init to a var list or initial consumeToken(); // consume the 'var' token init = variables(true); } else { init = expr(true); } } if (matchToken(Token.IN)) { decompiler.addToken(Token.IN); // 'cond' is the object over which we're iterating cond = expr(false); } else { // ordinary for loop mustMatchToken(Token.SEMI, "msg.no.semi.for"); decompiler.addToken(Token.SEMI); if (peekToken() == Token.SEMI) { // no loop condition cond = nf.createLeaf(Token.EMPTY); } else { cond = expr(false); } mustMatchToken(Token.SEMI, "msg.no.semi.for.cond"); decompiler.addToken(Token.SEMI); if (peekToken() == Token.RP) { incr = nf.createLeaf(Token.EMPTY); } else { incr = expr(false); } } mustMatchToken(Token.RP, "msg.no.paren.for.ctrl"); decompiler.addToken(Token.RP); decompiler.addEOL(Token.LC); body = statement(); decompiler.addEOL(Token.RC); if (incr == null) { // cond could be null if 'in obj' got eaten // by the init node. pn = nf.createForIn(loop, init, cond, body, isForEach); } else { pn = nf.createFor(loop, init, cond, incr, body); } } finally { exitLoop(); } return pn; } case Token.TRY: { consumeToken(); int lineno = ts.getLineno(); Node tryblock; Node catchblocks = null; Node finallyblock = null; decompiler.addToken(Token.TRY); decompiler.addEOL(Token.LC); tryblock = statement(); decompiler.addEOL(Token.RC); catchblocks = nf.createLeaf(Token.BLOCK); boolean sawDefaultCatch = false; int peek = peekToken(); if (peek == Token.CATCH) { while (matchToken(Token.CATCH)) { if (sawDefaultCatch) { reportError("msg.catch.unreachable"); } decompiler.addToken(Token.CATCH); mustMatchToken(Token.LP, "msg.no.paren.catch"); decompiler.addToken(Token.LP); mustMatchToken(Token.NAME, "msg.bad.catchcond"); String varName = ts.getString(); decompiler.addName(varName); Node catchCond = null; if (matchToken(Token.IF)) { decompiler.addToken(Token.IF); catchCond = expr(false); } else { sawDefaultCatch = true; } mustMatchToken(Token.RP, "msg.bad.catchcond"); decompiler.addToken(Token.RP); mustMatchToken(Token.LC, "msg.no.brace.catchblock"); decompiler.addEOL(Token.LC); nf.addChildToBack(catchblocks, nf.createCatch(varName, catchCond, statements(), ts.getLineno())); mustMatchToken(Token.RC, "msg.no.brace.after.body"); decompiler.addEOL(Token.RC); } } else if (peek != Token.FINALLY) { mustMatchToken(Token.FINALLY, "msg.try.no.catchfinally"); } if (matchToken(Token.FINALLY)) { decompiler.addToken(Token.FINALLY); decompiler.addEOL(Token.LC); finallyblock = statement(); decompiler.addEOL(Token.RC); } pn = nf.createTryCatchFinally(tryblock, catchblocks, finallyblock, lineno); return pn; } case Token.THROW: { consumeToken(); if (peekTokenOrEOL() == Token.EOL) { // ECMAScript does not allow new lines before throw expression, // see bug 256617 reportError("msg.bad.throw.eol"); } int lineno = ts.getLineno(); decompiler.addToken(Token.THROW); pn = nf.createThrow(expr(false), lineno); break; } case Token.BREAK: { consumeToken(); int lineno = ts.getLineno(); decompiler.addToken(Token.BREAK); // matchJumpLabelName only matches if there is one Node breakStatement = matchJumpLabelName(); if (breakStatement == null) { if (loopAndSwitchSet == null || loopAndSwitchSet.size() == 0) { reportError("msg.bad.break"); return null; } breakStatement = (Node)loopAndSwitchSet.peek(); } pn = nf.createBreak(breakStatement, lineno); break; } case Token.CONTINUE: { consumeToken(); int lineno = ts.getLineno(); decompiler.addToken(Token.CONTINUE); Node loop; // matchJumpLabelName only matches if there is one Node label = matchJumpLabelName(); if (label == null) { if (loopSet == null || loopSet.size() == 0) { reportError("msg.continue.outside"); return null; } loop = (Node)loopSet.peek(); } else { loop = nf.getLabelLoop(label); if (loop == null) { reportError("msg.continue.nonloop"); return null; } } pn = nf.createContinue(loop, lineno); break; } case Token.WITH: { consumeToken(); decompiler.addToken(Token.WITH); int lineno = ts.getLineno(); mustMatchToken(Token.LP, "msg.no.paren.with"); decompiler.addToken(Token.LP); Node obj = expr(false); mustMatchToken(Token.RP, "msg.no.paren.after.with"); decompiler.addToken(Token.RP); decompiler.addEOL(Token.LC); ++nestingOfWith; Node body; try { body = statement(); } finally { --nestingOfWith; } decompiler.addEOL(Token.RC); pn = nf.createWith(obj, body, lineno); return pn; } case Token.VAR: { consumeToken(); pn = variables(false); break; } case Token.RETURN: { if (!insideFunction()) { reportError("msg.bad.return"); } consumeToken(); decompiler.addToken(Token.RETURN); int lineno = ts.getLineno(); Node retExpr; /* This is ugly, but we don't want to require a semicolon. */ tt = peekTokenOrEOL(); switch (tt) { case Token.SEMI: case Token.RC: case Token.EOF: case Token.EOL: case Token.ERROR: retExpr = null; break; default: retExpr = expr(false); } pn = nf.createReturn(retExpr, lineno); break; } case Token.LC: consumeToken(); if (statementLabel != null) { decompiler.addToken(Token.LC); } pn = statements(); mustMatchToken(Token.RC, "msg.no.brace.block"); if (statementLabel != null) { decompiler.addEOL(Token.RC); } return pn; case Token.ERROR: // Fall thru, to have a node for error recovery to work on case Token.SEMI: consumeToken(); pn = nf.createLeaf(Token.EMPTY); return pn; case Token.FUNCTION: { consumeToken(); pn = function(FunctionNode.FUNCTION_EXPRESSION_STATEMENT); return pn; } case Token.DEFAULT : consumeToken(); mustHaveXML(); decompiler.addToken(Token.DEFAULT); int nsLine = ts.getLineno(); if (!(matchToken(Token.NAME) && ts.getString().equals("xml"))) { reportError("msg.bad.namespace"); } decompiler.addName(" xml"); if (!(matchToken(Token.NAME) && ts.getString().equals("namespace"))) { reportError("msg.bad.namespace"); } decompiler.addName(" namespace"); if (!matchToken(Token.ASSIGN)) { reportError("msg.bad.namespace"); } decompiler.addToken(Token.ASSIGN); Node expr = expr(false); pn = nf.createDefaultNamespace(expr, nsLine); break; case Token.NAME: { int lineno = ts.getLineno(); String name = ts.getString(); setCheckForLabel(); pn = expr(false); if (pn.getType() != Token.LABEL) { pn = nf.createExprStatement(pn, lineno); } else { // Parsed the label: push back token should be // colon that primaryExpr left untouched. if (peekToken() != Token.COLON) Kit.codeBug(); consumeToken(); // depend on decompiling lookahead to guess that that // last name was a label. decompiler.addName(name); decompiler.addEOL(Token.COLON); if (labelSet == null) { labelSet = new Hashtable(); } else if (labelSet.containsKey(name)) { reportError("msg.dup.label"); } boolean firstLabel; if (statementLabel == null) { firstLabel = true; statementLabel = pn; } else { // Discard multiple label nodes and use only // the first: it allows to simplify IRFactory firstLabel = false; } labelSet.put(name, statementLabel); try { pn = statementHelper(statementLabel); } finally { labelSet.remove(name); } if (firstLabel) { pn = nf.createLabeledStatement(statementLabel, pn); } return pn; } break; } default: { int lineno = ts.getLineno(); pn = expr(false); pn = nf.createExprStatement(pn, lineno); break; } } int ttFlagged = peekFlaggedToken(); switch (ttFlagged & CLEAR_TI_MASK) { case Token.SEMI: // Consume ';' as a part of expression consumeToken(); break; case Token.ERROR: case Token.EOF: case Token.RC: // Autoinsert ; break; default: if ((ttFlagged & TI_AFTER_EOL) == 0) { // Report error if no EOL or autoinsert ; otherwise reportError("msg.no.semi.stmt"); } break; } decompiler.addEOL(Token.SEMI); return pn; }
diff --git a/src/net/sf/freecol/server/ai/mission/UnitWanderHostileMission.java b/src/net/sf/freecol/server/ai/mission/UnitWanderHostileMission.java index 708f5587d..3e1255adf 100644 --- a/src/net/sf/freecol/server/ai/mission/UnitWanderHostileMission.java +++ b/src/net/sf/freecol/server/ai/mission/UnitWanderHostileMission.java @@ -1,169 +1,178 @@ /** * Copyright (C) 2002-2007 The FreeCol Team * * This file is part of FreeCol. * * FreeCol 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. * * FreeCol 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 FreeCol. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.freecol.server.ai.mission; import java.io.IOException; import java.util.logging.Logger; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamWriter; import net.sf.freecol.common.model.Map; import net.sf.freecol.common.model.Map.Direction; import net.sf.freecol.common.model.PathNode; import net.sf.freecol.common.model.Tile; import net.sf.freecol.common.model.Unit; import net.sf.freecol.common.model.Unit.MoveType; import net.sf.freecol.common.networking.Connection; import net.sf.freecol.common.networking.Message; import net.sf.freecol.server.ai.AIMain; import net.sf.freecol.server.ai.AIObject; import net.sf.freecol.server.ai.AIUnit; import org.w3c.dom.Element; /** * Mission for attacking any unit owned by a player we do not like that is within * a radius of 1 tile. If no such unit can be found; just wander * around. */ public class UnitWanderHostileMission extends Mission { private static final Logger logger = Logger.getLogger(UnitWanderHostileMission.class.getName()); /** * Creates a mission for the given <code>AIUnit</code>. * * @param aiMain The main AI-object. * @param aiUnit The <code>AIUnit</code> this mission * is created for. */ public UnitWanderHostileMission(AIMain aiMain, AIUnit aiUnit) { super(aiMain, aiUnit); } /** * Loads a mission from the given element. * * @param aiMain The main AI-object. * @param element An <code>Element</code> containing an * XML-representation of this object. */ public UnitWanderHostileMission(AIMain aiMain, Element element) { super(aiMain); readFromXMLElement(element); } /** * Creates a new <code>UnitWanderHostileMission</code> and reads the given element. * * @param aiMain The main AI-object. * @param in The input stream containing the XML. * @throws XMLStreamException if a problem was encountered * during parsing. * @see AIObject#readFromXML */ public UnitWanderHostileMission(AIMain aiMain, XMLStreamReader in) throws XMLStreamException { super(aiMain); readFromXML(in); } /** * Performs the mission. This is done by searching for hostile units * that are located within one tile and attacking them. If no such units * are found, then wander in a random direction. * * @param connection The <code>Connection</code> to the server. */ public void doMission(Connection connection) { Tile thisTile = getUnit().getTile(); Unit unit = getUnit(); Map map = getGame().getMap(); if (!(unit.getLocation() instanceof Tile)) { return; } PathNode pathToTarget = null; if (unit.isOffensiveUnit()) { pathToTarget = findTarget(5); } if (pathToTarget != null) { Direction direction = moveTowards(connection, pathToTarget); if (direction != null && unit.getMoveType(direction) == MoveType.ATTACK) { Element element = Message.createNewRootElement("attack"); element.setAttribute("unit", unit.getId()); element.setAttribute("direction", direction.toString()); try { connection.ask(element); } catch (IOException e) { logger.warning("Could not send message!"); } } + } else if (unit.getIndianSettlement() != null) { + if (unit.getIndianSettlement().getTile() != unit.getTile()) { + logger.finest("Unit " + unit.getId() + ": No target found - returning to settlement."); + Direction direction = moveTowards(connection, unit.getIndianSettlement().getTile()); + moveButDontAttack(connection, direction); + } else { + logger.finest("Unit " + unit.getId() + ": No target found - entering settlement."); + unit.getIndianSettlement().add(unit); + } } else { // Just make a random move if no target can be found. moveRandomly(connection); } } /** * Writes all of the <code>AIObject</code>s and other AI-related * information to an XML-stream. * * @param out The target stream. * @throws XMLStreamException if there are any problems writing * to the stream. */ protected void toXMLImpl(XMLStreamWriter out) throws XMLStreamException { out.writeStartElement(getXMLElementTagName()); out.writeAttribute("unit", getUnit().getId()); out.writeEndElement(); } /** * Reads all the <code>AIObject</code>s and other AI-related information * from XML data. * @param in The input stream with the XML. */ protected void readFromXMLImpl(XMLStreamReader in) throws XMLStreamException { setAIUnit((AIUnit) getAIMain().getAIObject(in.getAttributeValue(null, "unit"))); in.nextTag(); } /** * Returns the tag name of the root element representing this object. * @return The <code>String</code> "unitWanderHostileMission". */ public static String getXMLElementTagName() { return "unitWanderHostileMission"; } }
true
true
public void doMission(Connection connection) { Tile thisTile = getUnit().getTile(); Unit unit = getUnit(); Map map = getGame().getMap(); if (!(unit.getLocation() instanceof Tile)) { return; } PathNode pathToTarget = null; if (unit.isOffensiveUnit()) { pathToTarget = findTarget(5); } if (pathToTarget != null) { Direction direction = moveTowards(connection, pathToTarget); if (direction != null && unit.getMoveType(direction) == MoveType.ATTACK) { Element element = Message.createNewRootElement("attack"); element.setAttribute("unit", unit.getId()); element.setAttribute("direction", direction.toString()); try { connection.ask(element); } catch (IOException e) { logger.warning("Could not send message!"); } } } else { // Just make a random move if no target can be found. moveRandomly(connection); } }
public void doMission(Connection connection) { Tile thisTile = getUnit().getTile(); Unit unit = getUnit(); Map map = getGame().getMap(); if (!(unit.getLocation() instanceof Tile)) { return; } PathNode pathToTarget = null; if (unit.isOffensiveUnit()) { pathToTarget = findTarget(5); } if (pathToTarget != null) { Direction direction = moveTowards(connection, pathToTarget); if (direction != null && unit.getMoveType(direction) == MoveType.ATTACK) { Element element = Message.createNewRootElement("attack"); element.setAttribute("unit", unit.getId()); element.setAttribute("direction", direction.toString()); try { connection.ask(element); } catch (IOException e) { logger.warning("Could not send message!"); } } } else if (unit.getIndianSettlement() != null) { if (unit.getIndianSettlement().getTile() != unit.getTile()) { logger.finest("Unit " + unit.getId() + ": No target found - returning to settlement."); Direction direction = moveTowards(connection, unit.getIndianSettlement().getTile()); moveButDontAttack(connection, direction); } else { logger.finest("Unit " + unit.getId() + ": No target found - entering settlement."); unit.getIndianSettlement().add(unit); } } else { // Just make a random move if no target can be found. moveRandomly(connection); } }
diff --git a/src/com/jakewharton/wakkawallpaper/Entity.java b/src/com/jakewharton/wakkawallpaper/Entity.java index 10f228d..32090e7 100644 --- a/src/com/jakewharton/wakkawallpaper/Entity.java +++ b/src/com/jakewharton/wakkawallpaper/Entity.java @@ -1,313 +1,311 @@ package com.jakewharton.wakkawallpaper; import android.graphics.Canvas; import android.graphics.Point; import android.graphics.PointF; import android.util.Log; /** * The Entity class represents an object that can move within the game board. * * @author Jake Wharton */ public abstract class Entity { enum Direction { NORTH(270), SOUTH(90), EAST(0), WEST(180); private static final int DEGREES_IN_CIRCLE = 360; protected final int angle; /** * Create a direction with specified angle. * * @param angle Angle in degrees. */ private Direction(final int angle) { this.angle = angle; } /** * Get the angle of the direction taking into account the next direction. * * @param nextDirection The next direction. * @return Angle. */ public int getAngle(final Direction nextDirection) { if ((nextDirection == null) || (this == nextDirection) || (this.getOpposite() == nextDirection)) { return this.angle; } else { int angle1 = this.angle; int angle2 = nextDirection.angle; //Special case NORTH and EAST since (270+0)/2 is not what we want if ((this == Direction.NORTH) && (nextDirection == Direction.EAST)) { angle2 += Direction.DEGREES_IN_CIRCLE; } else if ((this == Direction.EAST) && (nextDirection == Direction.NORTH)) { angle1 += Direction.DEGREES_IN_CIRCLE; } return (angle1 + angle2) / 2; } } /** * Get the direction that is the opposite of this one. * * @return Opposite direction. */ public Direction getOpposite() { switch (this) { case NORTH: return Direction.SOUTH; case SOUTH: return Direction.NORTH; case EAST: return Direction.WEST; case WEST: return Direction.EAST; default: return null; } } } private static final String TAG = "WakkaWallpaper.Entity"; protected final Point mPosition; protected final PointF mLocation; protected Direction mDirectionLast; protected Direction mDirectionCurrent; protected Direction mDirectionNext; protected float mSpeed; protected float mCellWidth; protected float mCellHeight; protected float mCellWidthOverTwo; protected float mCellHeightOverTwo; protected int mTickCount; /** * Create a new entity. */ protected Entity() { this.mPosition = new Point(); this.mLocation = new PointF(); this.mDirectionCurrent = null; this.mDirectionNext = null; this.mSpeed = 1.0f; //100% this.mCellWidth = 0; this.mCellHeight = 0; this.mTickCount = 0; } /** * Resize the entity to fit within the specified dimensions. * * @param width New width. * @param height New height. */ public void performResize(final Game game) { if (Wallpaper.LOG_VERBOSE) { Log.v(Entity.TAG, "> performResize()"); } this.mCellWidth = game.getCellWidth(); this.mCellHeight = game.getCellHeight(); this.mCellWidthOverTwo = this.mCellWidth / 2.0f; this.mCellHeightOverTwo = this.mCellHeight / 2.0f; //Reset position to update location this.setPosition(this.mPosition); if (Wallpaper.LOG_VERBOSE) { Log.v(Entity.TAG, "< performResize()"); } } /** * Get the current position of the entity. * * @return Position. */ public Point getPosition() { return this.mPosition; } /** * Get the current location of the entity. * * @return Position. */ public PointF getLocation() { return this.mLocation; } /** * Get the current direction of the entity. * * @return Position. */ public Direction getDirection() { return this.mDirectionCurrent; } /** * Set the board position and location. * * @param x X coordinate. * @param y Y coordinate. */ public void setPosition(final Point position) { this.mPosition.set(position.x, position.y); this.mLocation.set((position.x * this.mCellWidth) + this.mCellWidthOverTwo, (position.y * this.mCellHeight) + this.mCellHeightOverTwo); } /** * Test if this entity is occupying the same cell as another. * * @param other Other entity. * @return Whether or not they are occupying the same cell. */ public boolean isCollidingWith(final Entity other) { return ((this.mPosition.x == other.getPosition().x) && (this.mPosition.y == other.getPosition().y)); } /** * Iterate the entity one step. * * @param game Game instance */ public void tick(final Game game) { this.mTickCount += 1; - if (Wallpaper.LOG_DEBUG) { - if (this.mDirectionNext == null) { - Log.w(Entity.TAG, this.getClass().getSimpleName() + "'s next direction is null. This will result in a fatal error."); - Log.w(Entity.TAG, "Position: (" + this.mPosition.x + ", " + this.mPosition.y + ")"); - Log.w(Entity.TAG, "Location: (" + this.mLocation.x + ", " + this.mLocation.y + ")"); - Log.w(Entity.TAG, "Direction Current: " + this.mDirectionCurrent); - Log.w(Entity.TAG, "Direction Last: " + this.mDirectionLast); - Log.w(Entity.TAG, "Speed: " + (this.mSpeed * 100) + "%"); - } + if (this.mDirectionNext == null) { + Log.w(Entity.TAG, this.getClass().getSimpleName() + "'s next direction is null. This will result in a fatal error."); + Log.w(Entity.TAG, "Position: (" + this.mPosition.x + ", " + this.mPosition.y + ")"); + Log.w(Entity.TAG, "Location: (" + this.mLocation.x + ", " + this.mLocation.y + ")"); + Log.w(Entity.TAG, "Direction Current: " + this.mDirectionCurrent); + Log.w(Entity.TAG, "Direction Last: " + this.mDirectionLast); + Log.w(Entity.TAG, "Speed: " + (this.mSpeed * 100) + "%"); } //Promote current direction to last this.mDirectionLast = this.mDirectionCurrent; //Promote next direction to current this.mDirectionCurrent = this.mDirectionNext; //Next direction fallback. Will be set by implementing moved() method call. this.mDirectionNext = null; //TODO: move this.mLocation based on this.mSpeed and this.mDirectionCurrent switch (this.mDirectionCurrent) { case NORTH: this.mLocation.set((this.mPosition.x * this.mCellWidth) + this.mCellWidthOverTwo, ((this.mPosition.y - 1) * this.mCellHeight) + this.mCellHeightOverTwo); break; case SOUTH: this.mLocation.set((this.mPosition.x * this.mCellWidth) + this.mCellWidthOverTwo, ((this.mPosition.y + 1) * this.mCellHeight) + this.mCellHeightOverTwo); break; case EAST: this.mLocation.set(((this.mPosition.x + 1) * this.mCellWidth) + this.mCellWidthOverTwo, (this.mPosition.y * this.mCellHeight) + this.mCellHeightOverTwo); break; case WEST: this.mLocation.set(((this.mPosition.x - 1) * this.mCellWidth) + this.mCellWidthOverTwo, (this.mPosition.y * this.mCellHeight) + this.mCellHeightOverTwo); break; } //Move to next space if we are far enough boolean moved = false; if (this.mLocation.x >= ((this.mPosition.x + 1) * this.mCellWidth)) { this.mPosition.x += 1; moved = true; } else if (this.mLocation.x < (this.mPosition.x * this.mCellWidth)) { this.mPosition.x -= 1; moved = true; } else if (this.mLocation.y >= ((this.mPosition.y + 1) * this.mCellHeight)) { this.mPosition.y += 1; moved = true; } else if (this.mLocation.y < (this.mPosition.y * this.mCellHeight)) { this.mPosition.y -= 1; moved = true; } if (moved) { this.moved(game); } if (Wallpaper.LOG_VERBOSE) { Log.v(Entity.TAG, "Position: (" + this.mPosition.x + "," + this.mPosition.y + "); Location: (" + this.mLocation.x + "," + this.mLocation.y + "); Direction: " + this.mDirectionCurrent + "; Next: " + this.mDirectionNext); } } /** * Render the entity on the Canvas. * * @param c Canvas on which to draw. */ public abstract void draw(final Canvas c, final boolean isLandscape); /** * Triggered when we have moved into a new cell. * * @param game Game instance */ protected abstract void moved(final Game game); /** * Triggered to reset to initial level state. * * @param game Game instance */ protected abstract void newLevel(final Game game); /** * Triggered to reset to initial level position. * * @param game Game instance */ public abstract void newLife(final Game game); /** * Update the point one step in the direction specified. * * @param point Point of original coordinates. * @param direction Direction in which to move the point. * @return New point coordinates. */ protected static Point move(final Point point, final Direction direction) { return Entity.move(point, direction, 1); } /** * Update the point in the direction specified by a specific number of steps. * * @param point Point of original coordinates. * @param direction Direction in which to move the point. * @param setps Number of steps to move point. * @return New point coordinates. */ protected static Point move(final Point point, final Direction direction, final int steps) { final Point newPoint = new Point(point); if (direction != null) { switch (direction) { case NORTH: newPoint.y -= steps; break; case SOUTH: newPoint.y += steps; break; case WEST: newPoint.x -= steps; break; case EAST: newPoint.x += steps; break; } } return newPoint; } }
true
true
public void tick(final Game game) { this.mTickCount += 1; if (Wallpaper.LOG_DEBUG) { if (this.mDirectionNext == null) { Log.w(Entity.TAG, this.getClass().getSimpleName() + "'s next direction is null. This will result in a fatal error."); Log.w(Entity.TAG, "Position: (" + this.mPosition.x + ", " + this.mPosition.y + ")"); Log.w(Entity.TAG, "Location: (" + this.mLocation.x + ", " + this.mLocation.y + ")"); Log.w(Entity.TAG, "Direction Current: " + this.mDirectionCurrent); Log.w(Entity.TAG, "Direction Last: " + this.mDirectionLast); Log.w(Entity.TAG, "Speed: " + (this.mSpeed * 100) + "%"); } } //Promote current direction to last this.mDirectionLast = this.mDirectionCurrent; //Promote next direction to current this.mDirectionCurrent = this.mDirectionNext; //Next direction fallback. Will be set by implementing moved() method call. this.mDirectionNext = null; //TODO: move this.mLocation based on this.mSpeed and this.mDirectionCurrent switch (this.mDirectionCurrent) { case NORTH: this.mLocation.set((this.mPosition.x * this.mCellWidth) + this.mCellWidthOverTwo, ((this.mPosition.y - 1) * this.mCellHeight) + this.mCellHeightOverTwo); break; case SOUTH: this.mLocation.set((this.mPosition.x * this.mCellWidth) + this.mCellWidthOverTwo, ((this.mPosition.y + 1) * this.mCellHeight) + this.mCellHeightOverTwo); break; case EAST: this.mLocation.set(((this.mPosition.x + 1) * this.mCellWidth) + this.mCellWidthOverTwo, (this.mPosition.y * this.mCellHeight) + this.mCellHeightOverTwo); break; case WEST: this.mLocation.set(((this.mPosition.x - 1) * this.mCellWidth) + this.mCellWidthOverTwo, (this.mPosition.y * this.mCellHeight) + this.mCellHeightOverTwo); break; } //Move to next space if we are far enough boolean moved = false; if (this.mLocation.x >= ((this.mPosition.x + 1) * this.mCellWidth)) { this.mPosition.x += 1; moved = true; } else if (this.mLocation.x < (this.mPosition.x * this.mCellWidth)) { this.mPosition.x -= 1; moved = true; } else if (this.mLocation.y >= ((this.mPosition.y + 1) * this.mCellHeight)) { this.mPosition.y += 1; moved = true; } else if (this.mLocation.y < (this.mPosition.y * this.mCellHeight)) { this.mPosition.y -= 1; moved = true; } if (moved) { this.moved(game); } if (Wallpaper.LOG_VERBOSE) { Log.v(Entity.TAG, "Position: (" + this.mPosition.x + "," + this.mPosition.y + "); Location: (" + this.mLocation.x + "," + this.mLocation.y + "); Direction: " + this.mDirectionCurrent + "; Next: " + this.mDirectionNext); } }
public void tick(final Game game) { this.mTickCount += 1; if (this.mDirectionNext == null) { Log.w(Entity.TAG, this.getClass().getSimpleName() + "'s next direction is null. This will result in a fatal error."); Log.w(Entity.TAG, "Position: (" + this.mPosition.x + ", " + this.mPosition.y + ")"); Log.w(Entity.TAG, "Location: (" + this.mLocation.x + ", " + this.mLocation.y + ")"); Log.w(Entity.TAG, "Direction Current: " + this.mDirectionCurrent); Log.w(Entity.TAG, "Direction Last: " + this.mDirectionLast); Log.w(Entity.TAG, "Speed: " + (this.mSpeed * 100) + "%"); } //Promote current direction to last this.mDirectionLast = this.mDirectionCurrent; //Promote next direction to current this.mDirectionCurrent = this.mDirectionNext; //Next direction fallback. Will be set by implementing moved() method call. this.mDirectionNext = null; //TODO: move this.mLocation based on this.mSpeed and this.mDirectionCurrent switch (this.mDirectionCurrent) { case NORTH: this.mLocation.set((this.mPosition.x * this.mCellWidth) + this.mCellWidthOverTwo, ((this.mPosition.y - 1) * this.mCellHeight) + this.mCellHeightOverTwo); break; case SOUTH: this.mLocation.set((this.mPosition.x * this.mCellWidth) + this.mCellWidthOverTwo, ((this.mPosition.y + 1) * this.mCellHeight) + this.mCellHeightOverTwo); break; case EAST: this.mLocation.set(((this.mPosition.x + 1) * this.mCellWidth) + this.mCellWidthOverTwo, (this.mPosition.y * this.mCellHeight) + this.mCellHeightOverTwo); break; case WEST: this.mLocation.set(((this.mPosition.x - 1) * this.mCellWidth) + this.mCellWidthOverTwo, (this.mPosition.y * this.mCellHeight) + this.mCellHeightOverTwo); break; } //Move to next space if we are far enough boolean moved = false; if (this.mLocation.x >= ((this.mPosition.x + 1) * this.mCellWidth)) { this.mPosition.x += 1; moved = true; } else if (this.mLocation.x < (this.mPosition.x * this.mCellWidth)) { this.mPosition.x -= 1; moved = true; } else if (this.mLocation.y >= ((this.mPosition.y + 1) * this.mCellHeight)) { this.mPosition.y += 1; moved = true; } else if (this.mLocation.y < (this.mPosition.y * this.mCellHeight)) { this.mPosition.y -= 1; moved = true; } if (moved) { this.moved(game); } if (Wallpaper.LOG_VERBOSE) { Log.v(Entity.TAG, "Position: (" + this.mPosition.x + "," + this.mPosition.y + "); Location: (" + this.mLocation.x + "," + this.mLocation.y + "); Direction: " + this.mDirectionCurrent + "; Next: " + this.mDirectionNext); } }
diff --git a/src/com/untamedears/ItemExchange/command/commands/CreateCommand.java b/src/com/untamedears/ItemExchange/command/commands/CreateCommand.java index 834e3ec..27c5d29 100644 --- a/src/com/untamedears/ItemExchange/command/commands/CreateCommand.java +++ b/src/com/untamedears/ItemExchange/command/commands/CreateCommand.java @@ -1,119 +1,119 @@ package com.untamedears.ItemExchange.command.commands; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.ItemStack; import com.untamedears.ItemExchange.ItemExchangePlugin; import com.untamedears.ItemExchange.command.PlayerCommand; import com.untamedears.ItemExchange.exceptions.ExchangeRuleCreateException; import com.untamedears.ItemExchange.exceptions.ExchangeRuleParseException; import com.untamedears.ItemExchange.utility.ExchangeRule; import com.untamedears.ItemExchange.utility.ExchangeRule.RuleType; import com.untamedears.ItemExchange.utility.ItemExchange; /* * General command for creating either an entire ItemExchange or * creating an exchange rule, given the context of the player when * the command is issued. */ public class CreateCommand extends PlayerCommand { public CreateCommand() { super("Create Exchange"); setDescription("Automatically creates an exchange inside the chest the player is looking at"); setUsage("/iecreate"); setArgumentRange(0, 3); setIdentifiers(new String[] { "iecreate", "iec" }); } @Override public boolean execute(CommandSender sender, String[] args) { Player player = (Player) sender; - Block block = player.getLastTwoTargetBlocks(null, 20).get(1).getLocation().getBlock(); + Block block = player.getLastTwoTargetBlocks(null, 5).get(1).getLocation().getBlock(); //If no input or ouptut is specified player attempt to set up ItemExchange at the block the player is looking at //The player must have citadel access to the inventory block if (args.length == 0) { if (ItemExchangePlugin.ACCEPTABLE_BLOCKS.contains(block.getState().getType())) { PlayerInteractEvent event = new PlayerInteractEvent(player, Action.RIGHT_CLICK_BLOCK, player.getItemInHand(), block, BlockFace.UP); Bukkit.getPluginManager().callEvent(event); if(!event.isCancelled()) player.sendMessage(ItemExchange.createExchange(block.getLocation(), player)); } else { player.sendMessage(ChatColor.RED + "Block in view is not suitable for an Item Exchange."); } } //Create a RuleBlock in the players inventory else { //Player must have space in their inventory for the RuleBlock if (player.getInventory().firstEmpty() != -1) { //If only an input/output is specified create the RuleBlock based on the item held in the players hand if (args.length == 1) { //Assign a ruleType RuleType ruleType = null; if (args[0].equalsIgnoreCase("input")) { ruleType = ExchangeRule.RuleType.INPUT; } else if (args[0].equalsIgnoreCase("output")) { ruleType = ExchangeRule.RuleType.OUTPUT; } if (ruleType != null) { ItemStack inHand = player.getItemInHand(); if(inHand == null || inHand.getType() == Material.AIR) { player.sendMessage(ChatColor.RED + "You are not holding anything in your hand!"); return true; } if(ExchangeRule.isRuleBlock(inHand)) { player.sendMessage(ChatColor.RED + "You cannot exchange rule blocks!"); return true; } //Creates the ExchangeRule, converts it to an ItemStack and places it in the player's inventory try { player.getInventory().addItem(ExchangeRule.parseItemStack(inHand, ruleType).toItemStack()); } catch (IllegalArgumentException | ExchangeRuleCreateException e) { player.sendMessage(ChatColor.RED + e.getMessage()); return true; } player.sendMessage(ChatColor.GREEN + "Created Rule Block!"); } else { player.sendMessage(ChatColor.RED + "Please specify and input or output."); } } //If additional arguments are specified create an exchange rule based upon the additional arguments and place it in the player's inventory else if (args.length >= 2) { try { //Attempts to create the ExchangeRule, converts it to an ItemStack and places it in the player's inventory player.getInventory().addItem(ExchangeRule.parseCreateCommand(args).toItemStack()); player.sendMessage(ChatColor.GREEN + "Created Rule Block!"); } catch (ExchangeRuleParseException e) { player.sendMessage(ChatColor.RED + "Incorrect entry format: " + e.getMessage()); } } } else { player.sendMessage(ChatColor.RED + "Player inventory is full!"); } } return true; } }
true
true
public boolean execute(CommandSender sender, String[] args) { Player player = (Player) sender; Block block = player.getLastTwoTargetBlocks(null, 20).get(1).getLocation().getBlock(); //If no input or ouptut is specified player attempt to set up ItemExchange at the block the player is looking at //The player must have citadel access to the inventory block if (args.length == 0) { if (ItemExchangePlugin.ACCEPTABLE_BLOCKS.contains(block.getState().getType())) { PlayerInteractEvent event = new PlayerInteractEvent(player, Action.RIGHT_CLICK_BLOCK, player.getItemInHand(), block, BlockFace.UP); Bukkit.getPluginManager().callEvent(event); if(!event.isCancelled()) player.sendMessage(ItemExchange.createExchange(block.getLocation(), player)); } else { player.sendMessage(ChatColor.RED + "Block in view is not suitable for an Item Exchange."); } } //Create a RuleBlock in the players inventory else { //Player must have space in their inventory for the RuleBlock if (player.getInventory().firstEmpty() != -1) { //If only an input/output is specified create the RuleBlock based on the item held in the players hand if (args.length == 1) { //Assign a ruleType RuleType ruleType = null; if (args[0].equalsIgnoreCase("input")) { ruleType = ExchangeRule.RuleType.INPUT; } else if (args[0].equalsIgnoreCase("output")) { ruleType = ExchangeRule.RuleType.OUTPUT; } if (ruleType != null) { ItemStack inHand = player.getItemInHand(); if(inHand == null || inHand.getType() == Material.AIR) { player.sendMessage(ChatColor.RED + "You are not holding anything in your hand!"); return true; } if(ExchangeRule.isRuleBlock(inHand)) { player.sendMessage(ChatColor.RED + "You cannot exchange rule blocks!"); return true; } //Creates the ExchangeRule, converts it to an ItemStack and places it in the player's inventory try { player.getInventory().addItem(ExchangeRule.parseItemStack(inHand, ruleType).toItemStack()); } catch (IllegalArgumentException | ExchangeRuleCreateException e) { player.sendMessage(ChatColor.RED + e.getMessage()); return true; } player.sendMessage(ChatColor.GREEN + "Created Rule Block!"); } else { player.sendMessage(ChatColor.RED + "Please specify and input or output."); } } //If additional arguments are specified create an exchange rule based upon the additional arguments and place it in the player's inventory else if (args.length >= 2) { try { //Attempts to create the ExchangeRule, converts it to an ItemStack and places it in the player's inventory player.getInventory().addItem(ExchangeRule.parseCreateCommand(args).toItemStack()); player.sendMessage(ChatColor.GREEN + "Created Rule Block!"); } catch (ExchangeRuleParseException e) { player.sendMessage(ChatColor.RED + "Incorrect entry format: " + e.getMessage()); } } } else { player.sendMessage(ChatColor.RED + "Player inventory is full!"); } } return true; }
public boolean execute(CommandSender sender, String[] args) { Player player = (Player) sender; Block block = player.getLastTwoTargetBlocks(null, 5).get(1).getLocation().getBlock(); //If no input or ouptut is specified player attempt to set up ItemExchange at the block the player is looking at //The player must have citadel access to the inventory block if (args.length == 0) { if (ItemExchangePlugin.ACCEPTABLE_BLOCKS.contains(block.getState().getType())) { PlayerInteractEvent event = new PlayerInteractEvent(player, Action.RIGHT_CLICK_BLOCK, player.getItemInHand(), block, BlockFace.UP); Bukkit.getPluginManager().callEvent(event); if(!event.isCancelled()) player.sendMessage(ItemExchange.createExchange(block.getLocation(), player)); } else { player.sendMessage(ChatColor.RED + "Block in view is not suitable for an Item Exchange."); } } //Create a RuleBlock in the players inventory else { //Player must have space in their inventory for the RuleBlock if (player.getInventory().firstEmpty() != -1) { //If only an input/output is specified create the RuleBlock based on the item held in the players hand if (args.length == 1) { //Assign a ruleType RuleType ruleType = null; if (args[0].equalsIgnoreCase("input")) { ruleType = ExchangeRule.RuleType.INPUT; } else if (args[0].equalsIgnoreCase("output")) { ruleType = ExchangeRule.RuleType.OUTPUT; } if (ruleType != null) { ItemStack inHand = player.getItemInHand(); if(inHand == null || inHand.getType() == Material.AIR) { player.sendMessage(ChatColor.RED + "You are not holding anything in your hand!"); return true; } if(ExchangeRule.isRuleBlock(inHand)) { player.sendMessage(ChatColor.RED + "You cannot exchange rule blocks!"); return true; } //Creates the ExchangeRule, converts it to an ItemStack and places it in the player's inventory try { player.getInventory().addItem(ExchangeRule.parseItemStack(inHand, ruleType).toItemStack()); } catch (IllegalArgumentException | ExchangeRuleCreateException e) { player.sendMessage(ChatColor.RED + e.getMessage()); return true; } player.sendMessage(ChatColor.GREEN + "Created Rule Block!"); } else { player.sendMessage(ChatColor.RED + "Please specify and input or output."); } } //If additional arguments are specified create an exchange rule based upon the additional arguments and place it in the player's inventory else if (args.length >= 2) { try { //Attempts to create the ExchangeRule, converts it to an ItemStack and places it in the player's inventory player.getInventory().addItem(ExchangeRule.parseCreateCommand(args).toItemStack()); player.sendMessage(ChatColor.GREEN + "Created Rule Block!"); } catch (ExchangeRuleParseException e) { player.sendMessage(ChatColor.RED + "Incorrect entry format: " + e.getMessage()); } } } else { player.sendMessage(ChatColor.RED + "Player inventory is full!"); } } return true; }
diff --git a/framework/src/com/phonegap/DroidGap.java b/framework/src/com/phonegap/DroidGap.java index 26a04f56..f9065676 100755 --- a/framework/src/com/phonegap/DroidGap.java +++ b/framework/src/com/phonegap/DroidGap.java @@ -1,1848 +1,1852 @@ /* 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 com.phonegap; import java.util.HashMap; import java.util.ArrayList; import java.util.Stack; import java.util.regex.Pattern; import java.util.regex.Matcher; import java.util.Iterator; import java.io.IOException; import org.json.JSONArray; import org.json.JSONException; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Configuration; import android.content.res.XmlResourceParser; import android.graphics.Bitmap; import android.graphics.Color; import android.media.AudioManager; import android.net.Uri; import android.net.http.SslError; import android.os.Bundle; import android.view.Display; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.webkit.ConsoleMessage; import android.webkit.GeolocationPermissions.Callback; import android.webkit.JsPromptResult; import android.webkit.JsResult; import android.webkit.SslErrorHandler; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebSettings.LayoutAlgorithm; import android.webkit.WebStorage; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.EditText; import android.widget.LinearLayout; import com.phonegap.api.LOG; import com.phonegap.api.PhonegapActivity; import com.phonegap.api.IPlugin; import com.phonegap.api.PluginManager; import org.xmlpull.v1.XmlPullParserException; /** * This class is the main Android activity that represents the PhoneGap * application. It should be extended by the user to load the specific * html file that contains the application. * * As an example: * * package com.phonegap.examples; * import android.app.Activity; * import android.os.Bundle; * import com.phonegap.*; * * public class Examples extends DroidGap { * @Override * public void onCreate(Bundle savedInstanceState) { * super.onCreate(savedInstanceState); * * // Set properties for activity * super.setStringProperty("loadingDialog", "Title,Message"); // show loading dialog * super.setStringProperty("errorUrl", "file:///android_asset/www/error.html"); // if error loading file in super.loadUrl(). * * // Initialize activity * super.init(); * * // Clear cache if you want * super.appView.clearCache(true); * * // Load your application * super.setIntegerProperty("splashscreen", R.drawable.splash); // load splash.jpg image from the resource drawable directory * super.loadUrl("file:///android_asset/www/index.html", 3000); // show splash screen 3 sec before loading app * } * } * * Properties: The application can be configured using the following properties: * * // Display a native loading dialog when loading app. Format for value = "Title,Message". * // (String - default=null) * super.setStringProperty("loadingDialog", "Wait,Loading Demo..."); * * // Display a native loading dialog when loading sub-pages. Format for value = "Title,Message". * // (String - default=null) * super.setStringProperty("loadingPageDialog", "Loading page..."); * * // Load a splash screen image from the resource drawable directory. * // (Integer - default=0) * super.setIntegerProperty("splashscreen", R.drawable.splash); * * // Set the background color. * // (Integer - default=0 or BLACK) * super.setIntegerProperty("backgroundColor", Color.WHITE); * * // Time in msec to wait before triggering a timeout error when loading * // with super.loadUrl(). (Integer - default=20000) * super.setIntegerProperty("loadUrlTimeoutValue", 60000); * * // URL to load if there's an error loading specified URL with loadUrl(). * // Should be a local URL starting with file://. (String - default=null) * super.setStringProperty("errorUrl", "file:///android_asset/www/error.html"); * * // Enable app to keep running in background. (Boolean - default=true) * super.setBooleanProperty("keepRunning", false); * * Phonegap.xml configuration: * PhoneGap uses a configuration file at res/xml/phonegap.xml to specify the following settings. * * Approved list of URLs that can be loaded into DroidGap * <access origin="http://server regexp" subdomains="true" /> * Log level: ERROR, WARN, INFO, DEBUG, VERBOSE (default=ERROR) * <log level="DEBUG" /> * * Phonegap plugins: * PhoneGap uses a file at res/xml/plugins.xml to list all plugins that are installed. * Before using a new plugin, a new element must be added to the file. * name attribute is the service name passed to PhoneGap.exec() in JavaScript * value attribute is the Java class name to call. * * <plugins> * <plugin name="App" value="com.phonegap.App"/> * ... * </plugins> */ public class DroidGap extends PhonegapActivity { public static String TAG = "DroidGap"; // The webview for our app protected WebView appView; protected WebViewClient webViewClient; private ArrayList<Pattern> whiteList = new ArrayList<Pattern>(); private HashMap<String, Boolean> whiteListCache = new HashMap<String,Boolean>(); protected LinearLayout root; public boolean bound = false; public CallbackServer callbackServer; protected PluginManager pluginManager; protected boolean cancelLoadUrl = false; protected ProgressDialog spinnerDialog = null; // The initial URL for our app // ie http://server/path/index.html#abc?query private String url = null; private Stack<String> urls = new Stack<String>(); // Url was specified from extras (activity was started programmatically) private String initUrl = null; private static int ACTIVITY_STARTING = 0; private static int ACTIVITY_RUNNING = 1; private static int ACTIVITY_EXITING = 2; private int activityState = 0; // 0=starting, 1=running (after 1st resume), 2=shutting down // The base of the initial URL for our app. // Does not include file name. Ends with / // ie http://server/path/ private String baseUrl = null; // Plugin to call when activity result is received protected IPlugin activityResultCallback = null; protected boolean activityResultKeepRunning; // Flag indicates that a loadUrl timeout occurred private int loadUrlTimeout = 0; // Default background color for activity // (this is not the color for the webview, which is set in HTML) private int backgroundColor = Color.BLACK; /* * The variables below are used to cache some of the activity properties. */ // Draw a splash screen using an image located in the drawable resource directory. // This is not the same as calling super.loadSplashscreen(url) protected int splashscreen = 0; // LoadUrl timeout value in msec (default of 20 sec) protected int loadUrlTimeoutValue = 20000; // Keep app running when pause is received. (default = true) // If true, then the JavaScript and native code continue to run in the background // when another application (activity) is started. protected boolean keepRunning = true; /** * Called when the activity is first created. * * @param savedInstanceState */ @Override public void onCreate(Bundle savedInstanceState) { LOG.d(TAG, "DroidGap.onCreate()"); super.onCreate(savedInstanceState); getWindow().requestFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN, WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); // This builds the view. We could probably get away with NOT having a LinearLayout, but I like having a bucket! Display display = getWindowManager().getDefaultDisplay(); int width = display.getWidth(); int height = display.getHeight(); root = new LinearLayoutSoftKeyboardDetect(this, width, height); root.setOrientation(LinearLayout.VERTICAL); root.setBackgroundColor(this.backgroundColor); root.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT, 0.0F)); // Load PhoneGap configuration: // white list of allowed URLs // debug setting this.loadConfiguration(); // If url was passed in to intent, then init webview, which will load the url Bundle bundle = this.getIntent().getExtras(); if (bundle != null) { String url = bundle.getString("url"); if (url != null) { this.initUrl = url; } } // Setup the hardware volume controls to handle volume control setVolumeControlStream(AudioManager.STREAM_MUSIC); } /** * Create and initialize web container. */ public void init() { LOG.d(TAG, "DroidGap.init()"); // Create web container this.appView = new WebView(DroidGap.this); this.appView.setId(100); this.appView.setLayoutParams(new LinearLayout.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT, 1.0F)); this.appView.setWebChromeClient(new GapClient(DroidGap.this)); this.setWebViewClient(this.appView, new GapViewClient(this)); this.appView.setInitialScale(0); this.appView.setVerticalScrollBarEnabled(false); this.appView.requestFocusFromTouch(); // Enable JavaScript WebSettings settings = this.appView.getSettings(); settings.setJavaScriptEnabled(true); settings.setJavaScriptCanOpenWindowsAutomatically(true); settings.setLayoutAlgorithm(LayoutAlgorithm.NORMAL); //Set the nav dump for HTC settings.setNavDump(true); // Enable database settings.setDatabaseEnabled(true); String databasePath = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath(); settings.setDatabasePath(databasePath); // Enable DOM storage settings.setDomStorageEnabled(true); // Enable built-in geolocation settings.setGeolocationEnabled(true); // Add web view but make it invisible while loading URL this.appView.setVisibility(View.INVISIBLE); root.addView(this.appView); setContentView(root); // Clear cancel flag this.cancelLoadUrl = false; } /** * Set the WebViewClient. * * @param appView * @param client */ protected void setWebViewClient(WebView appView, WebViewClient client) { this.webViewClient = client; appView.setWebViewClient(client); } /** * Look at activity parameters and process them. * This must be called from the main UI thread. */ private void handleActivityParameters() { // If backgroundColor this.backgroundColor = this.getIntegerProperty("backgroundColor", Color.BLACK); this.root.setBackgroundColor(this.backgroundColor); // If spashscreen this.splashscreen = this.getIntegerProperty("splashscreen", 0); if ((this.urls.size() == 0) && (this.splashscreen != 0)) { root.setBackgroundResource(this.splashscreen); } // If loadUrlTimeoutValue int timeout = this.getIntegerProperty("loadUrlTimeoutValue", 0); if (timeout > 0) { this.loadUrlTimeoutValue = timeout; } // If keepRunning this.keepRunning = this.getBooleanProperty("keepRunning", true); } /** * Load the url into the webview. * * @param url */ public void loadUrl(String url) { // If first page of app, then set URL to load to be the one passed in if (this.initUrl == null || (this.urls.size() > 0)) { this.loadUrlIntoView(url); } // Otherwise use the URL specified in the activity's extras bundle else { this.loadUrlIntoView(this.initUrl); } } /** * Load the url into the webview. * * @param url */ private void loadUrlIntoView(final String url) { if (!url.startsWith("javascript:")) { LOG.d(TAG, "DroidGap.loadUrl(%s)", url); } this.url = url; if (this.baseUrl == null) { int i = url.lastIndexOf('/'); if (i > 0) { this.baseUrl = url.substring(0, i+1); } else { this.baseUrl = this.url + "/"; } } if (!url.startsWith("javascript:")) { LOG.d(TAG, "DroidGap: url=%s baseUrl=%s", url, baseUrl); } // Load URL on UI thread final DroidGap me = this; this.runOnUiThread(new Runnable() { public void run() { // Init web view if not already done if (me.appView == null) { me.init(); } // Handle activity parameters me.handleActivityParameters(); // Track URLs loaded instead of using appView history me.urls.push(url); me.appView.clearHistory(); // Create callback server and plugin manager if (me.callbackServer == null) { me.callbackServer = new CallbackServer(); me.callbackServer.init(url); } else { me.callbackServer.reinit(url); } if (me.pluginManager == null) { me.pluginManager = new PluginManager(me.appView, me); } else { me.pluginManager.reinit(); } // If loadingDialog property, then show the App loading dialog for first page of app String loading = null; if (me.urls.size() == 1) { loading = me.getStringProperty("loadingDialog", null); } else { loading = me.getStringProperty("loadingPageDialog", null); } if (loading != null) { String title = ""; String message = "Loading Application..."; if (loading.length() > 0) { int comma = loading.indexOf(','); if (comma > 0) { title = loading.substring(0, comma); message = loading.substring(comma+1); } else { title = ""; message = loading; } } me.spinnerStart(title, message); } // Create a timeout timer for loadUrl final int currentLoadUrlTimeout = me.loadUrlTimeout; Runnable runnable = new Runnable() { public void run() { try { synchronized(this) { wait(me.loadUrlTimeoutValue); } } catch (InterruptedException e) { e.printStackTrace(); } // If timeout, then stop loading and handle error if (me.loadUrlTimeout == currentLoadUrlTimeout) { me.appView.stopLoading(); LOG.e(TAG, "DroidGap: TIMEOUT ERROR! - calling webViewClient"); me.webViewClient.onReceivedError(me.appView, -6, "The connection to the server was unsuccessful.", url); } } }; Thread thread = new Thread(runnable); thread.start(); me.appView.loadUrl(url); } }); } /** * Load the url into the webview after waiting for period of time. * This is used to display the splashscreen for certain amount of time. * * @param url * @param time The number of ms to wait before loading webview */ public void loadUrl(final String url, int time) { // If first page of app, then set URL to load to be the one passed in if (this.initUrl == null || (this.urls.size() > 0)) { this.loadUrlIntoView(url, time); } // Otherwise use the URL specified in the activity's extras bundle else { this.loadUrlIntoView(this.initUrl); } } /** * Load the url into the webview after waiting for period of time. * This is used to display the splashscreen for certain amount of time. * * @param url * @param time The number of ms to wait before loading webview */ private void loadUrlIntoView(final String url, final int time) { // Clear cancel flag this.cancelLoadUrl = false; // If not first page of app, then load immediately if (this.urls.size() > 0) { this.loadUrlIntoView(url); } if (!url.startsWith("javascript:")) { LOG.d(TAG, "DroidGap.loadUrl(%s, %d)", url, time); } final DroidGap me = this; // Handle activity parameters this.runOnUiThread(new Runnable() { public void run() { if (me.appView == null) { me.init(); } me.handleActivityParameters(); } }); Runnable runnable = new Runnable() { public void run() { try { synchronized(this) { this.wait(time); } } catch (InterruptedException e) { e.printStackTrace(); } if (!me.cancelLoadUrl) { me.loadUrlIntoView(url); } else{ me.cancelLoadUrl = false; LOG.d(TAG, "Aborting loadUrl(%s): Another URL was loaded before timer expired.", url); } } }; Thread thread = new Thread(runnable); thread.start(); } /** * Cancel loadUrl before it has been loaded. */ public void cancelLoadUrl() { this.cancelLoadUrl = true; } /** * Clear the resource cache. */ public void clearCache() { if (this.appView == null) { this.init(); } this.appView.clearCache(true); } /** * Clear web history in this web view. */ public void clearHistory() { this.urls.clear(); this.appView.clearHistory(); // Leave current url on history stack if (this.url != null) { this.urls.push(this.url); } } /** * Go to previous page in history. (We manage our own history) * * @return true if we went back, false if we are already at top */ public boolean backHistory() { // Check webview first to see if there is a history // This is needed to support curPage#diffLink, since they are added to appView's history, but not our history url array (JQMobile behavior) if (this.appView.canGoBack()) { this.appView.goBack(); return true; } // If our managed history has prev url if (this.urls.size() > 1) { this.urls.pop(); // Pop current url String url = this.urls.pop(); // Pop prev url that we want to load, since it will be added back by loadUrl() this.loadUrl(url); return true; } return false; } @Override /** * Called by the system when the device configuration changes while your activity is running. * * @param Configuration newConfig */ public void onConfigurationChanged(Configuration newConfig) { //don't reload the current page when the orientation is changed super.onConfigurationChanged(newConfig); } /** * Get boolean property for activity. * * @param name * @param defaultValue * @return */ public boolean getBooleanProperty(String name, boolean defaultValue) { Bundle bundle = this.getIntent().getExtras(); if (bundle == null) { return defaultValue; } Boolean p = (Boolean)bundle.get(name); if (p == null) { return defaultValue; } return p.booleanValue(); } /** * Get int property for activity. * * @param name * @param defaultValue * @return */ public int getIntegerProperty(String name, int defaultValue) { Bundle bundle = this.getIntent().getExtras(); if (bundle == null) { return defaultValue; } Integer p = (Integer)bundle.get(name); if (p == null) { return defaultValue; } return p.intValue(); } /** * Get string property for activity. * * @param name * @param defaultValue * @return */ public String getStringProperty(String name, String defaultValue) { Bundle bundle = this.getIntent().getExtras(); if (bundle == null) { return defaultValue; } String p = bundle.getString(name); if (p == null) { return defaultValue; } return p; } /** * Get double property for activity. * * @param name * @param defaultValue * @return */ public double getDoubleProperty(String name, double defaultValue) { Bundle bundle = this.getIntent().getExtras(); if (bundle == null) { return defaultValue; } Double p = (Double)bundle.get(name); if (p == null) { return defaultValue; } return p.doubleValue(); } /** * Set boolean property on activity. * * @param name * @param value */ public void setBooleanProperty(String name, boolean value) { this.getIntent().putExtra(name, value); } /** * Set int property on activity. * * @param name * @param value */ public void setIntegerProperty(String name, int value) { this.getIntent().putExtra(name, value); } /** * Set string property on activity. * * @param name * @param value */ public void setStringProperty(String name, String value) { this.getIntent().putExtra(name, value); } /** * Set double property on activity. * * @param name * @param value */ public void setDoubleProperty(String name, double value) { this.getIntent().putExtra(name, value); } @Override /** * Called when the system is about to start resuming a previous activity. */ protected void onPause() { super.onPause(); // Don't process pause if shutting down, since onDestroy() will be called if (this.activityState == ACTIVITY_EXITING) { return; } if (this.appView == null) { return; } // Send pause event to JavaScript this.appView.loadUrl("javascript:try{PhoneGap.fireDocumentEvent('pause');}catch(e){};"); // Forward to plugins this.pluginManager.onPause(this.keepRunning); // If app doesn't want to run in background if (!this.keepRunning) { // Pause JavaScript timers (including setInterval) this.appView.pauseTimers(); } } @Override /** * Called when the activity receives a new intent **/ protected void onNewIntent(Intent intent) { super.onNewIntent(intent); //Forward to plugins this.pluginManager.onNewIntent(intent); } @Override /** * Called when the activity will start interacting with the user. */ protected void onResume() { super.onResume(); if (this.activityState == ACTIVITY_STARTING) { this.activityState = ACTIVITY_RUNNING; return; } if (this.appView == null) { return; } // Send resume event to JavaScript this.appView.loadUrl("javascript:try{PhoneGap.fireDocumentEvent('resume');}catch(e){};"); // Forward to plugins this.pluginManager.onResume(this.keepRunning || this.activityResultKeepRunning); // If app doesn't want to run in background if (!this.keepRunning || this.activityResultKeepRunning) { // Restore multitasking state if (this.activityResultKeepRunning) { this.keepRunning = this.activityResultKeepRunning; this.activityResultKeepRunning = false; } // Resume JavaScript timers (including setInterval) this.appView.resumeTimers(); } } @Override /** * The final call you receive before your activity is destroyed. */ public void onDestroy() { super.onDestroy(); if (this.appView != null) { // Send destroy event to JavaScript this.appView.loadUrl("javascript:try{PhoneGap.onDestroy.fire();}catch(e){};"); // Load blank page so that JavaScript onunload is called this.appView.loadUrl("about:blank"); // Forward to plugins this.pluginManager.onDestroy(); } else { this.endActivity(); } } /** * Send a message to all plugins. * * @param id The message id * @param data The message data */ public void postMessage(String id, Object data) { // Forward to plugins this.pluginManager.postMessage(id, data); } /** * @deprecated * Add services to res/xml/plugins.xml instead. * * Add a class that implements a service. * * @param serviceType * @param className */ @Deprecated public void addService(String serviceType, String className) { this.pluginManager.addService(serviceType, className); } /** * Send JavaScript statement back to JavaScript. * (This is a convenience method) * * @param message */ public void sendJavascript(String statement) { this.callbackServer.sendJavascript(statement); } /** * Load the specified URL in the PhoneGap webview or a new browser instance. * * NOTE: If openExternal is false, only URLs listed in whitelist can be loaded. * * @param url The url to load. * @param openExternal Load url in browser instead of PhoneGap webview. * @param clearHistory Clear the history stack, so new page becomes top of history * @param params DroidGap parameters for new app */ public void showWebPage(String url, boolean openExternal, boolean clearHistory, HashMap<String, Object> params) { //throws android.content.ActivityNotFoundException { LOG.d(TAG, "showWebPage(%s, %b, %b, HashMap", url, openExternal, clearHistory); // If clearing history if (clearHistory) { this.clearHistory(); } // If loading into our webview if (!openExternal) { // Make sure url is in whitelist if (url.startsWith("file://") || url.indexOf(this.baseUrl) == 0 || isUrlWhiteListed(url)) { // TODO: What about params? // Clear out current url from history, since it will be replacing it if (clearHistory) { this.urls.clear(); } // Load new URL this.loadUrl(url); } // Load in default viewer if not else { LOG.w(TAG, "showWebPage: Cannot load URL into webview since it is not in white list. Loading into browser instead. (URL="+url+")"); try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); this.startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error loading url "+url, e); } } } // Load in default view intent else { try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); this.startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error loading url "+url, e); } } } /** * Show the spinner. Must be called from the UI thread. * * @param title Title of the dialog * @param message The message of the dialog */ public void spinnerStart(final String title, final String message) { if (this.spinnerDialog != null) { this.spinnerDialog.dismiss(); this.spinnerDialog = null; } final DroidGap me = this; this.spinnerDialog = ProgressDialog.show(DroidGap.this, title , message, true, true, new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { me.spinnerDialog = null; } }); } /** * Stop spinner. */ public void spinnerStop() { if (this.spinnerDialog != null) { this.spinnerDialog.dismiss(); this.spinnerDialog = null; } } /** * Set the chrome handler. */ public class GapClient extends WebChromeClient { private String TAG = "PhoneGapLog"; private long MAX_QUOTA = 100 * 1024 * 1024; private DroidGap ctx; /** * Constructor. * * @param ctx */ public GapClient(Context ctx) { this.ctx = (DroidGap)ctx; } /** * Tell the client to display a javascript alert dialog. * * @param view * @param url * @param message * @param result */ @Override public boolean onJsAlert(WebView view, String url, String message, final JsResult result) { AlertDialog.Builder dlg = new AlertDialog.Builder(this.ctx); dlg.setMessage(message); dlg.setTitle("Alert"); //Don't let alerts break the back button dlg.setCancelable(true); dlg.setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { result.confirm(); } }); dlg.setOnCancelListener( new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { result.confirm(); } }); dlg.setOnKeyListener(new DialogInterface.OnKeyListener() { //DO NOTHING public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK) { result.confirm(); return false; } else return true; } }); dlg.create(); dlg.show(); return true; } /** * Tell the client to display a confirm dialog to the user. * * @param view * @param url * @param message * @param result */ @Override public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) { AlertDialog.Builder dlg = new AlertDialog.Builder(this.ctx); dlg.setMessage(message); dlg.setTitle("Confirm"); dlg.setCancelable(true); dlg.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { result.confirm(); } }); dlg.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { result.cancel(); } }); dlg.setOnCancelListener( new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { result.cancel(); } }); dlg.setOnKeyListener(new DialogInterface.OnKeyListener() { //DO NOTHING public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK) { result.cancel(); return false; } else return true; } }); dlg.create(); dlg.show(); return true; } /** * Tell the client to display a prompt dialog to the user. * If the client returns true, WebView will assume that the client will * handle the prompt dialog and call the appropriate JsPromptResult method. * * Since we are hacking prompts for our own purposes, we should not be using them for * this purpose, perhaps we should hack console.log to do this instead! * * @param view * @param url * @param message * @param defaultValue * @param result */ @Override public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) { // Security check to make sure any requests are coming from the page initially // loaded in webview and not another loaded in an iframe. boolean reqOk = false; if (url.startsWith("file://") || url.indexOf(this.ctx.baseUrl) == 0 || isUrlWhiteListed(url)) { reqOk = true; } // Calling PluginManager.exec() to call a native service using // prompt(this.stringify(args), "gap:"+this.stringify([service, action, callbackId, true])); if (reqOk && defaultValue != null && defaultValue.length() > 3 && defaultValue.substring(0, 4).equals("gap:")) { JSONArray array; try { array = new JSONArray(defaultValue.substring(4)); String service = array.getString(0); String action = array.getString(1); String callbackId = array.getString(2); boolean async = array.getBoolean(3); String r = pluginManager.exec(service, action, callbackId, message, async); result.confirm(r); } catch (JSONException e) { e.printStackTrace(); } } // Polling for JavaScript messages else if (reqOk && defaultValue != null && defaultValue.equals("gap_poll:")) { String r = callbackServer.getJavascript(); result.confirm(r); } // Calling into CallbackServer else if (reqOk && defaultValue != null && defaultValue.equals("gap_callbackServer:")) { String r = ""; if (message.equals("usePolling")) { r = ""+callbackServer.usePolling(); } else if (message.equals("restartServer")) { callbackServer.restartServer(); } else if (message.equals("getPort")) { r = Integer.toString(callbackServer.getPort()); } else if (message.equals("getToken")) { r = callbackServer.getToken(); } result.confirm(r); } // PhoneGap JS has initialized, so show webview // (This solves white flash seen when rendering HTML) else if (reqOk && defaultValue != null && defaultValue.equals("gap_init:")) { appView.setVisibility(View.VISIBLE); ctx.spinnerStop(); result.confirm("OK"); } // Show dialog else { final JsPromptResult res = result; AlertDialog.Builder dlg = new AlertDialog.Builder(this.ctx); dlg.setMessage(message); final EditText input = new EditText(this.ctx); if (defaultValue != null) { input.setText(defaultValue); } dlg.setView(input); dlg.setCancelable(false); dlg.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { String usertext = input.getText().toString(); res.confirm(usertext); } }); dlg.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { res.cancel(); } }); dlg.create(); dlg.show(); } return true; } /** * Handle database quota exceeded notification. * * @param url * @param databaseIdentifier * @param currentQuota * @param estimatedSize * @param totalUsedQuota * @param quotaUpdater */ @Override public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota, long estimatedSize, long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) { LOG.d(TAG, "DroidGap: onExceededDatabaseQuota estimatedSize: %d currentQuota: %d totalUsedQuota: %d", estimatedSize, currentQuota, totalUsedQuota); if( estimatedSize < MAX_QUOTA) { //increase for 1Mb long newQuota = estimatedSize; LOG.d(TAG, "calling quotaUpdater.updateQuota newQuota: %d", newQuota); quotaUpdater.updateQuota(newQuota); } else { // Set the quota to whatever it is and force an error // TODO: get docs on how to handle this properly quotaUpdater.updateQuota(currentQuota); } } // console.log in api level 7: http://developer.android.com/guide/developing/debug-tasks.html @Override public void onConsoleMessage(String message, int lineNumber, String sourceID) { LOG.d(TAG, "%s: Line %d : %s", sourceID, lineNumber, message); super.onConsoleMessage(message, lineNumber, sourceID); } @Override public boolean onConsoleMessage(ConsoleMessage consoleMessage) { LOG.d(TAG, consoleMessage.message()); return super.onConsoleMessage(consoleMessage); } @Override /** * Instructs the client to show a prompt to ask the user to set the Geolocation permission state for the specified origin. * * @param origin * @param callback */ public void onGeolocationPermissionsShowPrompt(String origin, Callback callback) { super.onGeolocationPermissionsShowPrompt(origin, callback); callback.invoke(origin, true, false); } } /** * The webview client receives notifications about appView */ public class GapViewClient extends WebViewClient { DroidGap ctx; /** * Constructor. * * @param ctx */ public GapViewClient(DroidGap ctx) { this.ctx = ctx; } /** * Give the host application a chance to take over the control when a new url * is about to be loaded in the current WebView. * * @param view The WebView that is initiating the callback. * @param url The url to be loaded. * @return true to override, false for default behavior */ @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { // First give any plugins the chance to handle the url themselves if (this.ctx.pluginManager.onOverrideUrlLoading(url)) { } // If dialing phone (tel:5551212) else if (url.startsWith(WebView.SCHEME_TEL)) { try { Intent intent = new Intent(Intent.ACTION_DIAL); intent.setData(Uri.parse(url)); startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error dialing "+url+": "+ e.toString()); } } // If displaying map (geo:0,0?q=address) else if (url.startsWith("geo:")) { try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error showing map "+url+": "+ e.toString()); } } // If sending email (mailto:[email protected]) else if (url.startsWith(WebView.SCHEME_MAILTO)) { try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error sending email "+url+": "+ e.toString()); } } // If sms:5551212?body=This is the message else if (url.startsWith("sms:")) { try { Intent intent = new Intent(Intent.ACTION_VIEW); // Get address String address = null; int parmIndex = url.indexOf('?'); if (parmIndex == -1) { address = url.substring(4); } else { address = url.substring(4, parmIndex); // If body, then set sms body Uri uri = Uri.parse(url); String query = uri.getQuery(); if (query != null) { if (query.startsWith("body=")) { intent.putExtra("sms_body", query.substring(5)); } } } intent.setData(Uri.parse("sms:"+address)); intent.putExtra("address", address); intent.setType("vnd.android-dir/mms-sms"); startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error sending sms "+url+":"+ e.toString()); } } // All else else { // If our app or file:, then load into a new phonegap webview container by starting a new instance of our activity. // Our app continues to run. When BACK is pressed, our app is redisplayed. if (url.startsWith("file://") || url.indexOf(this.ctx.baseUrl) == 0 || isUrlWhiteListed(url)) { this.ctx.loadUrl(url); } // If not our application, let default viewer handle else { try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error loading url "+url, e); } } } return true; } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { // Clear history so history.back() doesn't do anything. // So we can reinit() native side CallbackServer & PluginManager. view.clearHistory(); } /** * Notify the host application that a page has finished loading. * * @param view The webview initiating the callback. * @param url The url of the page. */ @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); // Clear timeout flag this.ctx.loadUrlTimeout++; // Try firing the onNativeReady event in JS. If it fails because the JS is // not loaded yet then just set a flag so that the onNativeReady can be fired // from the JS side when the JS gets to that code. if (!url.equals("about:blank")) { appView.loadUrl("javascript:try{ PhoneGap.onNativeReady.fire();}catch(e){_nativeReady = true;}"); } // Make app visible after 2 sec in case there was a JS error and PhoneGap JS never initialized correctly if (appView.getVisibility() == View.INVISIBLE) { Thread t = new Thread(new Runnable() { public void run() { try { Thread.sleep(2000); ctx.runOnUiThread(new Runnable() { public void run() { appView.setVisibility(View.VISIBLE); ctx.spinnerStop(); } }); } catch (InterruptedException e) { } } }); t.start(); } // Shutdown if blank loaded if (url.equals("about:blank")) { if (this.ctx.callbackServer != null) { this.ctx.callbackServer.destroy(); } this.ctx.endActivity(); } } /** * Report an error to the host application. These errors are unrecoverable (i.e. the main resource is unavailable). * The errorCode parameter corresponds to one of the ERROR_* constants. * * @param view The WebView that is initiating the callback. * @param errorCode The error code corresponding to an ERROR_* value. * @param description A String describing the error. * @param failingUrl The url that failed to load. */ @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { LOG.d(TAG, "DroidGap: GapViewClient.onReceivedError: Error code=%s Description=%s URL=%s", errorCode, description, failingUrl); // Clear timeout flag this.ctx.loadUrlTimeout++; // Stop "app loading" spinner if showing this.ctx.spinnerStop(); // Handle error this.ctx.onReceivedError(errorCode, description, failingUrl); } public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { final String packageName = this.ctx.getPackageName(); final PackageManager pm = this.ctx.getPackageManager(); ApplicationInfo appInfo; try { appInfo = pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA); if ((appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) { // debug = true handler.proceed(); return; } else { // debug = false super.onReceivedSslError(view, handler, error); } } catch (NameNotFoundException e) { // When it doubt, lock it out! super.onReceivedSslError(view, handler, error); } } } /** * End this activity by calling finish for activity */ public void endActivity() { this.activityState = ACTIVITY_EXITING; this.finish(); } /** * Called when a key is pressed. * * @param keyCode * @param event */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (this.appView == null) { return super.onKeyDown(keyCode, event); } // If back key if (keyCode == KeyEvent.KEYCODE_BACK) { // If back key is bound, then send event to JavaScript if (this.bound) { this.appView.loadUrl("javascript:PhoneGap.fireDocumentEvent('backbutton');"); return true; } // If not bound else { // Go to previous page in webview if it is possible to go back if (this.backHistory()) { return true; } // If not, then invoke behavior of super class else { this.activityState = ACTIVITY_EXITING; return super.onKeyDown(keyCode, event); } } } // If menu key else if (keyCode == KeyEvent.KEYCODE_MENU) { this.appView.loadUrl("javascript:PhoneGap.fireDocumentEvent('menubutton');"); return super.onKeyDown(keyCode, event); } // If search key else if (keyCode == KeyEvent.KEYCODE_SEARCH) { this.appView.loadUrl("javascript:PhoneGap.fireDocumentEvent('searchbutton');"); return true; } return false; } /** * Any calls to Activity.startActivityForResult must use method below, so * the result can be routed to them correctly. * * This is done to eliminate the need to modify DroidGap.java to receive activity results. * * @param intent The intent to start * @param requestCode Identifies who to send the result to * * @throws RuntimeException */ @Override public void startActivityForResult(Intent intent, int requestCode) throws RuntimeException { LOG.d(TAG, "DroidGap.startActivityForResult(intent,%d)", requestCode); super.startActivityForResult(intent, requestCode); } /** * Launch an activity for which you would like a result when it finished. When this activity exits, * your onActivityResult() method will be called. * * @param command The command object * @param intent The intent to start * @param requestCode The request code that is passed to callback to identify the activity */ public void startActivityForResult(IPlugin command, Intent intent, int requestCode) { this.activityResultCallback = command; this.activityResultKeepRunning = this.keepRunning; // If multitasking turned on, then disable it for activities that return results if (command != null) { this.keepRunning = false; } // Start activity super.startActivityForResult(intent, requestCode); } @Override /** * Called when an activity you launched exits, giving you the requestCode you started it with, * the resultCode it returned, and any additional data from it. * * @param requestCode The request code originally supplied to startActivityForResult(), * allowing you to identify who this result came from. * @param resultCode The integer result code returned by the child activity through its setResult(). * @param data An Intent, which can return result data to the caller (various data can be attached to Intent "extras"). */ protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); IPlugin callback = this.activityResultCallback; if (callback != null) { callback.onActivityResult(requestCode, resultCode, intent); } } @Override public void setActivityResultCallback(IPlugin plugin) { this.activityResultCallback = plugin; } /** * Report an error to the host application. These errors are unrecoverable (i.e. the main resource is unavailable). * The errorCode parameter corresponds to one of the ERROR_* constants. * * @param errorCode The error code corresponding to an ERROR_* value. * @param description A String describing the error. * @param failingUrl The url that failed to load. */ public void onReceivedError(final int errorCode, final String description, final String failingUrl) { final DroidGap me = this; // If errorUrl specified, then load it final String errorUrl = me.getStringProperty("errorUrl", null); if ((errorUrl != null) && (errorUrl.startsWith("file://") || errorUrl.indexOf(me.baseUrl) == 0 || isUrlWhiteListed(errorUrl)) && (!failingUrl.equals(errorUrl))) { // Load URL on UI thread me.runOnUiThread(new Runnable() { public void run() { me.showWebPage(errorUrl, false, true, null); } }); } // If not, then display error dialog else { me.runOnUiThread(new Runnable() { public void run() { me.appView.setVisibility(View.GONE); me.displayError("Application Error", description + " ("+failingUrl+")", "OK", true); } }); } } /** * Display an error dialog and optionally exit application. * * @param title * @param message * @param button * @param exit */ public void displayError(final String title, final String message, final String button, final boolean exit) { final DroidGap me = this; me.runOnUiThread(new Runnable() { public void run() { AlertDialog.Builder dlg = new AlertDialog.Builder(me); dlg.setMessage(message); dlg.setTitle(title); dlg.setCancelable(false); dlg.setPositiveButton(button, new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if (exit) { me.endActivity(); } } }); dlg.create(); dlg.show(); } }); } /** * We are providing this class to detect when the soft keyboard is shown * and hidden in the web view. */ class LinearLayoutSoftKeyboardDetect extends LinearLayout { private static final String TAG = "SoftKeyboardDetect"; private int oldHeight = 0; // Need to save the old height as not to send redundant events private int oldWidth = 0; // Need to save old width for orientation change private int screenWidth = 0; private int screenHeight = 0; public LinearLayoutSoftKeyboardDetect(Context context, int width, int height) { super(context); screenWidth = width; screenHeight = height; } @Override /** * Start listening to new measurement events. Fire events when the height * gets smaller fire a show keyboard event and when height gets bigger fire * a hide keyboard event. * * Note: We are using callbackServer.sendJavascript() instead of * this.appView.loadUrl() as changing the URL of the app would cause the * soft keyboard to go away. * * @param widthMeasureSpec * @param heightMeasureSpec */ protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); LOG.v(TAG, "We are in our onMeasure method"); // Get the current height of the visible part of the screen. // This height will not included the status bar. int height = MeasureSpec.getSize(heightMeasureSpec); int width = MeasureSpec.getSize(widthMeasureSpec); LOG.v(TAG, "Old Height = %d", oldHeight); LOG.v(TAG, "Height = %d", height); LOG.v(TAG, "Old Width = %d", oldWidth); LOG.v(TAG, "Width = %d", width); // If the oldHeight = 0 then this is the first measure event as the app starts up. // If oldHeight == height then we got a measurement change that doesn't affect us. if (oldHeight == 0 || oldHeight == height) { LOG.d(TAG, "Ignore this event"); } // Account for orientation change and ignore this event/Fire orientation change else if(screenHeight == width) { int tmp_var = screenHeight; screenHeight = screenWidth; screenWidth = tmp_var; LOG.v(TAG, "Orientation Change"); } // If the height as gotten bigger then we will assume the soft keyboard has // gone away. else if (height > oldHeight) { - LOG.v(TAG, "Throw hide keyboard event"); - callbackServer.sendJavascript("PhoneGap.fireDocumentEvent('hidekeyboard');"); + if (callbackServer != null) { + LOG.v(TAG, "Throw hide keyboard event"); + callbackServer.sendJavascript("PhoneGap.fireDocumentEvent('hidekeyboard');"); + } } // If the height as gotten smaller then we will assume the soft keyboard has // been displayed. else if (height < oldHeight) { - LOG.v(TAG, "Throw show keyboard event"); - callbackServer.sendJavascript("PhoneGap.fireDocumentEvent('showkeyboard');"); + if (callbackServer != null) { + LOG.v(TAG, "Throw show keyboard event"); + callbackServer.sendJavascript("PhoneGap.fireDocumentEvent('showkeyboard');"); + } } // Update the old height for the next event oldHeight = height; oldWidth = width; } } /** * Load PhoneGap configuration from res/xml/phonegap.xml. * Approved list of URLs that can be loaded into DroidGap * <access origin="http://server regexp" subdomains="true" /> * Log level: ERROR, WARN, INFO, DEBUG, VERBOSE (default=ERROR) * <log level="DEBUG" /> */ private void loadConfiguration() { int id = getResources().getIdentifier("phonegap", "xml", getPackageName()); if (id == 0) { LOG.i("PhoneGapLog", "phonegap.xml missing. Ignoring..."); return; } XmlResourceParser xml = getResources().getXml(id); int eventType = -1; while (eventType != XmlResourceParser.END_DOCUMENT) { if (eventType == XmlResourceParser.START_TAG) { String strNode = xml.getName(); if (strNode.equals("access")) { String origin = xml.getAttributeValue(null, "origin"); String subdomains = xml.getAttributeValue(null, "subdomains"); if (origin != null) { this.addWhiteListEntry(origin, (subdomains != null) && (subdomains.compareToIgnoreCase("true") == 0)); } } else if (strNode.equals("log")) { String level = xml.getAttributeValue(null, "level"); LOG.i("PhoneGapLog", "Found log level %s", level); if (level != null) { LOG.setLogLevel(level); } } } try { eventType = xml.next(); } catch (XmlPullParserException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } /** * Add entry to approved list of URLs (whitelist) * * @param origin URL regular expression to allow * @param subdomains T=include all subdomains under origin */ private void addWhiteListEntry(String origin, boolean subdomains) { try { // Unlimited access to network resources if(origin.compareTo("*") == 0) { LOG.d(TAG, "Unlimited access to network resources"); whiteList.add(Pattern.compile("*")); } else { // specific access // check if subdomains should be included // TODO: we should not add more domains if * has already been added if (subdomains) { // XXX making it stupid friendly for people who forget to include protocol/SSL if(origin.startsWith("http")) { whiteList.add(Pattern.compile(origin.replaceFirst("https{0,1}://", "^https{0,1}://.*"))); } else { whiteList.add(Pattern.compile("^https{0,1}://.*"+origin)); } LOG.d(TAG, "Origin to allow with subdomains: %s", origin); } else { // XXX making it stupid friendly for people who forget to include protocol/SSL if(origin.startsWith("http")) { whiteList.add(Pattern.compile(origin.replaceFirst("https{0,1}://", "^https{0,1}://"))); } else { whiteList.add(Pattern.compile("^https{0,1}://"+origin)); } LOG.d(TAG, "Origin to allow: %s", origin); } } } catch(Exception e) { LOG.d(TAG, "Failed to add origin %s", origin); } } /** * Determine if URL is in approved list of URLs to load. * * @param url * @return */ private boolean isUrlWhiteListed(String url) { // Check to see if we have matched url previously if (whiteListCache.get(url) != null) { return true; } // Look for match in white list Iterator<Pattern> pit = whiteList.iterator(); while (pit.hasNext()) { Pattern p = pit.next(); Matcher m = p.matcher(url); // If match found, then cache it to speed up subsequent comparisons if (m.find()) { whiteListCache.put(url, true); return true; } } return false; } /* * Hook in DroidGap for menu plugins * */ @Override public boolean onCreateOptionsMenu(Menu menu) { this.postMessage("onCreateOptionsMenu", menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onPrepareOptionsMenu(Menu menu) { this.postMessage("onPrepareOptionsMenu", menu); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { this.postMessage("onOptionsItemSelected", item); return true; } }
false
true
public void showWebPage(String url, boolean openExternal, boolean clearHistory, HashMap<String, Object> params) { //throws android.content.ActivityNotFoundException { LOG.d(TAG, "showWebPage(%s, %b, %b, HashMap", url, openExternal, clearHistory); // If clearing history if (clearHistory) { this.clearHistory(); } // If loading into our webview if (!openExternal) { // Make sure url is in whitelist if (url.startsWith("file://") || url.indexOf(this.baseUrl) == 0 || isUrlWhiteListed(url)) { // TODO: What about params? // Clear out current url from history, since it will be replacing it if (clearHistory) { this.urls.clear(); } // Load new URL this.loadUrl(url); } // Load in default viewer if not else { LOG.w(TAG, "showWebPage: Cannot load URL into webview since it is not in white list. Loading into browser instead. (URL="+url+")"); try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); this.startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error loading url "+url, e); } } } // Load in default view intent else { try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); this.startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error loading url "+url, e); } } } /** * Show the spinner. Must be called from the UI thread. * * @param title Title of the dialog * @param message The message of the dialog */ public void spinnerStart(final String title, final String message) { if (this.spinnerDialog != null) { this.spinnerDialog.dismiss(); this.spinnerDialog = null; } final DroidGap me = this; this.spinnerDialog = ProgressDialog.show(DroidGap.this, title , message, true, true, new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { me.spinnerDialog = null; } }); } /** * Stop spinner. */ public void spinnerStop() { if (this.spinnerDialog != null) { this.spinnerDialog.dismiss(); this.spinnerDialog = null; } } /** * Set the chrome handler. */ public class GapClient extends WebChromeClient { private String TAG = "PhoneGapLog"; private long MAX_QUOTA = 100 * 1024 * 1024; private DroidGap ctx; /** * Constructor. * * @param ctx */ public GapClient(Context ctx) { this.ctx = (DroidGap)ctx; } /** * Tell the client to display a javascript alert dialog. * * @param view * @param url * @param message * @param result */ @Override public boolean onJsAlert(WebView view, String url, String message, final JsResult result) { AlertDialog.Builder dlg = new AlertDialog.Builder(this.ctx); dlg.setMessage(message); dlg.setTitle("Alert"); //Don't let alerts break the back button dlg.setCancelable(true); dlg.setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { result.confirm(); } }); dlg.setOnCancelListener( new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { result.confirm(); } }); dlg.setOnKeyListener(new DialogInterface.OnKeyListener() { //DO NOTHING public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK) { result.confirm(); return false; } else return true; } }); dlg.create(); dlg.show(); return true; } /** * Tell the client to display a confirm dialog to the user. * * @param view * @param url * @param message * @param result */ @Override public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) { AlertDialog.Builder dlg = new AlertDialog.Builder(this.ctx); dlg.setMessage(message); dlg.setTitle("Confirm"); dlg.setCancelable(true); dlg.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { result.confirm(); } }); dlg.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { result.cancel(); } }); dlg.setOnCancelListener( new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { result.cancel(); } }); dlg.setOnKeyListener(new DialogInterface.OnKeyListener() { //DO NOTHING public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK) { result.cancel(); return false; } else return true; } }); dlg.create(); dlg.show(); return true; } /** * Tell the client to display a prompt dialog to the user. * If the client returns true, WebView will assume that the client will * handle the prompt dialog and call the appropriate JsPromptResult method. * * Since we are hacking prompts for our own purposes, we should not be using them for * this purpose, perhaps we should hack console.log to do this instead! * * @param view * @param url * @param message * @param defaultValue * @param result */ @Override public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) { // Security check to make sure any requests are coming from the page initially // loaded in webview and not another loaded in an iframe. boolean reqOk = false; if (url.startsWith("file://") || url.indexOf(this.ctx.baseUrl) == 0 || isUrlWhiteListed(url)) { reqOk = true; } // Calling PluginManager.exec() to call a native service using // prompt(this.stringify(args), "gap:"+this.stringify([service, action, callbackId, true])); if (reqOk && defaultValue != null && defaultValue.length() > 3 && defaultValue.substring(0, 4).equals("gap:")) { JSONArray array; try { array = new JSONArray(defaultValue.substring(4)); String service = array.getString(0); String action = array.getString(1); String callbackId = array.getString(2); boolean async = array.getBoolean(3); String r = pluginManager.exec(service, action, callbackId, message, async); result.confirm(r); } catch (JSONException e) { e.printStackTrace(); } } // Polling for JavaScript messages else if (reqOk && defaultValue != null && defaultValue.equals("gap_poll:")) { String r = callbackServer.getJavascript(); result.confirm(r); } // Calling into CallbackServer else if (reqOk && defaultValue != null && defaultValue.equals("gap_callbackServer:")) { String r = ""; if (message.equals("usePolling")) { r = ""+callbackServer.usePolling(); } else if (message.equals("restartServer")) { callbackServer.restartServer(); } else if (message.equals("getPort")) { r = Integer.toString(callbackServer.getPort()); } else if (message.equals("getToken")) { r = callbackServer.getToken(); } result.confirm(r); } // PhoneGap JS has initialized, so show webview // (This solves white flash seen when rendering HTML) else if (reqOk && defaultValue != null && defaultValue.equals("gap_init:")) { appView.setVisibility(View.VISIBLE); ctx.spinnerStop(); result.confirm("OK"); } // Show dialog else { final JsPromptResult res = result; AlertDialog.Builder dlg = new AlertDialog.Builder(this.ctx); dlg.setMessage(message); final EditText input = new EditText(this.ctx); if (defaultValue != null) { input.setText(defaultValue); } dlg.setView(input); dlg.setCancelable(false); dlg.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { String usertext = input.getText().toString(); res.confirm(usertext); } }); dlg.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { res.cancel(); } }); dlg.create(); dlg.show(); } return true; } /** * Handle database quota exceeded notification. * * @param url * @param databaseIdentifier * @param currentQuota * @param estimatedSize * @param totalUsedQuota * @param quotaUpdater */ @Override public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota, long estimatedSize, long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) { LOG.d(TAG, "DroidGap: onExceededDatabaseQuota estimatedSize: %d currentQuota: %d totalUsedQuota: %d", estimatedSize, currentQuota, totalUsedQuota); if( estimatedSize < MAX_QUOTA) { //increase for 1Mb long newQuota = estimatedSize; LOG.d(TAG, "calling quotaUpdater.updateQuota newQuota: %d", newQuota); quotaUpdater.updateQuota(newQuota); } else { // Set the quota to whatever it is and force an error // TODO: get docs on how to handle this properly quotaUpdater.updateQuota(currentQuota); } } // console.log in api level 7: http://developer.android.com/guide/developing/debug-tasks.html @Override public void onConsoleMessage(String message, int lineNumber, String sourceID) { LOG.d(TAG, "%s: Line %d : %s", sourceID, lineNumber, message); super.onConsoleMessage(message, lineNumber, sourceID); } @Override public boolean onConsoleMessage(ConsoleMessage consoleMessage) { LOG.d(TAG, consoleMessage.message()); return super.onConsoleMessage(consoleMessage); } @Override /** * Instructs the client to show a prompt to ask the user to set the Geolocation permission state for the specified origin. * * @param origin * @param callback */ public void onGeolocationPermissionsShowPrompt(String origin, Callback callback) { super.onGeolocationPermissionsShowPrompt(origin, callback); callback.invoke(origin, true, false); } } /** * The webview client receives notifications about appView */ public class GapViewClient extends WebViewClient { DroidGap ctx; /** * Constructor. * * @param ctx */ public GapViewClient(DroidGap ctx) { this.ctx = ctx; } /** * Give the host application a chance to take over the control when a new url * is about to be loaded in the current WebView. * * @param view The WebView that is initiating the callback. * @param url The url to be loaded. * @return true to override, false for default behavior */ @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { // First give any plugins the chance to handle the url themselves if (this.ctx.pluginManager.onOverrideUrlLoading(url)) { } // If dialing phone (tel:5551212) else if (url.startsWith(WebView.SCHEME_TEL)) { try { Intent intent = new Intent(Intent.ACTION_DIAL); intent.setData(Uri.parse(url)); startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error dialing "+url+": "+ e.toString()); } } // If displaying map (geo:0,0?q=address) else if (url.startsWith("geo:")) { try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error showing map "+url+": "+ e.toString()); } } // If sending email (mailto:[email protected]) else if (url.startsWith(WebView.SCHEME_MAILTO)) { try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error sending email "+url+": "+ e.toString()); } } // If sms:5551212?body=This is the message else if (url.startsWith("sms:")) { try { Intent intent = new Intent(Intent.ACTION_VIEW); // Get address String address = null; int parmIndex = url.indexOf('?'); if (parmIndex == -1) { address = url.substring(4); } else { address = url.substring(4, parmIndex); // If body, then set sms body Uri uri = Uri.parse(url); String query = uri.getQuery(); if (query != null) { if (query.startsWith("body=")) { intent.putExtra("sms_body", query.substring(5)); } } } intent.setData(Uri.parse("sms:"+address)); intent.putExtra("address", address); intent.setType("vnd.android-dir/mms-sms"); startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error sending sms "+url+":"+ e.toString()); } } // All else else { // If our app or file:, then load into a new phonegap webview container by starting a new instance of our activity. // Our app continues to run. When BACK is pressed, our app is redisplayed. if (url.startsWith("file://") || url.indexOf(this.ctx.baseUrl) == 0 || isUrlWhiteListed(url)) { this.ctx.loadUrl(url); } // If not our application, let default viewer handle else { try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error loading url "+url, e); } } } return true; } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { // Clear history so history.back() doesn't do anything. // So we can reinit() native side CallbackServer & PluginManager. view.clearHistory(); } /** * Notify the host application that a page has finished loading. * * @param view The webview initiating the callback. * @param url The url of the page. */ @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); // Clear timeout flag this.ctx.loadUrlTimeout++; // Try firing the onNativeReady event in JS. If it fails because the JS is // not loaded yet then just set a flag so that the onNativeReady can be fired // from the JS side when the JS gets to that code. if (!url.equals("about:blank")) { appView.loadUrl("javascript:try{ PhoneGap.onNativeReady.fire();}catch(e){_nativeReady = true;}"); } // Make app visible after 2 sec in case there was a JS error and PhoneGap JS never initialized correctly if (appView.getVisibility() == View.INVISIBLE) { Thread t = new Thread(new Runnable() { public void run() { try { Thread.sleep(2000); ctx.runOnUiThread(new Runnable() { public void run() { appView.setVisibility(View.VISIBLE); ctx.spinnerStop(); } }); } catch (InterruptedException e) { } } }); t.start(); } // Shutdown if blank loaded if (url.equals("about:blank")) { if (this.ctx.callbackServer != null) { this.ctx.callbackServer.destroy(); } this.ctx.endActivity(); } } /** * Report an error to the host application. These errors are unrecoverable (i.e. the main resource is unavailable). * The errorCode parameter corresponds to one of the ERROR_* constants. * * @param view The WebView that is initiating the callback. * @param errorCode The error code corresponding to an ERROR_* value. * @param description A String describing the error. * @param failingUrl The url that failed to load. */ @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { LOG.d(TAG, "DroidGap: GapViewClient.onReceivedError: Error code=%s Description=%s URL=%s", errorCode, description, failingUrl); // Clear timeout flag this.ctx.loadUrlTimeout++; // Stop "app loading" spinner if showing this.ctx.spinnerStop(); // Handle error this.ctx.onReceivedError(errorCode, description, failingUrl); } public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { final String packageName = this.ctx.getPackageName(); final PackageManager pm = this.ctx.getPackageManager(); ApplicationInfo appInfo; try { appInfo = pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA); if ((appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) { // debug = true handler.proceed(); return; } else { // debug = false super.onReceivedSslError(view, handler, error); } } catch (NameNotFoundException e) { // When it doubt, lock it out! super.onReceivedSslError(view, handler, error); } } } /** * End this activity by calling finish for activity */ public void endActivity() { this.activityState = ACTIVITY_EXITING; this.finish(); } /** * Called when a key is pressed. * * @param keyCode * @param event */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (this.appView == null) { return super.onKeyDown(keyCode, event); } // If back key if (keyCode == KeyEvent.KEYCODE_BACK) { // If back key is bound, then send event to JavaScript if (this.bound) { this.appView.loadUrl("javascript:PhoneGap.fireDocumentEvent('backbutton');"); return true; } // If not bound else { // Go to previous page in webview if it is possible to go back if (this.backHistory()) { return true; } // If not, then invoke behavior of super class else { this.activityState = ACTIVITY_EXITING; return super.onKeyDown(keyCode, event); } } } // If menu key else if (keyCode == KeyEvent.KEYCODE_MENU) { this.appView.loadUrl("javascript:PhoneGap.fireDocumentEvent('menubutton');"); return super.onKeyDown(keyCode, event); } // If search key else if (keyCode == KeyEvent.KEYCODE_SEARCH) { this.appView.loadUrl("javascript:PhoneGap.fireDocumentEvent('searchbutton');"); return true; } return false; } /** * Any calls to Activity.startActivityForResult must use method below, so * the result can be routed to them correctly. * * This is done to eliminate the need to modify DroidGap.java to receive activity results. * * @param intent The intent to start * @param requestCode Identifies who to send the result to * * @throws RuntimeException */ @Override public void startActivityForResult(Intent intent, int requestCode) throws RuntimeException { LOG.d(TAG, "DroidGap.startActivityForResult(intent,%d)", requestCode); super.startActivityForResult(intent, requestCode); } /** * Launch an activity for which you would like a result when it finished. When this activity exits, * your onActivityResult() method will be called. * * @param command The command object * @param intent The intent to start * @param requestCode The request code that is passed to callback to identify the activity */ public void startActivityForResult(IPlugin command, Intent intent, int requestCode) { this.activityResultCallback = command; this.activityResultKeepRunning = this.keepRunning; // If multitasking turned on, then disable it for activities that return results if (command != null) { this.keepRunning = false; } // Start activity super.startActivityForResult(intent, requestCode); } @Override /** * Called when an activity you launched exits, giving you the requestCode you started it with, * the resultCode it returned, and any additional data from it. * * @param requestCode The request code originally supplied to startActivityForResult(), * allowing you to identify who this result came from. * @param resultCode The integer result code returned by the child activity through its setResult(). * @param data An Intent, which can return result data to the caller (various data can be attached to Intent "extras"). */ protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); IPlugin callback = this.activityResultCallback; if (callback != null) { callback.onActivityResult(requestCode, resultCode, intent); } } @Override public void setActivityResultCallback(IPlugin plugin) { this.activityResultCallback = plugin; } /** * Report an error to the host application. These errors are unrecoverable (i.e. the main resource is unavailable). * The errorCode parameter corresponds to one of the ERROR_* constants. * * @param errorCode The error code corresponding to an ERROR_* value. * @param description A String describing the error. * @param failingUrl The url that failed to load. */ public void onReceivedError(final int errorCode, final String description, final String failingUrl) { final DroidGap me = this; // If errorUrl specified, then load it final String errorUrl = me.getStringProperty("errorUrl", null); if ((errorUrl != null) && (errorUrl.startsWith("file://") || errorUrl.indexOf(me.baseUrl) == 0 || isUrlWhiteListed(errorUrl)) && (!failingUrl.equals(errorUrl))) { // Load URL on UI thread me.runOnUiThread(new Runnable() { public void run() { me.showWebPage(errorUrl, false, true, null); } }); } // If not, then display error dialog else { me.runOnUiThread(new Runnable() { public void run() { me.appView.setVisibility(View.GONE); me.displayError("Application Error", description + " ("+failingUrl+")", "OK", true); } }); } } /** * Display an error dialog and optionally exit application. * * @param title * @param message * @param button * @param exit */ public void displayError(final String title, final String message, final String button, final boolean exit) { final DroidGap me = this; me.runOnUiThread(new Runnable() { public void run() { AlertDialog.Builder dlg = new AlertDialog.Builder(me); dlg.setMessage(message); dlg.setTitle(title); dlg.setCancelable(false); dlg.setPositiveButton(button, new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if (exit) { me.endActivity(); } } }); dlg.create(); dlg.show(); } }); } /** * We are providing this class to detect when the soft keyboard is shown * and hidden in the web view. */ class LinearLayoutSoftKeyboardDetect extends LinearLayout { private static final String TAG = "SoftKeyboardDetect"; private int oldHeight = 0; // Need to save the old height as not to send redundant events private int oldWidth = 0; // Need to save old width for orientation change private int screenWidth = 0; private int screenHeight = 0; public LinearLayoutSoftKeyboardDetect(Context context, int width, int height) { super(context); screenWidth = width; screenHeight = height; } @Override /** * Start listening to new measurement events. Fire events when the height * gets smaller fire a show keyboard event and when height gets bigger fire * a hide keyboard event. * * Note: We are using callbackServer.sendJavascript() instead of * this.appView.loadUrl() as changing the URL of the app would cause the * soft keyboard to go away. * * @param widthMeasureSpec * @param heightMeasureSpec */ protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); LOG.v(TAG, "We are in our onMeasure method"); // Get the current height of the visible part of the screen. // This height will not included the status bar. int height = MeasureSpec.getSize(heightMeasureSpec); int width = MeasureSpec.getSize(widthMeasureSpec); LOG.v(TAG, "Old Height = %d", oldHeight); LOG.v(TAG, "Height = %d", height); LOG.v(TAG, "Old Width = %d", oldWidth); LOG.v(TAG, "Width = %d", width); // If the oldHeight = 0 then this is the first measure event as the app starts up. // If oldHeight == height then we got a measurement change that doesn't affect us. if (oldHeight == 0 || oldHeight == height) { LOG.d(TAG, "Ignore this event"); } // Account for orientation change and ignore this event/Fire orientation change else if(screenHeight == width) { int tmp_var = screenHeight; screenHeight = screenWidth; screenWidth = tmp_var; LOG.v(TAG, "Orientation Change"); } // If the height as gotten bigger then we will assume the soft keyboard has // gone away. else if (height > oldHeight) { LOG.v(TAG, "Throw hide keyboard event"); callbackServer.sendJavascript("PhoneGap.fireDocumentEvent('hidekeyboard');"); } // If the height as gotten smaller then we will assume the soft keyboard has // been displayed. else if (height < oldHeight) { LOG.v(TAG, "Throw show keyboard event"); callbackServer.sendJavascript("PhoneGap.fireDocumentEvent('showkeyboard');"); } // Update the old height for the next event oldHeight = height; oldWidth = width; } } /** * Load PhoneGap configuration from res/xml/phonegap.xml. * Approved list of URLs that can be loaded into DroidGap * <access origin="http://server regexp" subdomains="true" /> * Log level: ERROR, WARN, INFO, DEBUG, VERBOSE (default=ERROR) * <log level="DEBUG" /> */ private void loadConfiguration() { int id = getResources().getIdentifier("phonegap", "xml", getPackageName()); if (id == 0) { LOG.i("PhoneGapLog", "phonegap.xml missing. Ignoring..."); return; } XmlResourceParser xml = getResources().getXml(id); int eventType = -1; while (eventType != XmlResourceParser.END_DOCUMENT) { if (eventType == XmlResourceParser.START_TAG) { String strNode = xml.getName(); if (strNode.equals("access")) { String origin = xml.getAttributeValue(null, "origin"); String subdomains = xml.getAttributeValue(null, "subdomains"); if (origin != null) { this.addWhiteListEntry(origin, (subdomains != null) && (subdomains.compareToIgnoreCase("true") == 0)); } } else if (strNode.equals("log")) { String level = xml.getAttributeValue(null, "level"); LOG.i("PhoneGapLog", "Found log level %s", level); if (level != null) { LOG.setLogLevel(level); } } } try { eventType = xml.next(); } catch (XmlPullParserException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } /** * Add entry to approved list of URLs (whitelist) * * @param origin URL regular expression to allow * @param subdomains T=include all subdomains under origin */ private void addWhiteListEntry(String origin, boolean subdomains) { try { // Unlimited access to network resources if(origin.compareTo("*") == 0) { LOG.d(TAG, "Unlimited access to network resources"); whiteList.add(Pattern.compile("*")); } else { // specific access // check if subdomains should be included // TODO: we should not add more domains if * has already been added if (subdomains) { // XXX making it stupid friendly for people who forget to include protocol/SSL if(origin.startsWith("http")) { whiteList.add(Pattern.compile(origin.replaceFirst("https{0,1}://", "^https{0,1}://.*"))); } else { whiteList.add(Pattern.compile("^https{0,1}://.*"+origin)); } LOG.d(TAG, "Origin to allow with subdomains: %s", origin); } else { // XXX making it stupid friendly for people who forget to include protocol/SSL if(origin.startsWith("http")) { whiteList.add(Pattern.compile(origin.replaceFirst("https{0,1}://", "^https{0,1}://"))); } else { whiteList.add(Pattern.compile("^https{0,1}://"+origin)); } LOG.d(TAG, "Origin to allow: %s", origin); } } } catch(Exception e) { LOG.d(TAG, "Failed to add origin %s", origin); } } /** * Determine if URL is in approved list of URLs to load. * * @param url * @return */ private boolean isUrlWhiteListed(String url) { // Check to see if we have matched url previously if (whiteListCache.get(url) != null) { return true; } // Look for match in white list Iterator<Pattern> pit = whiteList.iterator(); while (pit.hasNext()) { Pattern p = pit.next(); Matcher m = p.matcher(url); // If match found, then cache it to speed up subsequent comparisons if (m.find()) { whiteListCache.put(url, true); return true; } } return false; } /* * Hook in DroidGap for menu plugins * */ @Override public boolean onCreateOptionsMenu(Menu menu) { this.postMessage("onCreateOptionsMenu", menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onPrepareOptionsMenu(Menu menu) { this.postMessage("onPrepareOptionsMenu", menu); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { this.postMessage("onOptionsItemSelected", item); return true; } }
public void showWebPage(String url, boolean openExternal, boolean clearHistory, HashMap<String, Object> params) { //throws android.content.ActivityNotFoundException { LOG.d(TAG, "showWebPage(%s, %b, %b, HashMap", url, openExternal, clearHistory); // If clearing history if (clearHistory) { this.clearHistory(); } // If loading into our webview if (!openExternal) { // Make sure url is in whitelist if (url.startsWith("file://") || url.indexOf(this.baseUrl) == 0 || isUrlWhiteListed(url)) { // TODO: What about params? // Clear out current url from history, since it will be replacing it if (clearHistory) { this.urls.clear(); } // Load new URL this.loadUrl(url); } // Load in default viewer if not else { LOG.w(TAG, "showWebPage: Cannot load URL into webview since it is not in white list. Loading into browser instead. (URL="+url+")"); try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); this.startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error loading url "+url, e); } } } // Load in default view intent else { try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); this.startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error loading url "+url, e); } } } /** * Show the spinner. Must be called from the UI thread. * * @param title Title of the dialog * @param message The message of the dialog */ public void spinnerStart(final String title, final String message) { if (this.spinnerDialog != null) { this.spinnerDialog.dismiss(); this.spinnerDialog = null; } final DroidGap me = this; this.spinnerDialog = ProgressDialog.show(DroidGap.this, title , message, true, true, new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { me.spinnerDialog = null; } }); } /** * Stop spinner. */ public void spinnerStop() { if (this.spinnerDialog != null) { this.spinnerDialog.dismiss(); this.spinnerDialog = null; } } /** * Set the chrome handler. */ public class GapClient extends WebChromeClient { private String TAG = "PhoneGapLog"; private long MAX_QUOTA = 100 * 1024 * 1024; private DroidGap ctx; /** * Constructor. * * @param ctx */ public GapClient(Context ctx) { this.ctx = (DroidGap)ctx; } /** * Tell the client to display a javascript alert dialog. * * @param view * @param url * @param message * @param result */ @Override public boolean onJsAlert(WebView view, String url, String message, final JsResult result) { AlertDialog.Builder dlg = new AlertDialog.Builder(this.ctx); dlg.setMessage(message); dlg.setTitle("Alert"); //Don't let alerts break the back button dlg.setCancelable(true); dlg.setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { result.confirm(); } }); dlg.setOnCancelListener( new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { result.confirm(); } }); dlg.setOnKeyListener(new DialogInterface.OnKeyListener() { //DO NOTHING public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK) { result.confirm(); return false; } else return true; } }); dlg.create(); dlg.show(); return true; } /** * Tell the client to display a confirm dialog to the user. * * @param view * @param url * @param message * @param result */ @Override public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) { AlertDialog.Builder dlg = new AlertDialog.Builder(this.ctx); dlg.setMessage(message); dlg.setTitle("Confirm"); dlg.setCancelable(true); dlg.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { result.confirm(); } }); dlg.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { result.cancel(); } }); dlg.setOnCancelListener( new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { result.cancel(); } }); dlg.setOnKeyListener(new DialogInterface.OnKeyListener() { //DO NOTHING public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK) { result.cancel(); return false; } else return true; } }); dlg.create(); dlg.show(); return true; } /** * Tell the client to display a prompt dialog to the user. * If the client returns true, WebView will assume that the client will * handle the prompt dialog and call the appropriate JsPromptResult method. * * Since we are hacking prompts for our own purposes, we should not be using them for * this purpose, perhaps we should hack console.log to do this instead! * * @param view * @param url * @param message * @param defaultValue * @param result */ @Override public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) { // Security check to make sure any requests are coming from the page initially // loaded in webview and not another loaded in an iframe. boolean reqOk = false; if (url.startsWith("file://") || url.indexOf(this.ctx.baseUrl) == 0 || isUrlWhiteListed(url)) { reqOk = true; } // Calling PluginManager.exec() to call a native service using // prompt(this.stringify(args), "gap:"+this.stringify([service, action, callbackId, true])); if (reqOk && defaultValue != null && defaultValue.length() > 3 && defaultValue.substring(0, 4).equals("gap:")) { JSONArray array; try { array = new JSONArray(defaultValue.substring(4)); String service = array.getString(0); String action = array.getString(1); String callbackId = array.getString(2); boolean async = array.getBoolean(3); String r = pluginManager.exec(service, action, callbackId, message, async); result.confirm(r); } catch (JSONException e) { e.printStackTrace(); } } // Polling for JavaScript messages else if (reqOk && defaultValue != null && defaultValue.equals("gap_poll:")) { String r = callbackServer.getJavascript(); result.confirm(r); } // Calling into CallbackServer else if (reqOk && defaultValue != null && defaultValue.equals("gap_callbackServer:")) { String r = ""; if (message.equals("usePolling")) { r = ""+callbackServer.usePolling(); } else if (message.equals("restartServer")) { callbackServer.restartServer(); } else if (message.equals("getPort")) { r = Integer.toString(callbackServer.getPort()); } else if (message.equals("getToken")) { r = callbackServer.getToken(); } result.confirm(r); } // PhoneGap JS has initialized, so show webview // (This solves white flash seen when rendering HTML) else if (reqOk && defaultValue != null && defaultValue.equals("gap_init:")) { appView.setVisibility(View.VISIBLE); ctx.spinnerStop(); result.confirm("OK"); } // Show dialog else { final JsPromptResult res = result; AlertDialog.Builder dlg = new AlertDialog.Builder(this.ctx); dlg.setMessage(message); final EditText input = new EditText(this.ctx); if (defaultValue != null) { input.setText(defaultValue); } dlg.setView(input); dlg.setCancelable(false); dlg.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { String usertext = input.getText().toString(); res.confirm(usertext); } }); dlg.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { res.cancel(); } }); dlg.create(); dlg.show(); } return true; } /** * Handle database quota exceeded notification. * * @param url * @param databaseIdentifier * @param currentQuota * @param estimatedSize * @param totalUsedQuota * @param quotaUpdater */ @Override public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota, long estimatedSize, long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) { LOG.d(TAG, "DroidGap: onExceededDatabaseQuota estimatedSize: %d currentQuota: %d totalUsedQuota: %d", estimatedSize, currentQuota, totalUsedQuota); if( estimatedSize < MAX_QUOTA) { //increase for 1Mb long newQuota = estimatedSize; LOG.d(TAG, "calling quotaUpdater.updateQuota newQuota: %d", newQuota); quotaUpdater.updateQuota(newQuota); } else { // Set the quota to whatever it is and force an error // TODO: get docs on how to handle this properly quotaUpdater.updateQuota(currentQuota); } } // console.log in api level 7: http://developer.android.com/guide/developing/debug-tasks.html @Override public void onConsoleMessage(String message, int lineNumber, String sourceID) { LOG.d(TAG, "%s: Line %d : %s", sourceID, lineNumber, message); super.onConsoleMessage(message, lineNumber, sourceID); } @Override public boolean onConsoleMessage(ConsoleMessage consoleMessage) { LOG.d(TAG, consoleMessage.message()); return super.onConsoleMessage(consoleMessage); } @Override /** * Instructs the client to show a prompt to ask the user to set the Geolocation permission state for the specified origin. * * @param origin * @param callback */ public void onGeolocationPermissionsShowPrompt(String origin, Callback callback) { super.onGeolocationPermissionsShowPrompt(origin, callback); callback.invoke(origin, true, false); } } /** * The webview client receives notifications about appView */ public class GapViewClient extends WebViewClient { DroidGap ctx; /** * Constructor. * * @param ctx */ public GapViewClient(DroidGap ctx) { this.ctx = ctx; } /** * Give the host application a chance to take over the control when a new url * is about to be loaded in the current WebView. * * @param view The WebView that is initiating the callback. * @param url The url to be loaded. * @return true to override, false for default behavior */ @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { // First give any plugins the chance to handle the url themselves if (this.ctx.pluginManager.onOverrideUrlLoading(url)) { } // If dialing phone (tel:5551212) else if (url.startsWith(WebView.SCHEME_TEL)) { try { Intent intent = new Intent(Intent.ACTION_DIAL); intent.setData(Uri.parse(url)); startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error dialing "+url+": "+ e.toString()); } } // If displaying map (geo:0,0?q=address) else if (url.startsWith("geo:")) { try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error showing map "+url+": "+ e.toString()); } } // If sending email (mailto:[email protected]) else if (url.startsWith(WebView.SCHEME_MAILTO)) { try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error sending email "+url+": "+ e.toString()); } } // If sms:5551212?body=This is the message else if (url.startsWith("sms:")) { try { Intent intent = new Intent(Intent.ACTION_VIEW); // Get address String address = null; int parmIndex = url.indexOf('?'); if (parmIndex == -1) { address = url.substring(4); } else { address = url.substring(4, parmIndex); // If body, then set sms body Uri uri = Uri.parse(url); String query = uri.getQuery(); if (query != null) { if (query.startsWith("body=")) { intent.putExtra("sms_body", query.substring(5)); } } } intent.setData(Uri.parse("sms:"+address)); intent.putExtra("address", address); intent.setType("vnd.android-dir/mms-sms"); startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error sending sms "+url+":"+ e.toString()); } } // All else else { // If our app or file:, then load into a new phonegap webview container by starting a new instance of our activity. // Our app continues to run. When BACK is pressed, our app is redisplayed. if (url.startsWith("file://") || url.indexOf(this.ctx.baseUrl) == 0 || isUrlWhiteListed(url)) { this.ctx.loadUrl(url); } // If not our application, let default viewer handle else { try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error loading url "+url, e); } } } return true; } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { // Clear history so history.back() doesn't do anything. // So we can reinit() native side CallbackServer & PluginManager. view.clearHistory(); } /** * Notify the host application that a page has finished loading. * * @param view The webview initiating the callback. * @param url The url of the page. */ @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); // Clear timeout flag this.ctx.loadUrlTimeout++; // Try firing the onNativeReady event in JS. If it fails because the JS is // not loaded yet then just set a flag so that the onNativeReady can be fired // from the JS side when the JS gets to that code. if (!url.equals("about:blank")) { appView.loadUrl("javascript:try{ PhoneGap.onNativeReady.fire();}catch(e){_nativeReady = true;}"); } // Make app visible after 2 sec in case there was a JS error and PhoneGap JS never initialized correctly if (appView.getVisibility() == View.INVISIBLE) { Thread t = new Thread(new Runnable() { public void run() { try { Thread.sleep(2000); ctx.runOnUiThread(new Runnable() { public void run() { appView.setVisibility(View.VISIBLE); ctx.spinnerStop(); } }); } catch (InterruptedException e) { } } }); t.start(); } // Shutdown if blank loaded if (url.equals("about:blank")) { if (this.ctx.callbackServer != null) { this.ctx.callbackServer.destroy(); } this.ctx.endActivity(); } } /** * Report an error to the host application. These errors are unrecoverable (i.e. the main resource is unavailable). * The errorCode parameter corresponds to one of the ERROR_* constants. * * @param view The WebView that is initiating the callback. * @param errorCode The error code corresponding to an ERROR_* value. * @param description A String describing the error. * @param failingUrl The url that failed to load. */ @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { LOG.d(TAG, "DroidGap: GapViewClient.onReceivedError: Error code=%s Description=%s URL=%s", errorCode, description, failingUrl); // Clear timeout flag this.ctx.loadUrlTimeout++; // Stop "app loading" spinner if showing this.ctx.spinnerStop(); // Handle error this.ctx.onReceivedError(errorCode, description, failingUrl); } public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { final String packageName = this.ctx.getPackageName(); final PackageManager pm = this.ctx.getPackageManager(); ApplicationInfo appInfo; try { appInfo = pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA); if ((appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) { // debug = true handler.proceed(); return; } else { // debug = false super.onReceivedSslError(view, handler, error); } } catch (NameNotFoundException e) { // When it doubt, lock it out! super.onReceivedSslError(view, handler, error); } } } /** * End this activity by calling finish for activity */ public void endActivity() { this.activityState = ACTIVITY_EXITING; this.finish(); } /** * Called when a key is pressed. * * @param keyCode * @param event */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (this.appView == null) { return super.onKeyDown(keyCode, event); } // If back key if (keyCode == KeyEvent.KEYCODE_BACK) { // If back key is bound, then send event to JavaScript if (this.bound) { this.appView.loadUrl("javascript:PhoneGap.fireDocumentEvent('backbutton');"); return true; } // If not bound else { // Go to previous page in webview if it is possible to go back if (this.backHistory()) { return true; } // If not, then invoke behavior of super class else { this.activityState = ACTIVITY_EXITING; return super.onKeyDown(keyCode, event); } } } // If menu key else if (keyCode == KeyEvent.KEYCODE_MENU) { this.appView.loadUrl("javascript:PhoneGap.fireDocumentEvent('menubutton');"); return super.onKeyDown(keyCode, event); } // If search key else if (keyCode == KeyEvent.KEYCODE_SEARCH) { this.appView.loadUrl("javascript:PhoneGap.fireDocumentEvent('searchbutton');"); return true; } return false; } /** * Any calls to Activity.startActivityForResult must use method below, so * the result can be routed to them correctly. * * This is done to eliminate the need to modify DroidGap.java to receive activity results. * * @param intent The intent to start * @param requestCode Identifies who to send the result to * * @throws RuntimeException */ @Override public void startActivityForResult(Intent intent, int requestCode) throws RuntimeException { LOG.d(TAG, "DroidGap.startActivityForResult(intent,%d)", requestCode); super.startActivityForResult(intent, requestCode); } /** * Launch an activity for which you would like a result when it finished. When this activity exits, * your onActivityResult() method will be called. * * @param command The command object * @param intent The intent to start * @param requestCode The request code that is passed to callback to identify the activity */ public void startActivityForResult(IPlugin command, Intent intent, int requestCode) { this.activityResultCallback = command; this.activityResultKeepRunning = this.keepRunning; // If multitasking turned on, then disable it for activities that return results if (command != null) { this.keepRunning = false; } // Start activity super.startActivityForResult(intent, requestCode); } @Override /** * Called when an activity you launched exits, giving you the requestCode you started it with, * the resultCode it returned, and any additional data from it. * * @param requestCode The request code originally supplied to startActivityForResult(), * allowing you to identify who this result came from. * @param resultCode The integer result code returned by the child activity through its setResult(). * @param data An Intent, which can return result data to the caller (various data can be attached to Intent "extras"). */ protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); IPlugin callback = this.activityResultCallback; if (callback != null) { callback.onActivityResult(requestCode, resultCode, intent); } } @Override public void setActivityResultCallback(IPlugin plugin) { this.activityResultCallback = plugin; } /** * Report an error to the host application. These errors are unrecoverable (i.e. the main resource is unavailable). * The errorCode parameter corresponds to one of the ERROR_* constants. * * @param errorCode The error code corresponding to an ERROR_* value. * @param description A String describing the error. * @param failingUrl The url that failed to load. */ public void onReceivedError(final int errorCode, final String description, final String failingUrl) { final DroidGap me = this; // If errorUrl specified, then load it final String errorUrl = me.getStringProperty("errorUrl", null); if ((errorUrl != null) && (errorUrl.startsWith("file://") || errorUrl.indexOf(me.baseUrl) == 0 || isUrlWhiteListed(errorUrl)) && (!failingUrl.equals(errorUrl))) { // Load URL on UI thread me.runOnUiThread(new Runnable() { public void run() { me.showWebPage(errorUrl, false, true, null); } }); } // If not, then display error dialog else { me.runOnUiThread(new Runnable() { public void run() { me.appView.setVisibility(View.GONE); me.displayError("Application Error", description + " ("+failingUrl+")", "OK", true); } }); } } /** * Display an error dialog and optionally exit application. * * @param title * @param message * @param button * @param exit */ public void displayError(final String title, final String message, final String button, final boolean exit) { final DroidGap me = this; me.runOnUiThread(new Runnable() { public void run() { AlertDialog.Builder dlg = new AlertDialog.Builder(me); dlg.setMessage(message); dlg.setTitle(title); dlg.setCancelable(false); dlg.setPositiveButton(button, new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if (exit) { me.endActivity(); } } }); dlg.create(); dlg.show(); } }); } /** * We are providing this class to detect when the soft keyboard is shown * and hidden in the web view. */ class LinearLayoutSoftKeyboardDetect extends LinearLayout { private static final String TAG = "SoftKeyboardDetect"; private int oldHeight = 0; // Need to save the old height as not to send redundant events private int oldWidth = 0; // Need to save old width for orientation change private int screenWidth = 0; private int screenHeight = 0; public LinearLayoutSoftKeyboardDetect(Context context, int width, int height) { super(context); screenWidth = width; screenHeight = height; } @Override /** * Start listening to new measurement events. Fire events when the height * gets smaller fire a show keyboard event and when height gets bigger fire * a hide keyboard event. * * Note: We are using callbackServer.sendJavascript() instead of * this.appView.loadUrl() as changing the URL of the app would cause the * soft keyboard to go away. * * @param widthMeasureSpec * @param heightMeasureSpec */ protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); LOG.v(TAG, "We are in our onMeasure method"); // Get the current height of the visible part of the screen. // This height will not included the status bar. int height = MeasureSpec.getSize(heightMeasureSpec); int width = MeasureSpec.getSize(widthMeasureSpec); LOG.v(TAG, "Old Height = %d", oldHeight); LOG.v(TAG, "Height = %d", height); LOG.v(TAG, "Old Width = %d", oldWidth); LOG.v(TAG, "Width = %d", width); // If the oldHeight = 0 then this is the first measure event as the app starts up. // If oldHeight == height then we got a measurement change that doesn't affect us. if (oldHeight == 0 || oldHeight == height) { LOG.d(TAG, "Ignore this event"); } // Account for orientation change and ignore this event/Fire orientation change else if(screenHeight == width) { int tmp_var = screenHeight; screenHeight = screenWidth; screenWidth = tmp_var; LOG.v(TAG, "Orientation Change"); } // If the height as gotten bigger then we will assume the soft keyboard has // gone away. else if (height > oldHeight) { if (callbackServer != null) { LOG.v(TAG, "Throw hide keyboard event"); callbackServer.sendJavascript("PhoneGap.fireDocumentEvent('hidekeyboard');"); } } // If the height as gotten smaller then we will assume the soft keyboard has // been displayed. else if (height < oldHeight) { if (callbackServer != null) { LOG.v(TAG, "Throw show keyboard event"); callbackServer.sendJavascript("PhoneGap.fireDocumentEvent('showkeyboard');"); } } // Update the old height for the next event oldHeight = height; oldWidth = width; } } /** * Load PhoneGap configuration from res/xml/phonegap.xml. * Approved list of URLs that can be loaded into DroidGap * <access origin="http://server regexp" subdomains="true" /> * Log level: ERROR, WARN, INFO, DEBUG, VERBOSE (default=ERROR) * <log level="DEBUG" /> */ private void loadConfiguration() { int id = getResources().getIdentifier("phonegap", "xml", getPackageName()); if (id == 0) { LOG.i("PhoneGapLog", "phonegap.xml missing. Ignoring..."); return; } XmlResourceParser xml = getResources().getXml(id); int eventType = -1; while (eventType != XmlResourceParser.END_DOCUMENT) { if (eventType == XmlResourceParser.START_TAG) { String strNode = xml.getName(); if (strNode.equals("access")) { String origin = xml.getAttributeValue(null, "origin"); String subdomains = xml.getAttributeValue(null, "subdomains"); if (origin != null) { this.addWhiteListEntry(origin, (subdomains != null) && (subdomains.compareToIgnoreCase("true") == 0)); } } else if (strNode.equals("log")) { String level = xml.getAttributeValue(null, "level"); LOG.i("PhoneGapLog", "Found log level %s", level); if (level != null) { LOG.setLogLevel(level); } } } try { eventType = xml.next(); } catch (XmlPullParserException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } /** * Add entry to approved list of URLs (whitelist) * * @param origin URL regular expression to allow * @param subdomains T=include all subdomains under origin */ private void addWhiteListEntry(String origin, boolean subdomains) { try { // Unlimited access to network resources if(origin.compareTo("*") == 0) { LOG.d(TAG, "Unlimited access to network resources"); whiteList.add(Pattern.compile("*")); } else { // specific access // check if subdomains should be included // TODO: we should not add more domains if * has already been added if (subdomains) { // XXX making it stupid friendly for people who forget to include protocol/SSL if(origin.startsWith("http")) { whiteList.add(Pattern.compile(origin.replaceFirst("https{0,1}://", "^https{0,1}://.*"))); } else { whiteList.add(Pattern.compile("^https{0,1}://.*"+origin)); } LOG.d(TAG, "Origin to allow with subdomains: %s", origin); } else { // XXX making it stupid friendly for people who forget to include protocol/SSL if(origin.startsWith("http")) { whiteList.add(Pattern.compile(origin.replaceFirst("https{0,1}://", "^https{0,1}://"))); } else { whiteList.add(Pattern.compile("^https{0,1}://"+origin)); } LOG.d(TAG, "Origin to allow: %s", origin); } } } catch(Exception e) { LOG.d(TAG, "Failed to add origin %s", origin); } } /** * Determine if URL is in approved list of URLs to load. * * @param url * @return */ private boolean isUrlWhiteListed(String url) { // Check to see if we have matched url previously if (whiteListCache.get(url) != null) { return true; } // Look for match in white list Iterator<Pattern> pit = whiteList.iterator(); while (pit.hasNext()) { Pattern p = pit.next(); Matcher m = p.matcher(url); // If match found, then cache it to speed up subsequent comparisons if (m.find()) { whiteListCache.put(url, true); return true; } } return false; } /* * Hook in DroidGap for menu plugins * */ @Override public boolean onCreateOptionsMenu(Menu menu) { this.postMessage("onCreateOptionsMenu", menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onPrepareOptionsMenu(Menu menu) { this.postMessage("onPrepareOptionsMenu", menu); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { this.postMessage("onOptionsItemSelected", item); return true; } }
diff --git a/src/main/java/org/halvors/lupi/util/WorldConfiguration.java b/src/main/java/org/halvors/lupi/util/WorldConfiguration.java index 2effc86..7d52f31 100644 --- a/src/main/java/org/halvors/lupi/util/WorldConfiguration.java +++ b/src/main/java/org/halvors/lupi/util/WorldConfiguration.java @@ -1,98 +1,99 @@ /* * Copyright (C) 2011 halvors <[email protected]> * Copyright (C) 2011 speeddemon92 <[email protected]> * Copyright (C) 2011 adamonline45 <[email protected]> * * This file is part of Lupi. * * Lupi 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. * * Lupi 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 Lupi. If not, see <http://www.gnu.org/licenses/>. */ package org.halvors.lupi.util; import java.io.File; import java.util.logging.Level; import org.bukkit.util.config.Configuration; import org.halvors.lupi.Lupi; /** * Holds the configuration for individual worlds. * * @author halvors */ public class WorldConfiguration { // private Lupi plugin; private final ConfigurationManager configManager; private String worldName; private Configuration config; private File configFile; /* Configuration data start */ public boolean wolfEnable; public int wolfItem; public boolean wolfFriendly; public boolean wolfPvp; public int wolfLimit; public boolean wolfKeepChunksLoaded; public int infoItem; public boolean inventoryEnable; public int inventoryItem; /* Configuration data end */ public WorldConfiguration(Lupi plugin, String worldName) { // this.plugin = plugin; this.configManager = plugin.getConfigurationManager(); this.worldName = worldName; File baseFolder = new File(plugin.getDataFolder(), "worlds/"); configFile = new File(baseFolder, worldName + ".yml"); configManager.createDefaultConfiguration(configFile, "config_world.yml"); config = new Configuration(configFile); load(); plugin.log(Level.INFO, "Loaded configuration for world '" + worldName + '"'); } /** * Load the configuration. */ private void load() { config.load(); wolfEnable = config.getBoolean("wolf.enable", wolfEnable); wolfItem = config.getInt("wolf.item", wolfItem); wolfFriendly = config.getBoolean("wolf.friendly", wolfFriendly); wolfPvp = config.getBoolean("wolf.pvp", wolfPvp); wolfLimit = config.getInt("wolf.limit", wolfLimit); + wolfKeepChunksLoaded = config.getBoolean("wolf.keepchunksloaded", wolfKeepChunksLoaded); infoItem = config.getInt("info.item", infoItem); inventoryEnable = config.getBoolean("inventory.enable", inventoryEnable); inventoryItem = config.getInt("inventory.item", inventoryItem); config.save(); } public String getWorldName() { return this.worldName; } }
true
true
private void load() { config.load(); wolfEnable = config.getBoolean("wolf.enable", wolfEnable); wolfItem = config.getInt("wolf.item", wolfItem); wolfFriendly = config.getBoolean("wolf.friendly", wolfFriendly); wolfPvp = config.getBoolean("wolf.pvp", wolfPvp); wolfLimit = config.getInt("wolf.limit", wolfLimit); infoItem = config.getInt("info.item", infoItem); inventoryEnable = config.getBoolean("inventory.enable", inventoryEnable); inventoryItem = config.getInt("inventory.item", inventoryItem); config.save(); }
private void load() { config.load(); wolfEnable = config.getBoolean("wolf.enable", wolfEnable); wolfItem = config.getInt("wolf.item", wolfItem); wolfFriendly = config.getBoolean("wolf.friendly", wolfFriendly); wolfPvp = config.getBoolean("wolf.pvp", wolfPvp); wolfLimit = config.getInt("wolf.limit", wolfLimit); wolfKeepChunksLoaded = config.getBoolean("wolf.keepchunksloaded", wolfKeepChunksLoaded); infoItem = config.getInt("info.item", infoItem); inventoryEnable = config.getBoolean("inventory.enable", inventoryEnable); inventoryItem = config.getInt("inventory.item", inventoryItem); config.save(); }
diff --git a/src/gov/nist/javax/sip/stack/SIPClientTransaction.java b/src/gov/nist/javax/sip/stack/SIPClientTransaction.java index 9a1a6111..48455aa0 100755 --- a/src/gov/nist/javax/sip/stack/SIPClientTransaction.java +++ b/src/gov/nist/javax/sip/stack/SIPClientTransaction.java @@ -1,1908 +1,1909 @@ /* * Conditions Of Use * * This software was developed by employees of the National Institute of * Standards and Technology (NIST), an agency of the Federal Government. * Pursuant to title 15 Untied States Code Section 105, works of NIST * employees are not subject to copyright protection in the United States * and are considered to be in the public domain. As a result, a formal * license is not needed to use the software. * * This software is provided by NIST as a service and is expressly * provided "AS IS." NIST MAKES NO WARRANTY OF ANY KIND, EXPRESS, IMPLIED * OR STATUTORY, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTY OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT * AND DATA ACCURACY. NIST does not warrant or make any representations * regarding the use of the software or the results thereof, including but * not limited to the correctness, accuracy, reliability or usefulness of * the software. * * Permission to use this software is contingent upon your acceptance * of the terms of this agreement * * . * */ package gov.nist.javax.sip.stack; import gov.nist.core.CommonLogger; import gov.nist.core.InternalErrorHandler; import gov.nist.core.LogWriter; import gov.nist.core.NameValueList; import gov.nist.core.StackLogger; import gov.nist.javax.sip.SIPConstants; import gov.nist.javax.sip.SipProviderImpl; import gov.nist.javax.sip.SipStackImpl; import gov.nist.javax.sip.Utils; import gov.nist.javax.sip.address.AddressImpl; import gov.nist.javax.sip.header.Contact; import gov.nist.javax.sip.header.Event; import gov.nist.javax.sip.header.Expires; import gov.nist.javax.sip.header.RecordRoute; import gov.nist.javax.sip.header.RecordRouteList; import gov.nist.javax.sip.header.Route; import gov.nist.javax.sip.header.RouteList; import gov.nist.javax.sip.header.TimeStamp; import gov.nist.javax.sip.header.To; import gov.nist.javax.sip.header.Via; import gov.nist.javax.sip.message.SIPMessage; import gov.nist.javax.sip.message.SIPRequest; import gov.nist.javax.sip.message.SIPResponse; import gov.nist.javax.sip.stack.IllegalTransactionStateException.Reason; import java.io.IOException; import java.text.ParseException; import java.util.HashSet; import java.util.ListIterator; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.atomic.AtomicBoolean; import javax.sip.Dialog; import javax.sip.DialogState; import javax.sip.InvalidArgumentException; import javax.sip.ObjectInUseException; import javax.sip.SipException; import javax.sip.Timeout; import javax.sip.TimeoutEvent; import javax.sip.TransactionState; import javax.sip.address.Hop; import javax.sip.address.SipURI; import javax.sip.header.EventHeader; import javax.sip.header.ExpiresHeader; import javax.sip.header.RouteHeader; import javax.sip.header.TimeStampHeader; import javax.sip.message.Request; /* * Jeff Keyser -- initial. Daniel J. Martinez Manzano --Added support for TLS message channel. * Emil Ivov -- bug fixes. Chris Beardshear -- bug fix. Andreas Bystrom -- bug fixes. Matt Keller * (Motorolla) -- bug fix. */ /** * Represents a client transaction. Implements the following state machines. (From RFC 3261) * * <pre> * * * * * * * |INVITE from TU * Timer A fires |INVITE sent * Reset A, V Timer B fires * INVITE sent +-----------+ or Transport Err. * +---------| |---------------+inform TU * | | Calling | | * +--------&gt;| |--------------&gt;| * +-----------+ 2xx | * | | 2xx to TU | * | |1xx | * 300-699 +---------------+ |1xx to TU | * ACK sent | | | * resp. to TU | 1xx V | * | 1xx to TU -----------+ | * | +---------| | | * | | |Proceeding |--------------&gt;| * | +--------&gt;| | 2xx | * | +-----------+ 2xx to TU | * | 300-699 | | * | ACK sent, | | * | resp. to TU| | * | | | NOTE: * | 300-699 V | * | ACK sent +-----------+Transport Err. | transitions * | +---------| |Inform TU | labeled with * | | | Completed |--------------&gt;| the event * | +--------&gt;| | | over the action * | +-----------+ | to take * | &circ; | | * | | | Timer D fires | * +--------------+ | - | * | | * V | * +-----------+ | * | | | * | Terminated|&lt;--------------+ * | | * +-----------+ * * Figure 5: INVITE client transaction * * * |Request from TU * |send request * Timer E V * send request +-----------+ * +---------| |-------------------+ * | | Trying | Timer F | * +--------&gt;| | or Transport Err.| * +-----------+ inform TU | * 200-699 | | | * resp. to TU | |1xx | * +---------------+ |resp. to TU | * | | | * | Timer E V Timer F | * | send req +-----------+ or Transport Err. | * | +---------| | inform TU | * | | |Proceeding |------------------&gt;| * | +--------&gt;| |-----+ | * | +-----------+ |1xx | * | | &circ; |resp to TU | * | 200-699 | +--------+ | * | resp. to TU | | * | | | * | V | * | +-----------+ | * | | | | * | | Completed | | * | | | | * | +-----------+ | * | &circ; | | * | | | Timer K | * +--------------+ | - | * | | * V | * NOTE: +-----------+ | * | | | * transitions | Terminated|&lt;------------------+ * labeled with | | * the event +-----------+ * over the action * to take * * Figure 6: non-INVITE client transaction * * * * * * * </pre> * * * @author M. Ranganathan * * @version 1.2 $Revision: 1.144 $ $Date: 2010-12-02 22:04:16 $ */ public class SIPClientTransaction extends SIPTransaction implements ServerResponseInterface, javax.sip.ClientTransaction, gov.nist.javax.sip.ClientTransactionExt { private static StackLogger logger = CommonLogger.getLogger(SIPClientTransaction.class); // a SIP Client transaction may belong simultaneously to multiple // dialogs in the early state. These dialogs all have // the same call ID and same From tag but different to tags. //jeand : we don't keep the ref to the dialogs but only to their id to save on memory private Set<String> sipDialogs; private SIPRequest lastRequest; private int viaPort; private String viaHost; // Real ResponseInterface to pass messages to private transient ServerResponseInterface respondTo; // jeand: ref to the default dialog id to allow nullying the ref to the dialog quickly // and thus saving on mem private String defaultDialogId; private SIPDialog defaultDialog; private Hop nextHop; private boolean notifyOnRetransmit; private boolean timeoutIfStillInCallingState; private int callingStateTimeoutCount; private SIPStackTimerTask transactionTimer; // jeand/ avoid keeping the full Original Request in memory private String originalRequestFromTag; private String originalRequestCallId; private Event originalRequestEventHeader; private Contact originalRequestContact; private String originalRequestScheme; private Object transactionTimerLock = new Object(); private AtomicBoolean timerKStarted = new AtomicBoolean(false); private boolean transactionTimerCancelled = false; private Set<Integer> responsesReceived = new HashSet<Integer>(2); public class TransactionTimer extends SIPStackTimerTask { public TransactionTimer() { } public void runTask() { SIPClientTransaction clientTransaction; SIPTransactionStack sipStack; clientTransaction = SIPClientTransaction.this; sipStack = clientTransaction.sipStack; // If the transaction has terminated, if (clientTransaction.isTerminated()) { try { sipStack.getTimer().cancel(this); } catch (IllegalStateException ex) { if (!sipStack.isAlive()) return; } cleanUpOnTerminated(); } else { // If this transaction has not // terminated, // Fire the transaction timer. clientTransaction.fireTimer(); } } } class ExpiresTimerTask extends SIPStackTimerTask { public ExpiresTimerTask() { } @Override public void runTask() { SIPClientTransaction ct = SIPClientTransaction.this; SipProviderImpl provider = ct.getSipProvider(); if (ct.getState() != TransactionState.TERMINATED ) { TimeoutEvent tte = new TimeoutEvent(SIPClientTransaction.this.getSipProvider(), SIPClientTransaction.this, Timeout.TRANSACTION); provider.handleEvent(tte, ct); } else { if ( SIPClientTransaction.this.logger.isLoggingEnabled(LogWriter.TRACE_DEBUG) ) { SIPClientTransaction.this.logger.logDebug("state = " + ct.getState()); } } } } /** * Creates a new client transaction. * * @param newSIPStack Transaction stack this transaction belongs to. * @param newChannelToUse Channel to encapsulate. * @return the created client transaction. */ protected SIPClientTransaction(SIPTransactionStack newSIPStack, MessageChannel newChannelToUse) { super(newSIPStack, newChannelToUse); // Create a random branch parameter for this transaction setBranch(Utils.getInstance().generateBranchId()); this.messageProcessor = newChannelToUse.messageProcessor; this.setEncapsulatedChannel(newChannelToUse); this.notifyOnRetransmit = false; this.timeoutIfStillInCallingState = false; if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { logger.logDebug("Creating clientTransaction " + this); logger.logStackTrace(); } // this.startTransactionTimer(); this.sipDialogs = new CopyOnWriteArraySet<String>(); } /** * Sets the real ResponseInterface this transaction encapsulates. * * @param newRespondTo ResponseInterface to send messages to. */ public void setResponseInterface(ServerResponseInterface newRespondTo) { if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { logger.logDebug( "Setting response interface for " + this + " to " + newRespondTo); if (newRespondTo == null) { logger.logStackTrace(); logger.logDebug("WARNING -- setting to null!"); } } respondTo = newRespondTo; } /** * Returns this transaction. */ public MessageChannel getRequestChannel() { return this; } /** * Deterines if the message is a part of this transaction. * * @param messageToTest Message to check if it is part of this transaction. * * @return true if the message is part of this transaction, false if not. */ public boolean isMessagePartOfTransaction(SIPMessage messageToTest) { // List of Via headers in the message to test Via topMostViaHeader = messageToTest.getTopmostVia(); // Flags whether the select message is part of this transaction boolean transactionMatches; String messageBranch = topMostViaHeader.getBranch(); boolean rfc3261Compliant = getBranch() != null && messageBranch != null && getBranch().toLowerCase().startsWith( SIPConstants.BRANCH_MAGIC_COOKIE_LOWER_CASE) && messageBranch.toLowerCase().startsWith( SIPConstants.BRANCH_MAGIC_COOKIE_LOWER_CASE); transactionMatches = false; if (TransactionState._COMPLETED == this.getInternalState()) { if (rfc3261Compliant) { transactionMatches = getBranch().equalsIgnoreCase( topMostViaHeader.getBranch()) && getMethod().equals(messageToTest.getCSeq().getMethod()); } else { transactionMatches = getBranch().equals(messageToTest.getTransactionId()); } } else if (!isTerminated()) { if (rfc3261Compliant) { if (topMostViaHeader != null) { // If the branch parameter is the // same as this transaction and the method is the same, if (getBranch().equalsIgnoreCase(topMostViaHeader.getBranch())) { transactionMatches = getMethod().equals( messageToTest.getCSeq().getMethod()); } } } else { // not RFC 3261 compliant. if (getBranch() != null) { transactionMatches = getBranch().equalsIgnoreCase( messageToTest.getTransactionId()); } else { transactionMatches = ((SIPRequest)getRequest()).getTransactionId() .equalsIgnoreCase(messageToTest.getTransactionId()); } } } return transactionMatches; } /** * Send a request message through this transaction and onto the client. * * @param messageToSend Request to process and send. */ public void sendMessage(SIPMessage messageToSend) throws IOException { try { // Message typecast as a request SIPRequest transactionRequest; transactionRequest = (SIPRequest) messageToSend; // Set the branch id for the top via header. Via topVia = (Via) transactionRequest.getTopmostVia(); // Tack on a branch identifier to match responses. try { topVia.setBranch(getBranch()); } catch (java.text.ParseException ex) { } if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { logger.logDebug("Sending Message " + messageToSend); logger.logDebug("TransactionState " + this.getState()); } // If this is the first request for this transaction, if (TransactionState._PROCEEDING == getInternalState() || TransactionState._CALLING == getInternalState()) { // If this is a TU-generated ACK request, if (transactionRequest.getMethod().equals(Request.ACK)) { // Send directly to the underlying // transport and close this transaction if (isReliable()) { this.setState(TransactionState._TERMINATED); } else { this.setState(TransactionState._COMPLETED); } cleanUpOnTimer(); // BUGBUG -- This suppresses sending the ACK uncomment this // to // test 4xx retransmission // if (transactionRequest.getMethod() != Request.ACK) super.sendMessage(transactionRequest); return; } } try { // Send the message to the server lastRequest = transactionRequest; if (getInternalState() < 0) { // Save this request as the one this transaction // is handling setOriginalRequest(transactionRequest); // Change to trying/calling state // Set state first to avoid race condition.. if (transactionRequest.getMethod().equals(Request.INVITE)) { this.setState(TransactionState._CALLING); } else if (transactionRequest.getMethod().equals(Request.ACK)) { // Acks are never retransmitted. this.setState(TransactionState._TERMINATED); cleanUpOnTimer(); } else { this.setState(TransactionState._TRYING); } if (!isReliable()) { enableRetransmissionTimer(); } if (isInviteTransaction()) { enableTimeoutTimer(TIMER_B); } else { enableTimeoutTimer(TIMER_F); } } // BUGBUG This supresses sending ACKS -- uncomment to test // 4xx retransmission. // if (transactionRequest.getMethod() != Request.ACK) super.sendMessage(transactionRequest); } catch (IOException e) { this.setState(TransactionState._TERMINATED); throw e; } } finally { this.isMapped = true; this.startTransactionTimer(); } } /** * Process a new response message through this transaction. If necessary, this message will * also be passed onto the TU. * * @param transactionResponse Response to process. * @param sourceChannel Channel that received this message. */ public synchronized void processResponse(SIPResponse transactionResponse, MessageChannel sourceChannel, SIPDialog dialog) { // If the state has not yet been assigned then this is a // spurious response. if (getInternalState() < 0) return; // Ignore 1xx if ((TransactionState._COMPLETED == this.getInternalState() || TransactionState._TERMINATED == this .getInternalState()) && transactionResponse.getStatusCode() / 100 == 1) { return; } if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { logger.logDebug( "processing " + transactionResponse.getFirstLine() + "current state = " + getState()); logger.logDebug("dialog = " + dialog); } this.lastResponse = transactionResponse; /* * JvB: this is now duplicate with code in the other processResponse * * if (dialog != null && transactionResponse.getStatusCode() != 100 && * (transactionResponse.getTo().getTag() != null || sipStack .isRfc2543Supported())) { // * add the route before you process the response. dialog.setLastResponse(this, * transactionResponse); this.setDialog(dialog, transactionResponse.getDialogId(false)); } */ try { if (isInviteTransaction()) inviteClientTransaction(transactionResponse, sourceChannel, dialog); else nonInviteClientTransaction(transactionResponse, sourceChannel, dialog); } catch (IOException ex) { if (logger.isLoggingEnabled()) logger.logException(ex); this.setState(TransactionState._TERMINATED); raiseErrorEvent(SIPTransactionErrorEvent.TRANSPORT_ERROR); } } /** * Implements the state machine for invite client transactions. * * <pre> * * * * * * |Request from TU * |send request * Timer E V * send request +-----------+ * +---------| |-------------------+ * | | Trying | Timer F | * +--------&gt;| | or Transport Err.| * +-----------+ inform TU | * 200-699 | | | * resp. to TU | |1xx | * +---------------+ |resp. to TU | * | | | * | Timer E V Timer F | * | send req +-----------+ or Transport Err. | * | +---------| | inform TU | * | | |Proceeding |------------------&gt;| * | +--------&gt;| |-----+ | * | +-----------+ |1xx | * | | &circ; |resp to TU | * | 200-699 | +--------+ | * | resp. to TU | | * | | | * | V | * | +-----------+ | * | | | | * | | Completed | | * | | | | * | +-----------+ | * | &circ; | | * | | | Timer K | * +--------------+ | - | * | | * V | * NOTE: +-----------+ | * | | | * transitions | Terminated|&lt;------------------+ * labeled with | | * the event +-----------+ * over the action * to take * * Figure 6: non-INVITE client transaction * * * * * </pre> * * @param transactionResponse -- transaction response received. * @param sourceChannel - source channel on which the response was received. */ private void nonInviteClientTransaction(SIPResponse transactionResponse, MessageChannel sourceChannel, SIPDialog sipDialog) throws IOException { int statusCode = transactionResponse.getStatusCode(); if (TransactionState._TRYING == this.getInternalState()) { if (statusCode / 100 == 1) { this.setState(TransactionState._PROCEEDING); enableRetransmissionTimer(MAXIMUM_RETRANSMISSION_TICK_COUNT); enableTimeoutTimer(TIMER_F); // According to RFC, the TU has to be informed on // this transition. if (respondTo != null) { respondTo.processResponse(transactionResponse, this, sipDialog); } else { this.semRelease(); } } else if (200 <= statusCode && statusCode <= 699) { if (!isReliable()) { this.setState(TransactionState._COMPLETED); scheduleTimerK(TIMER_K); } else { this.setState(TransactionState._TERMINATED); } // Send the response up to the TU. if (respondTo != null) { respondTo.processResponse(transactionResponse, this, sipDialog); } else { this.semRelease(); } if (isReliable() && TransactionState._TERMINATED == getInternalState()) { cleanUpOnTerminated(); } cleanUpOnTimer(); } } else if (TransactionState._PROCEEDING == this.getInternalState()) { if (statusCode / 100 == 1) { if (respondTo != null) { respondTo.processResponse(transactionResponse, this, sipDialog); } else { this.semRelease(); } } else if (200 <= statusCode && statusCode <= 699) { disableRetransmissionTimer(); disableTimeoutTimer(); if (!isReliable()) { this.setState(TransactionState._COMPLETED); scheduleTimerK(TIMER_K); } else { this.setState(TransactionState._TERMINATED); } if (respondTo != null) { respondTo.processResponse(transactionResponse, this, sipDialog); } else { this.semRelease(); } if (isReliable() && TransactionState._TERMINATED == getInternalState()) { cleanUpOnTerminated(); } cleanUpOnTimer(); } } else { if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { logger.logDebug( " Not sending response to TU! " + getState()); } this.semRelease(); } } // avoid re-scheduling the transaction timer every 500ms while we know we have to wait for TIMER_K * 500 ms private void scheduleTimerK(long time) { if(transactionTimer != null && timerKStarted.compareAndSet(false, true)) { synchronized (transactionTimerLock) { if(!transactionTimerCancelled) { sipStack.getTimer().cancel(transactionTimer); transactionTimer = null; if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { logger.logDebug("starting TransactionTimerK() : " + getTransactionId() + " time " + time); } SIPStackTimerTask task = new SIPStackTimerTask () { public void runTask() { if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { logger.logDebug("executing TransactionTimerJ() : " + getTransactionId()); } fireTimeoutTimer(); cleanUpOnTerminated(); } }; if(time > 0) { sipStack.getTimer().schedule(task, time * BASE_TIMER_INTERVAL); } else { task.runTask(); } transactionTimerCancelled =true; } } } } /** * Implements the state machine for invite client transactions. * * <pre> * * * * * * |INVITE from TU * Timer A fires |INVITE sent * Reset A, V Timer B fires * INVITE sent +-----------+ or Transport Err. * +---------| |---------------+inform TU * | | Calling | | * +--------&gt;| |--------------&gt;| * +-----------+ 2xx | * | | 2xx to TU | * | |1xx | * 300-699 +---------------+ |1xx to TU | * ACK sent | | | * resp. to TU | 1xx V | * | 1xx to TU -----------+ | * | +---------| | | * | | |Proceeding |--------------&gt;| * | +--------&gt;| | 2xx | * | +-----------+ 2xx to TU | * | 300-699 | | * | ACK sent, | | * | resp. to TU| | * | | | NOTE: * | 300-699 V | * | ACK sent +-----------+Transport Err. | transitions * | +---------| |Inform TU | labeled with * | | | Completed |--------------&gt;| the event * | +--------&gt;| | | over the action * | +-----------+ | to take * | &circ; | | * | | | Timer D fires | * +--------------+ | - | * | | * V | * +-----------+ | * | | | * | Terminated|&lt;--------------+ * | | * +-----------+ * * * * * </pre> * * @param transactionResponse -- transaction response received. * @param sourceChannel - source channel on which the response was received. */ private void inviteClientTransaction(SIPResponse transactionResponse, MessageChannel sourceChannel, SIPDialog dialog) throws IOException { int statusCode = transactionResponse.getStatusCode(); if (TransactionState._TERMINATED == this.getInternalState()) { boolean ackAlreadySent = false; // if (dialog != null && dialog.isAckSeen() && dialog.getLastAckSent() != null) if ( dialog!= null && dialog.isAckSent(transactionResponse.getCSeq().getSeqNumber())) { if (dialog.getLastAckSent().getCSeq().getSeqNumber() == transactionResponse.getCSeq() .getSeqNumber() && transactionResponse.getFromTag().equals( dialog.getLastAckSent().getFromTag())) { // the last ack sent corresponded to this response ackAlreadySent = true; } } // retransmit the ACK for this response. if (dialog!= null && ackAlreadySent && transactionResponse.getCSeq().getMethod().equals(dialog.getMethod())) { try { // Found the dialog - resend the ACK and // dont pass up the null transaction if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) logger.logDebug("resending ACK"); dialog.resendAck(); } catch (SipException ex) { // What to do here ?? kill the dialog? } - } - if(dialog == null) { + } + if(dialog == null && statusCode >= 200 && statusCode < 300) { // http://java.net/jira/browse/JSIP-377 + // RFC 3261 Section 17.1.1.2 // The client transaction MUST be destroyed the instant it enters the // "Terminated" state. This is actually necessary to guarantee correct // operation. The reason is that 2xx responses to an INVITE are treated // differently; each one is forwarded by proxies // for proxy, it happens that there is a race condition while the tx is getting removed and TERMINATED - // where some responses are still able to be handled by it so we let responses for proxies pass up to the application + // where some responses are still able to be handled by it so we let 2xx responses for proxies pass up to the application if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) logger.logDebug("Client Transaction " + this + " branch id " + getBranch() + " doesn't have any dialog and is in TERMINATED state"); if (respondTo != null) { if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) - logger.logDebug("passing response up to the application"); + logger.logDebug("passing 2xx response up to the application"); respondTo.processResponse(transactionResponse, this, dialog); } else { this.semRelease(); return; } } else { this.semRelease(); return; } } else if (TransactionState._CALLING == this.getInternalState()) { if (statusCode / 100 == 2) { // JvB: do this ~before~ calling the application, to avoid // retransmissions // of the INVITE after app sends ACK disableRetransmissionTimer(); disableTimeoutTimer(); this.setState(TransactionState._TERMINATED); // 200 responses are always seen by TU. if (respondTo != null) respondTo.processResponse(transactionResponse, this, dialog); else { this.semRelease(); } } else if (statusCode / 100 == 1) { disableRetransmissionTimer(); disableTimeoutTimer(); this.setState(TransactionState._PROCEEDING); if (respondTo != null) respondTo.processResponse(transactionResponse, this, dialog); else { this.semRelease(); } } else if (300 <= statusCode && statusCode <= 699) { // Send back an ACK request try { sendMessage((SIPRequest) createErrorAck()); } catch (Exception ex) { logger.logError( "Unexpected Exception sending ACK -- sending error AcK ", ex); } /* * When in either the "Calling" or "Proceeding" states, reception of response with * status code from 300-699 MUST cause the client transaction to transition to * "Completed". The client transaction MUST pass the received response up to the * TU, and the client transaction MUST generate an ACK request. */ if (this.getDialog() != null && ((SIPDialog)this.getDialog()).isBackToBackUserAgent()) { ((SIPDialog) this.getDialog()).releaseAckSem(); } if (!isReliable()) { this.setState(TransactionState._COMPLETED); enableTimeoutTimer(TIMER_D); } else { // Proceed immediately to the TERMINATED state. this.setState(TransactionState._TERMINATED); } if (respondTo != null) { respondTo.processResponse(transactionResponse, this, dialog); } else { this.semRelease(); } cleanUpOnTimer(); } } else if (TransactionState._PROCEEDING == this.getInternalState()) { if (statusCode / 100 == 1) { if (respondTo != null) { respondTo.processResponse(transactionResponse, this, dialog); } else { this.semRelease(); } } else if (statusCode / 100 == 2) { this.setState(TransactionState._TERMINATED); if (respondTo != null) { respondTo.processResponse(transactionResponse, this, dialog); } else { this.semRelease(); } } else if (300 <= statusCode && statusCode <= 699) { // Send back an ACK request try { sendMessage((SIPRequest) createErrorAck()); } catch (Exception ex) { InternalErrorHandler.handleException(ex); } if (this.getDialog() != null) { ((SIPDialog) this.getDialog()).releaseAckSem(); } // JvB: update state before passing to app if (!isReliable()) { this.setState(TransactionState._COMPLETED); this.enableTimeoutTimer(TIMER_D); } else { this.setState(TransactionState._TERMINATED); } cleanUpOnTimer(); // Pass up to the TU for processing. if (respondTo != null) respondTo.processResponse(transactionResponse, this, dialog); else { this.semRelease(); } // JvB: duplicate with line 874 // if (!isReliable()) { // enableTimeoutTimer(TIMER_D); // } } } else if (TransactionState._COMPLETED == this.getInternalState()) { if (300 <= statusCode && statusCode <= 699) { // Send back an ACK request try { sendMessage((SIPRequest) createErrorAck()); } catch (Exception ex) { InternalErrorHandler.handleException(ex); } finally { this.semRelease(); } } } } /* * (non-Javadoc) * * @see javax.sip.ClientTransaction#sendRequest() */ public void sendRequest() throws SipException { SIPRequest sipRequest = this.getOriginalRequest(); if (this.getInternalState() >= 0) throw new IllegalTransactionStateException("Request already sent", Reason.RequestAlreadySent); if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { logger.logDebug("sendRequest() " + sipRequest); } try { sipRequest.checkHeaders(); } catch (ParseException ex) { if (logger.isLoggingEnabled()) logger.logError("missing required header"); throw new IllegalTransactionStateException(ex.getMessage(), Reason.MissingRequiredHeader); } if (getMethod().equals(Request.SUBSCRIBE) && sipRequest.getHeader(ExpiresHeader.NAME) == null) { /* * If no "Expires" header is present in a SUBSCRIBE request, the implied default is * defined by the event package being used. * */ if (logger.isLoggingEnabled()) logger.logWarning( "Expires header missing in outgoing subscribe --" + " Notifier will assume implied value on event package"); } try { /* * This check is removed because it causes problems for load balancers ( See issue * 136) reported by Raghav Ramesh ( BT ) * */ if (this.getMethod().equals(Request.CANCEL) && sipStack.isCancelClientTransactionChecked()) { SIPClientTransaction ct = (SIPClientTransaction) sipStack.findCancelTransaction( this.getOriginalRequest(), false); if (ct == null) { /* * If the original request has generated a final response, the CANCEL SHOULD * NOT be sent, as it is an effective no-op, since CANCEL has no effect on * requests that have already generated a final response. */ throw new SipException("Could not find original tx to cancel. RFC 3261 9.1"); } else if (ct.getInternalState() < 0) { throw new SipException( "State is null no provisional response yet -- cannot cancel RFC 3261 9.1"); } else if (!ct.isInviteTransaction()) { throw new SipException("Cannot cancel non-invite requests RFC 3261 9.1"); } } else if (this.getMethod().equals(Request.BYE) || this.getMethod().equals(Request.NOTIFY)) { SIPDialog dialog = sipStack.getDialog(this.getOriginalRequest() .getDialogId(false)); // I want to behave like a user agent so send the BYE using the // Dialog if (this.getSipProvider().isAutomaticDialogSupportEnabled() && dialog != null) { throw new SipException( "Dialog is present and AutomaticDialogSupport is enabled for " + " the provider -- Send the Request using the Dialog.sendRequest(transaction)"); } } // Only map this after the fist request is sent out. if (isInviteTransaction()) { SIPDialog dialog = this.getDefaultDialog(); if (dialog != null && dialog.isBackToBackUserAgent()) { // Block sending re-INVITE till we see the ACK. if ( ! dialog.takeAckSem() ) { throw new SipException ("Failed to take ACK semaphore"); } } } this.isMapped = true; // Time extracted from the Expires header. int expiresTime = -1; if ( sipRequest.getHeader(ExpiresHeader.NAME) != null ) { Expires expires = (Expires) sipRequest.getHeader(ExpiresHeader.NAME); expiresTime = expires.getExpires(); } // This is a User Agent. The user has specified an Expires time. Start a timer // which will check if the tx is terminated by that time. if ( this.getDefaultDialog() != null && isInviteTransaction() && expiresTime != -1 && expiresTimerTask == null ) { this.expiresTimerTask = new ExpiresTimerTask(); sipStack.getTimer().schedule(expiresTimerTask, expiresTime * 1000); } this.sendMessage(sipRequest); } catch (IOException ex) { this.setState(TransactionState._TERMINATED); if ( this.expiresTimerTask != null ) { sipStack.getTimer().cancel(this.expiresTimerTask); } throw new SipException( ex.getMessage() == null ? "IO Error sending request" : ex.getMessage(), ex); } } /** * Called by the transaction stack when a retransmission timer fires. */ protected void fireRetransmissionTimer() { try { // Resend the last request sent if (this.getInternalState() < 0 || !this.isMapped) return; boolean inv = isInviteTransaction(); int s = this.getInternalState(); // JvB: INVITE CTs only retransmit in CALLING, non-INVITE in both TRYING and // PROCEEDING // Bug-fix for non-INVITE transactions not retransmitted when 1xx response received if ((inv && TransactionState._CALLING == s) || (!inv && (TransactionState._TRYING == s || TransactionState._PROCEEDING == s))) { // If the retransmission filter is disabled then // retransmission of the INVITE is the application // responsibility. if (lastRequest != null) { if (sipStack.generateTimeStampHeader && lastRequest.getHeader(TimeStampHeader.NAME) != null) { long milisec = System.currentTimeMillis(); TimeStamp timeStamp = new TimeStamp(); try { timeStamp.setTimeStamp(milisec); } catch (InvalidArgumentException ex) { InternalErrorHandler.handleException(ex); } lastRequest.setHeader(timeStamp); } super.sendMessage(lastRequest); if (this.notifyOnRetransmit) { TimeoutEvent txTimeout = new TimeoutEvent(this.getSipProvider(), this, Timeout.RETRANSMIT); this.getSipProvider().handleEvent(txTimeout, this); } if (this.timeoutIfStillInCallingState && this.getInternalState() == TransactionState._CALLING) { this.callingStateTimeoutCount--; if (callingStateTimeoutCount == 0) { TimeoutEvent timeoutEvent = new TimeoutEvent(this.getSipProvider(), this, Timeout.RETRANSMIT); this.getSipProvider().handleEvent(timeoutEvent, this); this.timeoutIfStillInCallingState = false; } } } } } catch (IOException e) { this.raiseIOExceptionEvent(); raiseErrorEvent(SIPTransactionErrorEvent.TRANSPORT_ERROR); } } /** * Called by the transaction stack when a timeout timer fires. */ protected void fireTimeoutTimer() { if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) logger.logDebug("fireTimeoutTimer " + this); SIPDialog dialog = (SIPDialog) this.getDialog(); if (TransactionState._CALLING == this.getInternalState() || TransactionState._TRYING == this.getInternalState() || TransactionState._PROCEEDING == this.getInternalState()) { // Timeout occured. If this is asociated with a transaction // creation then kill the dialog. if (dialog != null && (dialog.getState() == null || dialog.getState() == DialogState.EARLY)) { if (SIPTransactionStack.isDialogCreated(this.getMethod())) { // If this is a re-invite we do not delete the dialog even // if the // reinvite times out. Else // terminate the enclosing dialog. dialog.delete(); } } else if (dialog != null) { // Guard against the case of BYE time out. if (this.getMethod().equalsIgnoreCase(Request.BYE) && dialog.isTerminatedOnBye()) { // Terminate the associated dialog on BYE Timeout. dialog.delete(); } } } if (TransactionState._COMPLETED != this.getInternalState() && TransactionState._TERMINATED != this.getInternalState()) { raiseErrorEvent(SIPTransactionErrorEvent.TIMEOUT_ERROR); // Got a timeout error on a cancel. if (this.getMethod().equalsIgnoreCase(Request.CANCEL)) { SIPClientTransaction inviteTx = (SIPClientTransaction) this.getOriginalRequest() .getInviteTransaction(); if (inviteTx != null && ((inviteTx.getInternalState() == TransactionState._CALLING || inviteTx .getInternalState() == TransactionState._PROCEEDING)) && inviteTx.getDialog() != null) { /* * A proxy server should have started TIMER C and take care of the Termination * using transaction.terminate() by itself (i.e. this is not the job of the * stack at this point but we do it to be nice. */ inviteTx.setState(TransactionState._TERMINATED); } } } else { this.setState(TransactionState._TERMINATED); } } /* * (non-Javadoc) * * @see javax.sip.ClientTransaction#createCancel() */ public Request createCancel() throws SipException { SIPRequest originalRequest = this.getOriginalRequest(); if (originalRequest == null) throw new SipException("Bad state " + getState()); if (!originalRequest.getMethod().equals(Request.INVITE)) throw new SipException("Only INIVTE may be cancelled"); if (originalRequest.getMethod().equalsIgnoreCase(Request.ACK)) throw new SipException("Cannot Cancel ACK!"); else { SIPRequest cancelRequest = originalRequest.createCancelRequest(); cancelRequest.setInviteTransaction(this); return cancelRequest; } } /* * (non-Javadoc) * * @see javax.sip.ClientTransaction#createAck() */ public Request createAck() throws SipException { SIPRequest originalRequest = this.getOriginalRequest(); if (originalRequest == null) throw new SipException("bad state " + getState()); if (getMethod().equalsIgnoreCase(Request.ACK)) { throw new SipException("Cannot ACK an ACK!"); } else if (lastResponse == null) { throw new SipException("bad Transaction state"); } else if (lastResponse.getStatusCode() < 200) { if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { logger.logDebug("lastResponse = " + lastResponse); } throw new SipException("Cannot ACK a provisional response!"); } SIPRequest ackRequest = originalRequest.createAckRequest((To) lastResponse.getTo()); // Pull the record route headers from the last reesponse. RecordRouteList recordRouteList = lastResponse.getRecordRouteHeaders(); if (recordRouteList == null) { // If the record route list is null then we can // construct the ACK from the specified contact header. // Note the 3xx check here because 3xx is a redirect. // The contact header for the 3xx is the redirected // location so we cannot use that to construct the // request URI. if (lastResponse.getContactHeaders() != null && lastResponse.getStatusCode() / 100 != 3) { Contact contact = (Contact) lastResponse.getContactHeaders().getFirst(); javax.sip.address.URI uri = (javax.sip.address.URI) contact.getAddress().getURI() .clone(); ackRequest.setRequestURI(uri); } return ackRequest; } ackRequest.removeHeader(RouteHeader.NAME); RouteList routeList = new RouteList(); // start at the end of the list and walk backwards ListIterator<RecordRoute> li = recordRouteList.listIterator(recordRouteList.size()); while (li.hasPrevious()) { RecordRoute rr = (RecordRoute) li.previous(); Route route = new Route(); route.setAddress((AddressImpl) ((AddressImpl) rr.getAddress()).clone()); route.setParameters((NameValueList) rr.getParameters().clone()); routeList.add(route); } Contact contact = null; if (lastResponse.getContactHeaders() != null) { contact = (Contact) lastResponse.getContactHeaders().getFirst(); } if (!((SipURI) ((Route) routeList.getFirst()).getAddress().getURI()).hasLrParam()) { // Contact may not yet be there (bug reported by Andreas B). Route route = null; if (contact != null) { route = new Route(); route.setAddress((AddressImpl) ((AddressImpl) (contact.getAddress())).clone()); } Route firstRoute = (Route) routeList.getFirst(); routeList.removeFirst(); javax.sip.address.URI uri = firstRoute.getAddress().getURI(); ackRequest.setRequestURI(uri); if (route != null) routeList.add(route); ackRequest.addHeader(routeList); } else { if (contact != null) { javax.sip.address.URI uri = (javax.sip.address.URI) contact.getAddress().getURI() .clone(); ackRequest.setRequestURI(uri); ackRequest.addHeader(routeList); } } return ackRequest; } /* * Creates an ACK for an error response, according to RFC3261 section 17.1.1.3 * * Note that this is different from an ACK for 2xx */ private final Request createErrorAck() throws SipException, ParseException { SIPRequest originalRequest = this.getOriginalRequest(); if (originalRequest == null) throw new SipException("bad state " + getState()); if (!isInviteTransaction()) { throw new SipException("Can only ACK an INVITE!"); } else if (lastResponse == null) { throw new SipException("bad Transaction state"); } else if (lastResponse.getStatusCode() < 200) { if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { logger.logDebug("lastResponse = " + lastResponse); } throw new SipException("Cannot ACK a provisional response!"); } return originalRequest.createErrorAck((To) lastResponse.getTo()); } /** * Set the port of the recipient. */ public void setViaPort(int port) { this.viaPort = port; } /** * Set the port of the recipient. */ public void setViaHost(String host) { this.viaHost = host; } /** * Get the port of the recipient. */ public int getViaPort() { return this.viaPort; } /** * Get the host of the recipient. */ public String getViaHost() { return this.viaHost; } /** * get the via header for an outgoing request. */ public Via getOutgoingViaHeader() { return this.getMessageProcessor().getViaHeader(); } /** * This is called by the stack after a non-invite client transaction goes to completed state. */ public void clearState() { // reduce the state to minimum // This assumes that the application will not need // to access the request once the transaction is // completed. // TODO -- revisit this - results in a null pointer // occuring occasionally. // this.lastRequest = null; // this.originalRequest = null; // this.lastResponse = null; } /** * Sets a timeout after which the connection is closed (provided the server does not use the * connection for outgoing requests in this time period) and calls the superclass to set * state. */ public void setState(int newState) { // Set this timer for connection caching // of incoming connections. if (newState == TransactionState._TERMINATED && this.isReliable() && (!getSIPStack().cacheClientConnections)) { // Set a time after which the connection // is closed. this.collectionTime = TIMER_J; } if (super.getInternalState() != TransactionState._COMPLETED && (newState == TransactionState._COMPLETED || newState == TransactionState._TERMINATED)) { sipStack.decrementActiveClientTransactionCount(); } super.setState(newState); } /** * Start the timer task. */ protected void startTransactionTimer() { if (this.transactionTimerStarted.compareAndSet(false, true)) { if ( sipStack.getTimer() != null ) { synchronized (transactionTimerLock) { if(!transactionTimerCancelled) { transactionTimer = new TransactionTimer(); sipStack.getTimer().scheduleWithFixedDelay(transactionTimer, BASE_TIMER_INTERVAL, BASE_TIMER_INTERVAL); } } } } } /* * Terminate a transaction. This marks the tx as terminated The tx scanner will run and remove * the tx. (non-Javadoc) * * @see javax.sip.Transaction#terminate() */ public void terminate() throws ObjectInUseException { this.setState(TransactionState._TERMINATED); if(!transactionTimerStarted.get()) { // if no transaction timer was started just remove the tx without firing a transaction terminated event testAndSetTransactionTerminatedEvent(); sipStack.removeTransaction(this); } } /** * Stop the ExPIRES timer if it is running. */ public void stopExpiresTimer() { if ( this.expiresTimerTask != null ) { sipStack.getTimer().cancel(this.expiresTimerTask); this.expiresTimerTask = null; } } /** * Check if the From tag of the response matches the from tag of the original message. A * Response with a tag mismatch should be dropped if a Dialog has been created for the * original request. * * @param sipResponse the response to check. * @return true if the check passes. */ public boolean checkFromTag(SIPResponse sipResponse) { String originalFromTag = getOriginalRequestFromTag(); if (this.defaultDialog != null) { if (originalFromTag == null ^ sipResponse.getFrom().getTag() == null) { if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) logger.logDebug("From tag mismatch -- dropping response"); return false; } if (originalFromTag != null && !originalFromTag.equalsIgnoreCase(sipResponse.getFrom().getTag())) { if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) logger.logDebug("From tag mismatch -- dropping response"); return false; } } return true; } /* * (non-Javadoc) * * @see gov.nist.javax.sip.stack.ServerResponseInterface#processResponse(gov.nist.javax.sip.message.SIPResponse, * gov.nist.javax.sip.stack.MessageChannel) */ public void processResponse(SIPResponse sipResponse, MessageChannel incomingChannel) { int code = sipResponse.getStatusCode(); boolean isRetransmission = !responsesReceived.add(Integer.valueOf(code)); if(code > 100 && code < 200 && isRetransmission) { if(lastResponse != null && !sipResponse.toString().equals(lastResponse.toString())) { isRetransmission = false; } } if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { logger.logDebug( "marking response as retransmission " + isRetransmission + " for ctx " + this); } sipResponse.setRetransmission(isRetransmission); // If a dialog has already been created for this response, // pass it up. SIPDialog dialog = null; String method = sipResponse.getCSeq().getMethod(); String dialogId = sipResponse.getDialogId(false); if (method.equals(Request.CANCEL) && lastRequest != null) { // JvB for CANCEL: use invite CT in CANCEL request to get dialog // (instead of stripping tag) SIPClientTransaction ict = (SIPClientTransaction) lastRequest.getInviteTransaction(); if (ict != null) { dialog = ict.defaultDialog; } } else { dialog = this.getDialog(dialogId); } // JvB: Check all conditions required for creating a new Dialog if (dialog == null) { if ((code > 100 && code < 300) /* skip 100 (may have a to tag */ && (sipResponse.getToTag() != null || sipStack.isRfc2543Supported()) && SIPTransactionStack.isDialogCreated(method)) { /* * Dialog cannot be found for the response. This must be a forked response. no * dialog assigned to this response but a default dialog has been assigned. Note * that if automatic dialog support is configured then a default dialog is always * created. */ synchronized (this) { /* * We need synchronization here because two responses may compete for the * default dialog simultaneously */ if (defaultDialog != null) { if (sipResponse.getFromTag() != null) { String defaultDialogId = defaultDialog.getDialogId(); if (defaultDialog.getLastResponseMethod() == null || (method.equals(Request.SUBSCRIBE) && defaultDialog.getLastResponseMethod().equals( Request.NOTIFY) && defaultDialogId .equals(dialogId))) { // The default dialog has not been claimed yet. defaultDialog.setLastResponse(this, sipResponse); dialog = defaultDialog; } else { /* * check if we have created one previously (happens in the case of * REINVITE processing. JvB: should not happen, this.defaultDialog * should then get set in Dialog#sendRequest line 1662 */ dialog = sipStack.getDialog(dialogId); if (dialog == null) { if (defaultDialog.isAssigned()) { /* * Nop we dont have one. so go ahead and allocate a new * one. */ dialog = sipStack.createDialog(this, sipResponse); } } } if ( dialog != null ) { this.setDialog(dialog, dialog.getDialogId()); } else { logger.logError("dialog is unexpectedly null",new NullPointerException()); } } else { throw new RuntimeException("Response without from-tag"); } } else { // Need to create a new Dialog, this becomes default // JvB: not sure if this ever gets executed if (sipStack.isAutomaticDialogSupportEnabled) { dialog = sipStack.createDialog(this, sipResponse); this.setDialog(dialog, dialog.getDialogId()); } } } // synchronized } else { dialog = defaultDialog; } } else { // Test added to make sure the retrans flag is correct on forked responses // this will avoid setting the last response on the dialog and chnage its state // before it is passed to the dialogfilter layer where it is done as well if(TransactionState._TERMINATED != getInternalState()) { dialog.setLastResponse(this, sipResponse); } } this.processResponse(sipResponse, incomingChannel, dialog); } /* * (non-Javadoc) * * @see gov.nist.javax.sip.stack.SIPTransaction#getDialog() */ public Dialog getDialog() { // This is for backwards compatibility. Dialog retval = null; // get it in a local variable because the last response can be nullified and the if condition // can throw NPE SIPResponse localLastResponse = this.lastResponse; if(localLastResponse != null && localLastResponse.getFromTag() != null && localLastResponse.getToTag() != null && localLastResponse.getStatusCode() != 100) { String dialogId = localLastResponse.getDialogId(false); retval = (Dialog) getDialog(dialogId); } if (retval == null) { retval = (Dialog) this.getDefaultDialog(); } if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { logger.logDebug( " sipDialogs = " + sipDialogs + " default dialog " + this.getDefaultDialog() + " retval " + retval); } return retval; } /* * (non-Javadoc) * * @see gov.nist.javax.sip.stack.SIPTransaction#setDialog(gov.nist.javax.sip.stack.SIPDialog, * gov.nist.javax.sip.message.SIPMessage) */ public SIPDialog getDialog(String dialogId) { SIPDialog retval = null; if(sipDialogs != null && sipDialogs.contains(dialogId)) { retval = this.sipStack.getDialog(dialogId); if(retval == null) { retval = this.sipStack.getEarlyDialog(dialogId); } } return retval; } /* * (non-Javadoc) * * @see gov.nist.javax.sip.stack.SIPTransaction#setDialog(gov.nist.javax.sip.stack.SIPDialog, * gov.nist.javax.sip.message.SIPMessage) */ public void setDialog(SIPDialog sipDialog, String dialogId) { if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) logger.logDebug( "setDialog: " + dialogId + " sipDialog = " + sipDialog); if (sipDialog == null) { if (logger.isLoggingEnabled(LogWriter.TRACE_ERROR)) logger.logError("NULL DIALOG!!"); throw new NullPointerException("bad dialog null"); } if (this.defaultDialog == null && defaultDialogId == null) { this.defaultDialog = sipDialog; // We only deal with Forked INVITEs. if (isInviteTransaction() && this.getSIPStack().getMaxForkTime() != 0) { this.getSIPStack().addForkedClientTransaction(this); } } if (dialogId != null && sipDialog.getDialogId() != null && sipDialogs != null) { this.sipDialogs.add(dialogId); } } public SIPDialog getDefaultDialog() { SIPDialog dialog = defaultDialog; // jeand if the dialog has been nullified then get the dialog from the saved dialog id if(dialog == null && defaultDialogId != null) { dialog = this.sipStack.getDialog(defaultDialogId); } return dialog; } /** * Set the next hop ( if it has already been computed). * * @param hop -- the hop that has been previously computed. */ public void setNextHop(Hop hop) { this.nextHop = hop; } /** * Reeturn the previously computed next hop (avoid computing it twice). * * @return -- next hop previously computed. */ public Hop getNextHop() { return nextHop; } /** * Set this flag if you want your Listener to get Timeout.RETRANSMIT notifications each time a * retransmission occurs. * * @param notifyOnRetransmit the notifyOnRetransmit to set */ public void setNotifyOnRetransmit(boolean notifyOnRetransmit) { this.notifyOnRetransmit = notifyOnRetransmit; } /** * @return the notifyOnRetransmit */ public boolean isNotifyOnRetransmit() { return notifyOnRetransmit; } public void alertIfStillInCallingStateBy(int count) { this.timeoutIfStillInCallingState = true; this.callingStateTimeoutCount = count; } // jeand method use to cleanup eagerly all structures that won't be needed anymore once the tx passed in the COMPLETED state protected void cleanUpOnTimer() { if(isReleaseReferences()) { if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { logger.logDebug("cleanupOnTimer: " + getTransactionId()); } // we release the ref to the dialog asap and just keep the id of the dialog to look it up in the dialog table if(defaultDialog != null) { String dialogId = defaultDialog.getDialogId(); // we nullify the ref only if it can be find in the dialog table (not always true if the dialog is in null state, check challenge unittest of the testsuite) if(dialogId != null && sipStack.getDialog(dialogId) != null) { defaultDialogId = dialogId; defaultDialog = null; } } if(originalRequest != null) { originalRequest.setTransaction(null); originalRequest.setInviteTransaction(null); originalRequest.cleanUp(); // we keep the request in a byte array to be able to recreate it // no matter what to keep API backward compatibility if(originalRequestBytes == null) { originalRequestBytes = originalRequest.encodeAsBytes(this.getTransport()); } if(!getMethod().equalsIgnoreCase(Request.INVITE) && !getMethod().equalsIgnoreCase(Request.CANCEL)) { originalRequestFromTag = originalRequest.getFromTag(); originalRequestCallId = originalRequest.getCallId().getCallId(); originalRequestEventHeader = (Event) originalRequest.getHeader("Event"); originalRequestContact = originalRequest.getContactHeader(); originalRequestScheme = originalRequest.getRequestURI().getScheme(); originalRequest = null; } } // for subscribe Tx we need to keep the last response longer to be able to create notify from dialog if(!getMethod().equalsIgnoreCase(Request.SUBSCRIBE)) { lastResponse = null; } lastRequest = null; } } //jeand : cleanup method to clear the state of the tx once it has been removed from the stack @Override public void cleanUp() { if(isReleaseReferences()) { // release the connection associated with this transaction. if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { logger.logDebug("cleanup : " + getTransactionId()); } if(defaultDialog != null) { defaultDialogId = defaultDialog.getDialogId(); defaultDialog = null; } // we keep the request in a byte array to be able to recreate it // no matter what to keep API backward compatibility if(originalRequest != null && originalRequestBytes == null) { originalRequestBytes = originalRequest.encodeAsBytes(this.getTransport()); } originalRequest = null; cleanUpOnTimer(); // commented out because the application can hold on a ref to the tx // after it has been removed from the stack // and want to get the request or branch from it // originalRequestBytes = null; // originalRequestBranch = null; originalRequestCallId = null; originalRequestEventHeader = null; originalRequestFromTag = null; originalRequestContact = null; originalRequestScheme = null; if(sipDialogs != null) { sipDialogs.clear(); } responsesReceived.clear(); respondTo = null; transactionTimer = null; lastResponse = null; transactionTimerLock = null; // transactionTimerStarted = null; timerKStarted = null; } } // jeand cleanup called after the ctx timer or the timer k has fired protected void cleanUpOnTerminated() { if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { logger.logDebug( "removing = " + this + " isReliable " + isReliable()); } if(isReleaseReferences()) { if(originalRequest == null && originalRequestBytes != null) { try { originalRequest = (SIPRequest) sipStack.getMessageParserFactory().createMessageParser(sipStack).parseSIPMessage(originalRequestBytes, true, false, null); // originalRequestBytes = null; } catch (ParseException e) { logger.logError("message " + originalRequestBytes + " could not be reparsed !"); } } } sipStack.removeTransaction(this); // Client transaction terminated. Kill connection if // this is a TCP after the linger timer has expired. // The linger timer is needed to allow any pending requests to // return responses. if ((!sipStack.cacheClientConnections) && isReliable()) { int newUseCount = --getMessageChannel().useCount; if (newUseCount <= 0) { // Let the connection linger for a while and then close // it. SIPStackTimerTask myTimer = new LingerTimer(); sipStack.getTimer().schedule(myTimer, SIPTransactionStack.CONNECTION_LINGER_TIME * 1000); } } else { // Cache the client connections so dont close the // connection. This keeps the connection open permanently // until the client disconnects. if (logger.isLoggingEnabled() && isReliable()) { int useCount = getMessageChannel().useCount; if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) logger.logDebug("Client Use Count = " + useCount); } // Let the connection linger for a while and then close // it. if(((SipStackImpl)getSIPStack()).isReEntrantListener() && isReleaseReferences()) { cleanUp(); } // Commented out for Issue 298 : not to break backward compatibility // this piece of code was not present before aggressive optimizations // see sipx-stable-420 branch // else { // SIPStackTimerTask myTimer = new LingerTimer(); // sipStack.getTimer().schedule(myTimer, // SIPTransactionStack.CONNECTION_LINGER_TIME * 1000); // } } } /** * @return the originalRequestFromTag */ public String getOriginalRequestFromTag() { if(originalRequest == null) { return originalRequestFromTag; } return originalRequest.getFromTag(); } /** * @return the originalRequestFromTag */ public String getOriginalRequestCallId() { if(originalRequest == null) { return originalRequestCallId; } return originalRequest.getCallId().getCallId(); } /** * @return the originalRequestFromTag */ public Event getOriginalRequestEvent() { if(originalRequest == null) { return originalRequestEventHeader; } return (Event) originalRequest.getHeader(EventHeader.NAME); } /** * @return the originalRequestFromTag */ public Contact getOriginalRequestContact() { if(originalRequest == null) { return originalRequestContact; } return originalRequest.getContactHeader(); } /** * @return the originalRequestFromTag */ public String getOriginalRequestScheme() { if(originalRequest == null) { return originalRequestScheme; } return originalRequest.getRequestURI().getScheme(); } }
false
true
private void inviteClientTransaction(SIPResponse transactionResponse, MessageChannel sourceChannel, SIPDialog dialog) throws IOException { int statusCode = transactionResponse.getStatusCode(); if (TransactionState._TERMINATED == this.getInternalState()) { boolean ackAlreadySent = false; // if (dialog != null && dialog.isAckSeen() && dialog.getLastAckSent() != null) if ( dialog!= null && dialog.isAckSent(transactionResponse.getCSeq().getSeqNumber())) { if (dialog.getLastAckSent().getCSeq().getSeqNumber() == transactionResponse.getCSeq() .getSeqNumber() && transactionResponse.getFromTag().equals( dialog.getLastAckSent().getFromTag())) { // the last ack sent corresponded to this response ackAlreadySent = true; } } // retransmit the ACK for this response. if (dialog!= null && ackAlreadySent && transactionResponse.getCSeq().getMethod().equals(dialog.getMethod())) { try { // Found the dialog - resend the ACK and // dont pass up the null transaction if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) logger.logDebug("resending ACK"); dialog.resendAck(); } catch (SipException ex) { // What to do here ?? kill the dialog? } } if(dialog == null) { // http://java.net/jira/browse/JSIP-377 // The client transaction MUST be destroyed the instant it enters the // "Terminated" state. This is actually necessary to guarantee correct // operation. The reason is that 2xx responses to an INVITE are treated // differently; each one is forwarded by proxies // for proxy, it happens that there is a race condition while the tx is getting removed and TERMINATED // where some responses are still able to be handled by it so we let responses for proxies pass up to the application if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) logger.logDebug("Client Transaction " + this + " branch id " + getBranch() + " doesn't have any dialog and is in TERMINATED state"); if (respondTo != null) { if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) logger.logDebug("passing response up to the application"); respondTo.processResponse(transactionResponse, this, dialog); } else { this.semRelease(); return; } } else { this.semRelease(); return; } } else if (TransactionState._CALLING == this.getInternalState()) { if (statusCode / 100 == 2) { // JvB: do this ~before~ calling the application, to avoid // retransmissions // of the INVITE after app sends ACK disableRetransmissionTimer(); disableTimeoutTimer(); this.setState(TransactionState._TERMINATED); // 200 responses are always seen by TU. if (respondTo != null) respondTo.processResponse(transactionResponse, this, dialog); else { this.semRelease(); } } else if (statusCode / 100 == 1) { disableRetransmissionTimer(); disableTimeoutTimer(); this.setState(TransactionState._PROCEEDING); if (respondTo != null) respondTo.processResponse(transactionResponse, this, dialog); else { this.semRelease(); } } else if (300 <= statusCode && statusCode <= 699) { // Send back an ACK request try { sendMessage((SIPRequest) createErrorAck()); } catch (Exception ex) { logger.logError( "Unexpected Exception sending ACK -- sending error AcK ", ex); } /* * When in either the "Calling" or "Proceeding" states, reception of response with * status code from 300-699 MUST cause the client transaction to transition to * "Completed". The client transaction MUST pass the received response up to the * TU, and the client transaction MUST generate an ACK request. */ if (this.getDialog() != null && ((SIPDialog)this.getDialog()).isBackToBackUserAgent()) { ((SIPDialog) this.getDialog()).releaseAckSem(); } if (!isReliable()) { this.setState(TransactionState._COMPLETED); enableTimeoutTimer(TIMER_D); } else { // Proceed immediately to the TERMINATED state. this.setState(TransactionState._TERMINATED); } if (respondTo != null) { respondTo.processResponse(transactionResponse, this, dialog); } else { this.semRelease(); } cleanUpOnTimer(); } } else if (TransactionState._PROCEEDING == this.getInternalState()) { if (statusCode / 100 == 1) { if (respondTo != null) { respondTo.processResponse(transactionResponse, this, dialog); } else { this.semRelease(); } } else if (statusCode / 100 == 2) { this.setState(TransactionState._TERMINATED); if (respondTo != null) { respondTo.processResponse(transactionResponse, this, dialog); } else { this.semRelease(); } } else if (300 <= statusCode && statusCode <= 699) { // Send back an ACK request try { sendMessage((SIPRequest) createErrorAck()); } catch (Exception ex) { InternalErrorHandler.handleException(ex); } if (this.getDialog() != null) { ((SIPDialog) this.getDialog()).releaseAckSem(); } // JvB: update state before passing to app if (!isReliable()) { this.setState(TransactionState._COMPLETED); this.enableTimeoutTimer(TIMER_D); } else { this.setState(TransactionState._TERMINATED); } cleanUpOnTimer(); // Pass up to the TU for processing. if (respondTo != null) respondTo.processResponse(transactionResponse, this, dialog); else { this.semRelease(); } // JvB: duplicate with line 874 // if (!isReliable()) { // enableTimeoutTimer(TIMER_D); // } } } else if (TransactionState._COMPLETED == this.getInternalState()) { if (300 <= statusCode && statusCode <= 699) { // Send back an ACK request try { sendMessage((SIPRequest) createErrorAck()); } catch (Exception ex) { InternalErrorHandler.handleException(ex); } finally { this.semRelease(); } } } }
private void inviteClientTransaction(SIPResponse transactionResponse, MessageChannel sourceChannel, SIPDialog dialog) throws IOException { int statusCode = transactionResponse.getStatusCode(); if (TransactionState._TERMINATED == this.getInternalState()) { boolean ackAlreadySent = false; // if (dialog != null && dialog.isAckSeen() && dialog.getLastAckSent() != null) if ( dialog!= null && dialog.isAckSent(transactionResponse.getCSeq().getSeqNumber())) { if (dialog.getLastAckSent().getCSeq().getSeqNumber() == transactionResponse.getCSeq() .getSeqNumber() && transactionResponse.getFromTag().equals( dialog.getLastAckSent().getFromTag())) { // the last ack sent corresponded to this response ackAlreadySent = true; } } // retransmit the ACK for this response. if (dialog!= null && ackAlreadySent && transactionResponse.getCSeq().getMethod().equals(dialog.getMethod())) { try { // Found the dialog - resend the ACK and // dont pass up the null transaction if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) logger.logDebug("resending ACK"); dialog.resendAck(); } catch (SipException ex) { // What to do here ?? kill the dialog? } } if(dialog == null && statusCode >= 200 && statusCode < 300) { // http://java.net/jira/browse/JSIP-377 // RFC 3261 Section 17.1.1.2 // The client transaction MUST be destroyed the instant it enters the // "Terminated" state. This is actually necessary to guarantee correct // operation. The reason is that 2xx responses to an INVITE are treated // differently; each one is forwarded by proxies // for proxy, it happens that there is a race condition while the tx is getting removed and TERMINATED // where some responses are still able to be handled by it so we let 2xx responses for proxies pass up to the application if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) logger.logDebug("Client Transaction " + this + " branch id " + getBranch() + " doesn't have any dialog and is in TERMINATED state"); if (respondTo != null) { if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) logger.logDebug("passing 2xx response up to the application"); respondTo.processResponse(transactionResponse, this, dialog); } else { this.semRelease(); return; } } else { this.semRelease(); return; } } else if (TransactionState._CALLING == this.getInternalState()) { if (statusCode / 100 == 2) { // JvB: do this ~before~ calling the application, to avoid // retransmissions // of the INVITE after app sends ACK disableRetransmissionTimer(); disableTimeoutTimer(); this.setState(TransactionState._TERMINATED); // 200 responses are always seen by TU. if (respondTo != null) respondTo.processResponse(transactionResponse, this, dialog); else { this.semRelease(); } } else if (statusCode / 100 == 1) { disableRetransmissionTimer(); disableTimeoutTimer(); this.setState(TransactionState._PROCEEDING); if (respondTo != null) respondTo.processResponse(transactionResponse, this, dialog); else { this.semRelease(); } } else if (300 <= statusCode && statusCode <= 699) { // Send back an ACK request try { sendMessage((SIPRequest) createErrorAck()); } catch (Exception ex) { logger.logError( "Unexpected Exception sending ACK -- sending error AcK ", ex); } /* * When in either the "Calling" or "Proceeding" states, reception of response with * status code from 300-699 MUST cause the client transaction to transition to * "Completed". The client transaction MUST pass the received response up to the * TU, and the client transaction MUST generate an ACK request. */ if (this.getDialog() != null && ((SIPDialog)this.getDialog()).isBackToBackUserAgent()) { ((SIPDialog) this.getDialog()).releaseAckSem(); } if (!isReliable()) { this.setState(TransactionState._COMPLETED); enableTimeoutTimer(TIMER_D); } else { // Proceed immediately to the TERMINATED state. this.setState(TransactionState._TERMINATED); } if (respondTo != null) { respondTo.processResponse(transactionResponse, this, dialog); } else { this.semRelease(); } cleanUpOnTimer(); } } else if (TransactionState._PROCEEDING == this.getInternalState()) { if (statusCode / 100 == 1) { if (respondTo != null) { respondTo.processResponse(transactionResponse, this, dialog); } else { this.semRelease(); } } else if (statusCode / 100 == 2) { this.setState(TransactionState._TERMINATED); if (respondTo != null) { respondTo.processResponse(transactionResponse, this, dialog); } else { this.semRelease(); } } else if (300 <= statusCode && statusCode <= 699) { // Send back an ACK request try { sendMessage((SIPRequest) createErrorAck()); } catch (Exception ex) { InternalErrorHandler.handleException(ex); } if (this.getDialog() != null) { ((SIPDialog) this.getDialog()).releaseAckSem(); } // JvB: update state before passing to app if (!isReliable()) { this.setState(TransactionState._COMPLETED); this.enableTimeoutTimer(TIMER_D); } else { this.setState(TransactionState._TERMINATED); } cleanUpOnTimer(); // Pass up to the TU for processing. if (respondTo != null) respondTo.processResponse(transactionResponse, this, dialog); else { this.semRelease(); } // JvB: duplicate with line 874 // if (!isReliable()) { // enableTimeoutTimer(TIMER_D); // } } } else if (TransactionState._COMPLETED == this.getInternalState()) { if (300 <= statusCode && statusCode <= 699) { // Send back an ACK request try { sendMessage((SIPRequest) createErrorAck()); } catch (Exception ex) { InternalErrorHandler.handleException(ex); } finally { this.semRelease(); } } } }
diff --git a/src/main/ed/js/JSObjectBase.java b/src/main/ed/js/JSObjectBase.java index 5628eab13..a0eaf7b14 100644 --- a/src/main/ed/js/JSObjectBase.java +++ b/src/main/ed/js/JSObjectBase.java @@ -1,494 +1,494 @@ // JSObjectBase.java package ed.js; import java.io.*; import java.util.*; import ed.db.*; import ed.js.func.*; import ed.js.engine.*; public class JSObjectBase implements JSObject { static { JS._debugSIStart( "JSObjectBase" ); } static final String OBJECT_STRING = "Object"; public JSObjectBase(){ } public JSObjectBase( JSFunction constructor ){ setConstructor( constructor ); } public void prefunc(){} public Object set( Object n , Object v ){ _readOnlyCheck(); prefunc(); if ( n == null ) n = "null"; if ( v != null && v instanceof String ) v = new JSString( v.toString() ); if ( n instanceof JSString ) n = n.toString(); if ( v != null && "_id".equals( n ) && ( ( v instanceof String ) || ( v instanceof JSString ) ) ){ v = new ObjectId( v.toString() ); } if ( n instanceof String ){ String name = (String)n; if ( _map == null ){ _map = new TreeMap<String,Object>(); _keys = new ArrayList<String>(); } if ( ! ( name.equals( "__proto__" ) || name.equals( "__constructor__" ) || name.equals( "constructor" ) || name.equals( "__parent__" ) ) ) if ( ! _map.containsKey( n ) ) _keys.add( name ); _map.put( name , v ); return v; } if ( n instanceof Number ){ setInt( ((Number)n).intValue() , v ); return v; } throw new RuntimeException( "object key can't be a [" + n.getClass() + "]" ); } public Object get( Object n ){ prefunc(); if ( n == null ) n = "null"; if ( n instanceof JSString ) n = n.toString(); if ( ! "__preGet".equals( n ) ){ Object foo = _simpleGet( "__preGet" ); if ( foo != null && foo instanceof JSFunction ){ Scope s = Scope.getLastCreated(); if ( s != null ){ try { s.setThis( this ); ((JSFunction)foo).call( s , n ); } finally { s.clearThisNormal( null ); } } } } if ( n instanceof String ) return _simpleGet( (String)n ); if ( n instanceof Number ) return getInt( ((Number)n).intValue() ); throw new RuntimeException( "object key can't be a [" + n.getClass() + "]" ); } public Object _simpleGet( String s ){ Object res = null; if ( _map != null ) res = _map.get( s ); if ( res == null && _map != null ){ JSObject proto = (JSObject)_map.get( "prototype" ); if ( proto != null ) res = proto.get( s ); }; if ( res == null && _constructor != null ) res = _constructor._prototype.get( s ); if ( res == null && _objectLowFunctions != null && ( _map == null || _map.get( "prototype" ) == null ) && _constructor == null ){ res = _objectLowFunctions.get( s ); } if ( res == null && ! ( "__notFoundHandler".equals( s ) || "__preGet".equals( s ) ) ){ Object blah = _simpleGet( "__notFoundHandler" ); if ( blah instanceof JSFunction ){ JSFunction f = (JSFunction)blah; Scope scope = f.getScope(); if ( scope == null ) scope = Scope.getLastCreated(); scope = scope.child(); scope.setThis( this ); if ( ! _inNotFoundHandler.get() ){ try { _inNotFoundHandler.set( true ); return f.call( scope , s ); } finally { _inNotFoundHandler.set( false ); } } } } return res; } public Object removeField( Object n ){ if ( n == null ) return null; if ( n instanceof JSString ) n = n.toString(); Object val = null; if ( n instanceof String ){ if ( _map != null ) val = _map.remove( (String)n ); if ( _keys != null ) _keys.remove( n ); } return val; } public Object setInt( int n , Object v ){ _readOnlyCheck(); prefunc(); return set( String.valueOf( n ) , v ); } public Object getInt( int n ){ prefunc(); return get( String.valueOf( n ) ); } public boolean containsKey( String s ){ prefunc(); if ( _keys != null && _keys.contains( s ) ) return true; if ( _constructor != null && _constructor._prototype.containsKey( s ) ) return true; return false; } public Collection<String> keySet(){ prefunc(); if ( _keys == null ) return EMPTY_SET; return _keys; } public String toString(){ Object temp = get( "toString" ); if ( ! ( temp instanceof JSFunction ) ) return OBJECT_STRING; JSFunction f = (JSFunction)temp; Scope s = f.getScope().child(); s.setThis( this ); return f.call( s ).toString(); } protected void addAll( JSObject other ){ for ( String s : other.keySet() ) set( s , other.get( s ) ); } public String getJavaString( Object name ){ Object foo = get( name ); if ( foo == null ) return null; return foo.toString(); } public void setConstructor( JSFunction cons ){ setConstructor( cons , false ); } public void setConstructor( JSFunction cons , boolean exec ){ setConstructor( cons , exec , null ); } public void setConstructor( JSFunction cons , boolean exec , Object args[] ){ _readOnlyCheck(); _constructor = cons; set( "__constructor__" , _constructor ); set( "constructor" , _constructor ); set( "__proto__" , _constructor == null ? null : _constructor._prototype ); if ( _constructor != null && exec ){ Scope s = _constructor.getScope(); if ( s == null ) s = Scope.GLOBAL; s = s.child(); s.setThis( this ); _constructor.call( s , args ); } } public JSFunction getConstructor(){ return _constructor; } public JSObject getSuper(){ if ( _constructor != null && _constructor._prototype != null ) return _constructor._prototype; return (JSObject)_simpleGet( "prototype" ); } public void lock(){ setReadOnly( true ); } public void setReadOnly( boolean readOnly ){ _readOnly = readOnly; } private final void _readOnlyCheck(){ if ( _readOnly ) throw new RuntimeException( "can't modify JSObject - read only" ); } public void extend( JSObject other ){ if ( other == null ) return; for ( String key : other.keySet() ){ set( key , other.get( key ) ); } } public void debug(){ try { debug( 0 , System.out ); } catch ( IOException ioe ){ ioe.printStackTrace(); } } Appendable _space( int level , Appendable a ) throws IOException { for ( int i=0; i<level; i++ ) a.append( " " ); return a; } public void debug( int level , Appendable a ) throws IOException { _space( level , a ); a.append( "me :" ); if( _keys != null ) a.append( _keys.toString() ); a.append( "\n" ); if ( _map != null ){ JSObjectBase p = (JSObjectBase)_simpleGet( "prototype" ); if ( p != null ){ _space( level + 1 , a ).append( "prototype ||\n" ); p.debug( level + 2 , a ); } } if ( _constructor != null ){ _space( level + 1 , a ).append( "__constructor__ ||\n" ); _constructor.debug( level + 2 , a ); } } protected Map<String,Object> _map = null; private List<String> _keys = null; private JSFunction _constructor; private boolean _readOnly = false; static final Set<String> EMPTY_SET = Collections.unmodifiableSet( new HashSet<String>() ); private static class BaseThings extends JSObjectLame { BaseThings(){ init(); } public Object get( Object o ){ String name = o.toString(); return _things.get( name ); } public Object set( Object name , Object val ){ _things.put( name.toString() , val ); return val; } protected void init(){ set( "__extend" , new JSFunctionCalls1(){ public Object call( Scope s , Object other , Object args[] ){ if ( other == null ) return null; Object blah = s.getThis(); if ( ! ( blah != null && blah instanceof JSObjectBase ) ) throw new RuntimeException( "extendt not passed real thing" ); if ( ! ( other instanceof JSObject ) ) throw new RuntimeException( "can't extend with a non-object" ); ((JSObjectBase)(s.getThis())).extend( (JSObject)other ); return null; } } ); set( "__include" , new JSFunctionCalls1(){ public Object call( Scope s , Object other , Object args[] ){ if ( other == null ) return null; if ( ! ( other instanceof JSObject ) ) throw new RuntimeException( "can't include with a non-object" ); Object blah = s.getThis(); if ( ! ( blah != null && blah instanceof JSObjectBase ) ) throw new RuntimeException( "extendt not passed real thing" ); ((JSObjectBase)(s.getThis())).extend( (JSObject)other ); return null; } } ); set( "__send" , new JSFunctionCalls1(){ public Object call( Scope s , Object name , Object args[] ){ JSObject obj = ((JSObject)s.getThis()); if ( obj == null ) throw new NullPointerException( "send called on a null thing" ); JSFunction func = ((JSFunction)obj.get( name ) ); if ( func == null ){ // this is a dirty dirty hack for namespace collisions // i hate myself for even writing it in the first place func = ((JSFunction)obj.get( "__" + name ) ); } if ( func == null ) func = (JSFunction)s.get( name ); if ( func == null ) throw new NullPointerException( "can't find method [" + name + "] to send" ); return func.call( s , args ); } } ); set( "__keySet" , new JSFunctionCalls1(){ public Object call( Scope s , Object name , Object args[] ){ JSObjectBase obj = ((JSObjectBase)s.getThis()); return new JSArray( obj.keySet() ); } } ); set( "__debug" , new JSFunctionCalls1(){ public Object call( Scope s , Object name , Object args[] ){ JSObjectBase obj = ((JSObjectBase)s.getThis()); obj.debug(); return null; } } ); set( "is_a_q_" , new JSFunctionCalls1(){ public Object call( Scope s , Object type , Object args[] ){ return JSInternalFunctions.JS_instanceof( s.getThis() , type ); } } ); set( "_lb__rb_" , new JSFunctionCalls1(){ public Object call( Scope s , Object name , Object args[] ){ return ((JSObjectBase)s.getThis()).get( name ); } } ); set( "key_q_" , new JSFunctionCalls1(){ public Object call( Scope s , Object name , Object args[] ){ if ( name == null ) return null; return ((JSObjectBase)s.getThis()).containsKey( name.toString() ); } } ); - set( "__rdelete" , new JSFunctionCalls1(){ + set( "__delete" , new JSFunctionCalls1(){ public Object call( Scope s , Object name , Object args[] ){ return ((JSObjectBase)s.getThis()).removeField( name ); } } ); set( "const_defined_q_" , new JSFunctionCalls1(){ public Object call( Scope s , Object type , Object args[] ){ return s.get( type ) != null; } } ); } public Collection<String> keySet(){ return _things.keySet(); } private Map<String,Object> _things = new HashMap<String,Object>(); } public static final JSObject _objectLowFunctions = new BaseThings(); private static final ThreadLocal<Boolean> _inNotFoundHandler = new ThreadLocal<Boolean>(){ protected Boolean initialValue(){ return false; } }; }
true
true
protected void init(){ set( "__extend" , new JSFunctionCalls1(){ public Object call( Scope s , Object other , Object args[] ){ if ( other == null ) return null; Object blah = s.getThis(); if ( ! ( blah != null && blah instanceof JSObjectBase ) ) throw new RuntimeException( "extendt not passed real thing" ); if ( ! ( other instanceof JSObject ) ) throw new RuntimeException( "can't extend with a non-object" ); ((JSObjectBase)(s.getThis())).extend( (JSObject)other ); return null; } } ); set( "__include" , new JSFunctionCalls1(){ public Object call( Scope s , Object other , Object args[] ){ if ( other == null ) return null; if ( ! ( other instanceof JSObject ) ) throw new RuntimeException( "can't include with a non-object" ); Object blah = s.getThis(); if ( ! ( blah != null && blah instanceof JSObjectBase ) ) throw new RuntimeException( "extendt not passed real thing" ); ((JSObjectBase)(s.getThis())).extend( (JSObject)other ); return null; } } ); set( "__send" , new JSFunctionCalls1(){ public Object call( Scope s , Object name , Object args[] ){ JSObject obj = ((JSObject)s.getThis()); if ( obj == null ) throw new NullPointerException( "send called on a null thing" ); JSFunction func = ((JSFunction)obj.get( name ) ); if ( func == null ){ // this is a dirty dirty hack for namespace collisions // i hate myself for even writing it in the first place func = ((JSFunction)obj.get( "__" + name ) ); } if ( func == null ) func = (JSFunction)s.get( name ); if ( func == null ) throw new NullPointerException( "can't find method [" + name + "] to send" ); return func.call( s , args ); } } ); set( "__keySet" , new JSFunctionCalls1(){ public Object call( Scope s , Object name , Object args[] ){ JSObjectBase obj = ((JSObjectBase)s.getThis()); return new JSArray( obj.keySet() ); } } ); set( "__debug" , new JSFunctionCalls1(){ public Object call( Scope s , Object name , Object args[] ){ JSObjectBase obj = ((JSObjectBase)s.getThis()); obj.debug(); return null; } } ); set( "is_a_q_" , new JSFunctionCalls1(){ public Object call( Scope s , Object type , Object args[] ){ return JSInternalFunctions.JS_instanceof( s.getThis() , type ); } } ); set( "_lb__rb_" , new JSFunctionCalls1(){ public Object call( Scope s , Object name , Object args[] ){ return ((JSObjectBase)s.getThis()).get( name ); } } ); set( "key_q_" , new JSFunctionCalls1(){ public Object call( Scope s , Object name , Object args[] ){ if ( name == null ) return null; return ((JSObjectBase)s.getThis()).containsKey( name.toString() ); } } ); set( "__rdelete" , new JSFunctionCalls1(){ public Object call( Scope s , Object name , Object args[] ){ return ((JSObjectBase)s.getThis()).removeField( name ); } } ); set( "const_defined_q_" , new JSFunctionCalls1(){ public Object call( Scope s , Object type , Object args[] ){ return s.get( type ) != null; } } ); }
protected void init(){ set( "__extend" , new JSFunctionCalls1(){ public Object call( Scope s , Object other , Object args[] ){ if ( other == null ) return null; Object blah = s.getThis(); if ( ! ( blah != null && blah instanceof JSObjectBase ) ) throw new RuntimeException( "extendt not passed real thing" ); if ( ! ( other instanceof JSObject ) ) throw new RuntimeException( "can't extend with a non-object" ); ((JSObjectBase)(s.getThis())).extend( (JSObject)other ); return null; } } ); set( "__include" , new JSFunctionCalls1(){ public Object call( Scope s , Object other , Object args[] ){ if ( other == null ) return null; if ( ! ( other instanceof JSObject ) ) throw new RuntimeException( "can't include with a non-object" ); Object blah = s.getThis(); if ( ! ( blah != null && blah instanceof JSObjectBase ) ) throw new RuntimeException( "extendt not passed real thing" ); ((JSObjectBase)(s.getThis())).extend( (JSObject)other ); return null; } } ); set( "__send" , new JSFunctionCalls1(){ public Object call( Scope s , Object name , Object args[] ){ JSObject obj = ((JSObject)s.getThis()); if ( obj == null ) throw new NullPointerException( "send called on a null thing" ); JSFunction func = ((JSFunction)obj.get( name ) ); if ( func == null ){ // this is a dirty dirty hack for namespace collisions // i hate myself for even writing it in the first place func = ((JSFunction)obj.get( "__" + name ) ); } if ( func == null ) func = (JSFunction)s.get( name ); if ( func == null ) throw new NullPointerException( "can't find method [" + name + "] to send" ); return func.call( s , args ); } } ); set( "__keySet" , new JSFunctionCalls1(){ public Object call( Scope s , Object name , Object args[] ){ JSObjectBase obj = ((JSObjectBase)s.getThis()); return new JSArray( obj.keySet() ); } } ); set( "__debug" , new JSFunctionCalls1(){ public Object call( Scope s , Object name , Object args[] ){ JSObjectBase obj = ((JSObjectBase)s.getThis()); obj.debug(); return null; } } ); set( "is_a_q_" , new JSFunctionCalls1(){ public Object call( Scope s , Object type , Object args[] ){ return JSInternalFunctions.JS_instanceof( s.getThis() , type ); } } ); set( "_lb__rb_" , new JSFunctionCalls1(){ public Object call( Scope s , Object name , Object args[] ){ return ((JSObjectBase)s.getThis()).get( name ); } } ); set( "key_q_" , new JSFunctionCalls1(){ public Object call( Scope s , Object name , Object args[] ){ if ( name == null ) return null; return ((JSObjectBase)s.getThis()).containsKey( name.toString() ); } } ); set( "__delete" , new JSFunctionCalls1(){ public Object call( Scope s , Object name , Object args[] ){ return ((JSObjectBase)s.getThis()).removeField( name ); } } ); set( "const_defined_q_" , new JSFunctionCalls1(){ public Object call( Scope s , Object type , Object args[] ){ return s.get( type ) != null; } } ); }
diff --git a/continuum-core/src/main/java/org/apache/maven/continuum/buildcontroller/DefaultBuildController.java b/continuum-core/src/main/java/org/apache/maven/continuum/buildcontroller/DefaultBuildController.java index 96c1ad77e..f25301e4d 100644 --- a/continuum-core/src/main/java/org/apache/maven/continuum/buildcontroller/DefaultBuildController.java +++ b/continuum-core/src/main/java/org/apache/maven/continuum/buildcontroller/DefaultBuildController.java @@ -1,872 +1,872 @@ package org.apache.maven.continuum.buildcontroller; /* * 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 org.apache.maven.continuum.core.action.AbstractContinuumAction; import org.apache.maven.continuum.execution.ContinuumBuildExecutor; import org.apache.maven.continuum.execution.manager.BuildExecutorManager; 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.project.ProjectDependency; 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.notification.ContinuumNotificationDispatcher; import org.apache.maven.continuum.project.ContinuumProjectState; import org.apache.maven.continuum.store.ContinuumObjectNotFoundException; import org.apache.maven.continuum.store.ContinuumStore; import org.apache.maven.continuum.store.ContinuumStoreException; import org.apache.maven.continuum.utils.ContinuumUtils; import org.apache.maven.continuum.utils.WorkingDirectoryService; import org.apache.maven.scm.ScmException; import org.apache.maven.scm.repository.ScmRepositoryException; import org.codehaus.plexus.action.ActionManager; import org.codehaus.plexus.action.ActionNotFoundException; import org.codehaus.plexus.logging.AbstractLogEnabled; import org.codehaus.plexus.taskqueue.execution.TaskExecutionException; import org.codehaus.plexus.util.StringUtils; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; /** * @author <a href="mailto:[email protected]">Trygve Laugst&oslash;l</a> * @version $Id$ * @plexus.component role="org.apache.maven.continuum.buildcontroller.BuildController" role-hint="default" */ public class DefaultBuildController extends AbstractLogEnabled implements BuildController { /** * @plexus.requirement role-hint="jdo" */ private ContinuumStore store; /** * @plexus.requirement */ private ContinuumNotificationDispatcher notifierDispatcher; /** * @plexus.requirement */ private ActionManager actionManager; /** * @plexus.requirement */ private WorkingDirectoryService workingDirectoryService; /** * @plexus.requirement */ private BuildExecutorManager buildExecutorManager; // ---------------------------------------------------------------------- // BuildController Implementation // ---------------------------------------------------------------------- /** * @param projectId * @param buildDefinitionId * @param trigger * @throws TaskExecutionException */ public void build( int projectId, int buildDefinitionId, int trigger ) throws TaskExecutionException { getLogger().info( "Initializing build" ); BuildContext context = initializeBuildContext( projectId, buildDefinitionId, trigger ); getLogger().info( "Starting build of " + context.getProject().getName() ); startBuild( context ); try { // check if build definition requires smoking the existing checkout and rechecking out project if ( context.getBuildDefinition().isBuildFresh() ) { getLogger().info( "Purging exiting working copy" ); cleanWorkingDirectory( context ); } // ---------------------------------------------------------------------- // TODO: Centralize the error handling from the SCM related actions. // ContinuumScmResult should return a ContinuumScmResult from all // methods, even in a case of failure. // ---------------------------------------------------------------------- getLogger().info( "Updating working dir" ); updateWorkingDirectory( context ); getLogger().info( "Merging SCM results" ); //CONTINUUM-1393 if ( !context.getBuildDefinition().isBuildFresh() ) { mergeScmResults( context ); } // ignore this if AlwaysBuild ? if ( !checkScmResult( context ) ) { getLogger().info( "Error updating from SCM, not building" ); return; } checkProjectDependencies( context ); if ( !shouldBuild( context ) ) { return; } Map actionContext = context.getActionContext(); try { performAction( "update-project-from-working-directory", context ); } catch ( TaskExecutionException e ) { //just log the error but don't stop the build from progressing in order not to suppress any build result messages there getLogger().error( "Error executing action update-project-from-working-directory '", e ); } performAction( "execute-builder", context ); performAction( "deploy-artifact", context ); String s = (String) actionContext.get( AbstractContinuumAction.KEY_BUILD_ID ); if ( s != null ) { try { context.setBuildResult( store.getBuildResult( Integer.valueOf( s ) ) ); } catch ( NumberFormatException e ) { throw new TaskExecutionException( "Internal error: build id not an integer", e ); } catch ( ContinuumObjectNotFoundException e ) { throw new TaskExecutionException( "Internal error: Cannot find build result", e ); } catch ( ContinuumStoreException e ) { throw new TaskExecutionException( "Error loading build result", e ); } } } finally { endBuild( context ); } } /** * Checks if the build should be marked as ERROR and notifies the end of the build. * * @param context * @throws TaskExecutionException */ private void endBuild( BuildContext context ) throws TaskExecutionException { Project project = context.getProject(); try { if ( project.getState() != ContinuumProjectState.NEW && project.getState() != ContinuumProjectState.CHECKEDOUT && project.getState() != ContinuumProjectState.OK && project.getState() != ContinuumProjectState.FAILED && project.getState() != ContinuumProjectState.ERROR ) { try { String s = (String) context.getActionContext().get( AbstractContinuumAction.KEY_BUILD_ID ); if ( s != null ) { BuildResult buildResult = store.getBuildResult( Integer.valueOf( s ) ); project.setState( buildResult.getState() ); } else { project.setState( ContinuumProjectState.ERROR ); } store.updateProject( project ); } catch ( ContinuumStoreException e ) { throw new TaskExecutionException( "Error storing the project", e ); } } } finally { notifierDispatcher.buildComplete( project, context.getBuildDefinition(), context.getBuildResult() ); } } private void updateBuildResult( BuildContext context, String error ) throws TaskExecutionException { BuildResult build = context.getBuildResult(); if ( build == null ) { build = makeAndStoreBuildResult( context, error ); } else { updateBuildResult( build, context ); build.setError( error ); try { store.updateBuildResult( build ); build = store.getBuildResult( build.getId() ); context.setBuildResult( build ); } catch ( ContinuumStoreException e ) { throw new TaskExecutionException( "Error updating build result", e ); } } context.getProject().setState( build.getState() ); try { store.updateProject( context.getProject() ); } catch ( ContinuumStoreException e ) { throw new TaskExecutionException( "Error updating project", e ); } } private void updateBuildResult( BuildResult build, BuildContext context ) { if ( build.getScmResult() == null && context.getScmResult() != null ) { build.setScmResult( context.getScmResult() ); } if ( build.getModifiedDependencies() == null && context.getModifiedDependencies() != null ) { build.setModifiedDependencies( context.getModifiedDependencies() ); } } private void startBuild( BuildContext context ) throws TaskExecutionException { Project project = context.getProject(); project.setOldState( project.getState() ); project.setState( ContinuumProjectState.BUILDING ); try { store.updateProject( project ); } catch ( ContinuumStoreException e ) { throw new TaskExecutionException( "Error persisting project", e ); } notifierDispatcher.buildStarted( project, context.getBuildDefinition() ); } /** * Initializes a BuildContext for the build. * * @param projectId * @param buildDefinitionId * @param trigger * @return * @throws TaskExecutionException */ protected BuildContext initializeBuildContext( int projectId, int buildDefinitionId, int trigger ) throws TaskExecutionException { BuildContext context = new BuildContext(); context.setStartTime( System.currentTimeMillis() ); context.setTrigger( trigger ); try { context.setProject( store.getProject( projectId ) ); BuildDefinition buildDefinition = store.getBuildDefinition( buildDefinitionId ); context.setBuildDefinition( buildDefinition ); BuildResult oldBuildResult = store.getLatestBuildResultForBuildDefinition( projectId, buildDefinitionId ); context.setOldBuildResult( oldBuildResult ); if ( oldBuildResult != null ) { context.setOldScmResult( getOldScmResult( projectId, oldBuildResult.getEndTime() ) ); } } catch ( ContinuumStoreException e ) { throw new TaskExecutionException( "Error initializing the build context", e ); } Map actionContext = context.getActionContext(); actionContext.put( AbstractContinuumAction.KEY_PROJECT_ID, projectId ); actionContext.put( AbstractContinuumAction.KEY_PROJECT, context.getProject() ); actionContext.put( AbstractContinuumAction.KEY_BUILD_DEFINITION_ID, buildDefinitionId ); actionContext.put( AbstractContinuumAction.KEY_BUILD_DEFINITION, context.getBuildDefinition() ); actionContext.put( AbstractContinuumAction.KEY_TRIGGER, trigger ); actionContext.put( AbstractContinuumAction.KEY_FIRST_RUN, context.getOldBuildResult() == null ); return context; } private void cleanWorkingDirectory( BuildContext context ) throws TaskExecutionException { performAction( "clean-working-directory", context ); } private void updateWorkingDirectory( BuildContext context ) throws TaskExecutionException { Map actionContext = context.getActionContext(); performAction( "check-working-directory", context ); boolean workingDirectoryExists = AbstractContinuumAction.getBoolean( actionContext, AbstractContinuumAction.KEY_WORKING_DIRECTORY_EXISTS ); ScmResult scmResult; if ( workingDirectoryExists ) { performAction( "update-working-directory-from-scm", context ); scmResult = AbstractContinuumAction.getUpdateScmResult( actionContext, null ); } else { Project project = (Project) actionContext.get( AbstractContinuumAction.KEY_PROJECT ); actionContext.put( AbstractContinuumAction.KEY_WORKING_DIRECTORY, workingDirectoryService.getWorkingDirectory( project ).getAbsolutePath() ); performAction( "checkout-project", context ); scmResult = AbstractContinuumAction.getCheckoutResult( actionContext, null ); } context.setScmResult( scmResult ); } private void performAction( String actionName, BuildContext context ) throws TaskExecutionException { String error = null; TaskExecutionException exception = null; try { getLogger().info( "Performing action " + actionName ); actionManager.lookup( actionName ).execute( context.getActionContext() ); return; } catch ( ActionNotFoundException e ) { error = ContinuumUtils.throwableToString( e ); exception = new TaskExecutionException( "Error looking up action '" + actionName + "'", e ); } catch ( ScmRepositoryException e ) { error = getValidationMessages( e ) + "\n" + ContinuumUtils.throwableToString( e ); exception = new TaskExecutionException( "SCM error while executing '" + actionName + "'", e ); } catch ( ScmException e ) { error = ContinuumUtils.throwableToString( e ); exception = new TaskExecutionException( "SCM error while executing '" + actionName + "'", e ); } catch ( Exception e ) { exception = new TaskExecutionException( "Error executing action '" + actionName + "'", e ); error = ContinuumUtils.throwableToString( exception ); } // TODO: clean this up. We catch the original exception from the action, and then update the buildresult // for it - we need to because of the specialized error message for SCM. // If updating the buildresult fails, log the previous error and throw the new one. // If updating the buildresult succeeds, throw the original exception. The build result should NOT // be updated again - a TaskExecutionException is final, no further action should be taken upon it. try { updateBuildResult( context, error ); } catch ( TaskExecutionException e ) { getLogger().error( "Error updating build result after receiving the following exception: ", exception ); throw e; } throw exception; } protected boolean shouldBuild( BuildContext context ) throws TaskExecutionException { BuildDefinition buildDefinition = context.getBuildDefinition(); if ( buildDefinition.isAlwaysBuild() ) { getLogger().info( "AlwaysBuild configured, building" ); return true; } if ( context.getOldBuildResult() == null ) { getLogger().info( "The project was never be built with the current build definition, building" ); return true; } Project project = context.getProject(); //CONTINUUM-1428 if ( project.getOldState() == ContinuumProjectState.ERROR || context.getOldBuildResult().getState() == ContinuumProjectState.ERROR ) { getLogger().info( "Latest state was 'ERROR', building" ); return true; } - if ( context.getTrigger() != ContinuumProjectState.TRIGGER_FORCED ) + if ( context.getTrigger() == ContinuumProjectState.TRIGGER_FORCED ) { getLogger().info( "The project build is forced, building" ); return true; } boolean shouldBuild = false; boolean allChangesUnknown = true; if ( project.getOldState() != ContinuumProjectState.NEW && project.getOldState() != ContinuumProjectState.CHECKEDOUT && context.getTrigger() != ContinuumProjectState.TRIGGER_FORCED && project.getState() != ContinuumProjectState.NEW && project.getState() != ContinuumProjectState.CHECKEDOUT ) { // Check SCM changes allChangesUnknown = checkAllChangesUnknown( context.getScmResult().getChanges() ); if ( allChangesUnknown ) { if ( !context.getScmResult().getChanges().isEmpty() ) { getLogger().info( "The project was not built because all changes are unknown (maybe local modifications or ignored files not defined in your SCM tool." ); } else { getLogger().info( "The project was not built because no changes were detected in sources since the last build." ); } } // Check dependencies changes if ( context.getModifiedDependencies() != null && !context.getModifiedDependencies().isEmpty() ) { getLogger().info( "Found dependencies changes, building" ); shouldBuild = true; } } // Check changes if ( !shouldBuild && !allChangesUnknown && !context.getScmResult().getChanges().isEmpty() ) { try { ContinuumBuildExecutor executor = buildExecutorManager.getBuildExecutor( project.getExecutorId() ); shouldBuild = executor.shouldBuild( context.getScmResult().getChanges(), project, workingDirectoryService.getWorkingDirectory( project ), context.getBuildDefinition() ); } catch ( Exception e ) { throw new TaskExecutionException("Can't determine if the project should build or not", e); } } if ( shouldBuild ) { getLogger().info( "Changes found in the current project, building" ); } else { project.setState( project.getOldState() ); project.setOldState( 0 ); try { store.updateProject( project ); } catch ( ContinuumStoreException e ) { throw new TaskExecutionException( "Error storing project", e ); } getLogger().info( "No changes in the current project, not building" ); } return shouldBuild; } private boolean checkAllChangesUnknown( List<ChangeSet> changes ) { for ( ChangeSet changeSet : changes ) { List<ChangeFile> changeFiles = changeSet.getFiles(); for ( ChangeFile changeFile : changeFiles ) { if ( !"unknown".equalsIgnoreCase( changeFile.getStatus() ) ) { return false; } } } return true; } private String getValidationMessages( ScmRepositoryException ex ) { List<String> messages = ex.getValidationMessages(); StringBuffer message = new StringBuffer(); if ( messages != null && !messages.isEmpty() ) { for ( Iterator<String> i = messages.iterator(); i.hasNext(); ) { message.append( i.next() ); if ( i.hasNext() ) { message.append( System.getProperty( "line.separator" ) ); } } } return message.toString(); } protected void checkProjectDependencies( BuildContext context ) { if ( context.getOldBuildResult() == null ) { return; } try { Project project = store.getProjectWithAllDetails( context.getProject().getId() ); List<ProjectDependency> dependencies = project.getDependencies(); if ( dependencies == null ) { dependencies = new ArrayList<ProjectDependency>(); } if ( project.getParent() != null ) { dependencies.add( project.getParent() ); } if ( dependencies.isEmpty() ) { return; } List<ProjectDependency> modifiedDependencies = new ArrayList<ProjectDependency>(); for ( ProjectDependency dep : dependencies ) { Project dependencyProject = store.getProject( dep.getGroupId(), dep.getArtifactId(), dep.getVersion() ); if ( dependencyProject != null ) { List buildResults = store.getBuildResultsInSuccessForProject( dependencyProject.getId(), context.getOldBuildResult().getEndTime() ); if ( buildResults != null && !buildResults.isEmpty() ) { getLogger().debug( "Dependency changed: " + dep.getGroupId() + ":" + dep.getArtifactId() + ":" + dep.getVersion() ); modifiedDependencies.add( dep ); } else { getLogger().debug( "Dependency not changed: " + dep.getGroupId() + ":" + dep.getArtifactId() + ":" + dep.getVersion() ); } } else { getLogger().debug( "Skip non Continuum project: " + dep.getGroupId() + ":" + dep.getArtifactId() + ":" + dep.getVersion() ); } } context.setModifiedDependencies( modifiedDependencies ); context.getActionContext().put( AbstractContinuumAction.KEY_UPDATE_DEPENDENCIES, modifiedDependencies ); } catch ( ContinuumStoreException e ) { getLogger().warn( "Can't get the project dependencies", e ); } } private String convertScmResultToError( ScmResult result ) { String error = ""; if ( result == null ) { error = "Scm result is null."; } else { if ( result.getCommandLine() != null ) { error = "Command line: " + StringUtils.clean( result.getCommandLine() ) + System.getProperty( "line.separator" ); } if ( result.getProviderMessage() != null ) { error = "Provider message: " + StringUtils.clean( result.getProviderMessage() ) + System.getProperty( "line.separator" ); } if ( result.getCommandOutput() != null ) { error += "Command output: " + System.getProperty( "line.separator" ); error += "-------------------------------------------------------------------------------" + System.getProperty( "line.separator" ); error += StringUtils.clean( result.getCommandOutput() ) + System.getProperty( "line.separator" ); error += "-------------------------------------------------------------------------------" + System.getProperty( "line.separator" ); } if ( result.getException() != null ) { error += "Exception:" + System.getProperty( "line.separator" ); error += result.getException(); } } return error; } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- private BuildResult makeAndStoreBuildResult( BuildContext context, String error ) throws TaskExecutionException { // Project project, ScmResult scmResult, long startTime, int trigger ) // project, scmResult, startTime, trigger ); BuildResult build = new BuildResult(); build.setState( ContinuumProjectState.ERROR ); build.setTrigger( context.getTrigger() ); build.setStartTime( context.getStartTime() ); build.setEndTime( System.currentTimeMillis() ); updateBuildResult( build, context ); build.setScmResult( context.getScmResult() ); build.setBuildDefinition( context.getBuildDefinition() ); if ( error != null ) { build.setError( error ); } try { store.addBuildResult( context.getProject(), build ); build = store.getBuildResult( build.getId() ); context.setBuildResult( build ); return build; } catch ( ContinuumStoreException e ) { throw new TaskExecutionException( "Error storing build result", e ); } } private ScmResult getOldScmResult( int projectId, long fromDate ) { List<BuildResult> results = store.getBuildResultsForProject( projectId, fromDate ); ScmResult res = new ScmResult(); if ( results != null ) { 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; } /** * Merges scm results so we'll have all changes since last execution of current build definition * * @param context The build context */ private void mergeScmResults( BuildContext context ) { ScmResult oldScmResult = context.getOldScmResult(); ScmResult newScmResult = context.getScmResult(); if ( oldScmResult != null ) { if ( newScmResult == null ) { context.setScmResult( oldScmResult ); } else { List<ChangeSet> oldChanges = oldScmResult.getChanges(); List<ChangeSet> newChanges = newScmResult.getChanges(); for ( ChangeSet change : newChanges ) { if ( !oldChanges.contains( change ) ) { oldChanges.add( change ); } } newScmResult.setChanges( oldChanges ); } } } /** * Check to see if there was a error while checking out/updating the project * * @param context The build context * @return true if scm result is ok * @throws TaskExecutionException */ private boolean checkScmResult( BuildContext context ) throws TaskExecutionException { ScmResult scmResult = context.getScmResult(); if ( scmResult == null || !scmResult.isSuccess() ) { // scmResult must be converted before storing it because jpox modifies values of all fields to null String error = convertScmResultToError( scmResult ); BuildResult build = makeAndStoreBuildResult( context, error ); try { Project project = context.getProject(); project.setState( build.getState() ); store.updateProject( project ); return false; } catch ( ContinuumStoreException e ) { throw new TaskExecutionException( "Error storing project", e ); } } context.getActionContext().put( AbstractContinuumAction.KEY_UPDATE_SCM_RESULT, scmResult ); return true; } }
true
true
protected boolean shouldBuild( BuildContext context ) throws TaskExecutionException { BuildDefinition buildDefinition = context.getBuildDefinition(); if ( buildDefinition.isAlwaysBuild() ) { getLogger().info( "AlwaysBuild configured, building" ); return true; } if ( context.getOldBuildResult() == null ) { getLogger().info( "The project was never be built with the current build definition, building" ); return true; } Project project = context.getProject(); //CONTINUUM-1428 if ( project.getOldState() == ContinuumProjectState.ERROR || context.getOldBuildResult().getState() == ContinuumProjectState.ERROR ) { getLogger().info( "Latest state was 'ERROR', building" ); return true; } if ( context.getTrigger() != ContinuumProjectState.TRIGGER_FORCED ) { getLogger().info( "The project build is forced, building" ); return true; } boolean shouldBuild = false; boolean allChangesUnknown = true; if ( project.getOldState() != ContinuumProjectState.NEW && project.getOldState() != ContinuumProjectState.CHECKEDOUT && context.getTrigger() != ContinuumProjectState.TRIGGER_FORCED && project.getState() != ContinuumProjectState.NEW && project.getState() != ContinuumProjectState.CHECKEDOUT ) { // Check SCM changes allChangesUnknown = checkAllChangesUnknown( context.getScmResult().getChanges() ); if ( allChangesUnknown ) { if ( !context.getScmResult().getChanges().isEmpty() ) { getLogger().info( "The project was not built because all changes are unknown (maybe local modifications or ignored files not defined in your SCM tool." ); } else { getLogger().info( "The project was not built because no changes were detected in sources since the last build." ); } } // Check dependencies changes if ( context.getModifiedDependencies() != null && !context.getModifiedDependencies().isEmpty() ) { getLogger().info( "Found dependencies changes, building" ); shouldBuild = true; } } // Check changes if ( !shouldBuild && !allChangesUnknown && !context.getScmResult().getChanges().isEmpty() ) { try { ContinuumBuildExecutor executor = buildExecutorManager.getBuildExecutor( project.getExecutorId() ); shouldBuild = executor.shouldBuild( context.getScmResult().getChanges(), project, workingDirectoryService.getWorkingDirectory( project ), context.getBuildDefinition() ); } catch ( Exception e ) { throw new TaskExecutionException("Can't determine if the project should build or not", e); } } if ( shouldBuild ) { getLogger().info( "Changes found in the current project, building" ); } else { project.setState( project.getOldState() ); project.setOldState( 0 ); try { store.updateProject( project ); } catch ( ContinuumStoreException e ) { throw new TaskExecutionException( "Error storing project", e ); } getLogger().info( "No changes in the current project, not building" ); } return shouldBuild; }
protected boolean shouldBuild( BuildContext context ) throws TaskExecutionException { BuildDefinition buildDefinition = context.getBuildDefinition(); if ( buildDefinition.isAlwaysBuild() ) { getLogger().info( "AlwaysBuild configured, building" ); return true; } if ( context.getOldBuildResult() == null ) { getLogger().info( "The project was never be built with the current build definition, building" ); return true; } Project project = context.getProject(); //CONTINUUM-1428 if ( project.getOldState() == ContinuumProjectState.ERROR || context.getOldBuildResult().getState() == ContinuumProjectState.ERROR ) { getLogger().info( "Latest state was 'ERROR', building" ); return true; } if ( context.getTrigger() == ContinuumProjectState.TRIGGER_FORCED ) { getLogger().info( "The project build is forced, building" ); return true; } boolean shouldBuild = false; boolean allChangesUnknown = true; if ( project.getOldState() != ContinuumProjectState.NEW && project.getOldState() != ContinuumProjectState.CHECKEDOUT && context.getTrigger() != ContinuumProjectState.TRIGGER_FORCED && project.getState() != ContinuumProjectState.NEW && project.getState() != ContinuumProjectState.CHECKEDOUT ) { // Check SCM changes allChangesUnknown = checkAllChangesUnknown( context.getScmResult().getChanges() ); if ( allChangesUnknown ) { if ( !context.getScmResult().getChanges().isEmpty() ) { getLogger().info( "The project was not built because all changes are unknown (maybe local modifications or ignored files not defined in your SCM tool." ); } else { getLogger().info( "The project was not built because no changes were detected in sources since the last build." ); } } // Check dependencies changes if ( context.getModifiedDependencies() != null && !context.getModifiedDependencies().isEmpty() ) { getLogger().info( "Found dependencies changes, building" ); shouldBuild = true; } } // Check changes if ( !shouldBuild && !allChangesUnknown && !context.getScmResult().getChanges().isEmpty() ) { try { ContinuumBuildExecutor executor = buildExecutorManager.getBuildExecutor( project.getExecutorId() ); shouldBuild = executor.shouldBuild( context.getScmResult().getChanges(), project, workingDirectoryService.getWorkingDirectory( project ), context.getBuildDefinition() ); } catch ( Exception e ) { throw new TaskExecutionException("Can't determine if the project should build or not", e); } } if ( shouldBuild ) { getLogger().info( "Changes found in the current project, building" ); } else { project.setState( project.getOldState() ); project.setOldState( 0 ); try { store.updateProject( project ); } catch ( ContinuumStoreException e ) { throw new TaskExecutionException( "Error storing project", e ); } getLogger().info( "No changes in the current project, not building" ); } return shouldBuild; }
diff --git a/src/frontend/org/voltdb/VoltProcedure.java b/src/frontend/org/voltdb/VoltProcedure.java index d201a50ae..a3871921d 100644 --- a/src/frontend/org/voltdb/VoltProcedure.java +++ b/src/frontend/org/voltdb/VoltProcedure.java @@ -1,1413 +1,1413 @@ /* This file is part of VoltDB. * Copyright (C) 2008-2010 VoltDB L.L.C. * * VoltDB 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. * * VoltDB 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 VoltDB. If not, see <http://www.gnu.org/licenses/>. */ package org.voltdb; import java.io.IOException; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import org.voltdb.catalog.Cluster; import org.voltdb.catalog.PlanFragment; import org.voltdb.catalog.ProcParameter; import org.voltdb.catalog.Procedure; import org.voltdb.catalog.Statement; import org.voltdb.catalog.StmtParameter; import org.voltdb.dtxn.DtxnConstants; import org.voltdb.dtxn.TransactionState; import org.voltdb.exceptions.EEException; import org.voltdb.exceptions.SerializableException; import org.voltdb.logging.VoltLogger; import org.voltdb.messaging.FastSerializer; import org.voltdb.messaging.FragmentTaskMessage; import org.voltdb.types.TimestampType; import org.voltdb.types.VoltDecimalHelper; import org.voltdb.utils.CatalogUtil; /** * Wraps the stored procedure object created by the user * with metadata available at runtime. This is used to call * the procedure. * * VoltProcedure is extended by all running stored procedures. * Consider this when specifying access privileges. * */ public abstract class VoltProcedure { private static final VoltLogger log = new VoltLogger(VoltProcedure.class.getName()); // Used to get around the "abstract" for StmtProcedures. // Path of least resistance? static class StmtProcedure extends VoltProcedure {} // This must match MAX_BATCH_COUNT in src/ee/execution/VoltDBEngine.h final static int MAX_BATCH_SIZE = 1000; final static Double DOUBLE_NULL = new Double(-1.7976931348623157E+308); public static final String ANON_STMT_NAME = "sql"; protected HsqlBackend hsql; final private ProcedureProfiler profiler = new ProcedureProfiler(); //For runtime statistics collection private ProcedureStatsCollector statsCollector; // package scoped members used by VoltSystemProcedure Cluster m_cluster; SiteProcedureConnection m_site; TransactionState m_currentTxnState; // assigned in call() /** * Allow VoltProcedures access to their transaction id. * @return transaction id */ public long getTransactionId() { return m_currentTxnState.txnId; } private boolean m_initialized; // private members reserved exclusively to VoltProcedure private Method procMethod; private Class<?>[] paramTypes; private boolean paramTypeIsPrimitive[]; private boolean paramTypeIsArray[]; private Class<?> paramTypeComponentType[]; private int paramTypesLength; private Procedure catProc; private boolean isNative = true; private int numberOfPartitions; // cached fake SQLStmt array for single statement non-java procs SQLStmt[] m_cachedSingleStmt = { null }; // Workload Trace Handles private Object m_workloadXactHandle = null; private Integer m_workloadBatchId = null; private Set<Object> m_workloadQueryHandles; // data copied from EE proc wrapper private final SQLStmt batchQueryStmts[] = new SQLStmt[MAX_BATCH_SIZE]; private int batchQueryStmtIndex = 0; private Object[] batchQueryArgs[]; private int batchQueryArgsIndex = 0; private final long fragmentIds[] = new long[MAX_BATCH_SIZE]; private final int expectedDeps[] = new int[MAX_BATCH_SIZE]; private ParameterSet parameterSets[]; /** * Status code that can be set by stored procedure upon invocation that will be returned with the response. */ private byte m_statusCode = Byte.MIN_VALUE; private String m_statusString = null; // data from hsql wrapper private final ArrayList<VoltTable> queryResults = new ArrayList<VoltTable>(); // cached txnid-seeded RNG so all calls to getSeededRandomNumberGenerator() for // a given call don't re-seed and generate the same number over and over private Random m_cachedRNG = null; /** * End users should not instantiate VoltProcedure instances. * Constructor does nothing. All actual initialization is done in the * {@link VoltProcedure init} method. */ public VoltProcedure() {} /** * End users should not call this method. * Used by the VoltDB runtime to initialize stored procedures for execution. */ public void init( int numberOfPartitions, SiteProcedureConnection site, Procedure catProc, BackendTarget eeType, HsqlBackend hsql, Cluster cluster) { if (m_initialized) { throw new IllegalStateException("VoltProcedure has already been initialized"); } else { m_initialized = true; } this.catProc = catProc; this.m_site = site; this.isNative = (eeType != BackendTarget.HSQLDB_BACKEND); this.hsql = hsql; this.m_cluster = cluster; this.numberOfPartitions = numberOfPartitions; statsCollector = new ProcedureStatsCollector(); VoltDB.instance().getStatsAgent().registerStatsSource( SysProcSelector.PROCEDURE, Integer.parseInt(site.getCorrespondingCatalogSite().getTypeName()), statsCollector); // this is a stupid hack to make the EE happy for (int i = 0; i < expectedDeps.length; i++) expectedDeps[i] = 1; if (catProc.getHasjava()) { int tempParamTypesLength = 0; Method tempProcMethod = null; Method[] methods = getClass().getMethods(); Class<?> tempParamTypes[] = null; boolean tempParamTypeIsPrimitive[] = null; boolean tempParamTypeIsArray[] = null; Class<?> tempParamTypeComponentType[] = null; for (final Method m : methods) { String name = m.getName(); if (name.equals("run")) { //inspect(m); tempProcMethod = m; tempParamTypes = tempProcMethod.getParameterTypes(); tempParamTypesLength = tempParamTypes.length; tempParamTypeIsPrimitive = new boolean[tempParamTypesLength]; tempParamTypeIsArray = new boolean[tempParamTypesLength]; tempParamTypeComponentType = new Class<?>[tempParamTypesLength]; for (int ii = 0; ii < tempParamTypesLength; ii++) { tempParamTypeIsPrimitive[ii] = tempParamTypes[ii].isPrimitive(); tempParamTypeIsArray[ii] = tempParamTypes[ii].isArray(); tempParamTypeComponentType[ii] = tempParamTypes[ii].getComponentType(); } } } paramTypesLength = tempParamTypesLength; procMethod = tempProcMethod; paramTypes = tempParamTypes; paramTypeIsPrimitive = tempParamTypeIsPrimitive; paramTypeIsArray = tempParamTypeIsArray; paramTypeComponentType = tempParamTypeComponentType; if (procMethod == null) { log.debug("No good method found in: " + getClass().getName()); } Field[] fields = getClass().getFields(); for (final Field f : fields) { if (f.getType() == SQLStmt.class) { String name = f.getName(); Statement s = catProc.getStatements().get(name); if (s != null) { try { /* * Cache all the information we need about the statements in this stored * procedure locally instead of pulling them from the catalog on * a regular basis. */ SQLStmt stmt = (SQLStmt) f.get(this); stmt.catStmt = s; initSQLStmt(stmt); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } //LOG.fine("Found statement " + name); } } } } // has no java else { Statement catStmt = catProc.getStatements().get(ANON_STMT_NAME); SQLStmt stmt = new SQLStmt(catStmt.getSqltext()); stmt.catStmt = catStmt; initSQLStmt(stmt); m_cachedSingleStmt[0] = stmt; procMethod = null; paramTypesLength = catProc.getParameters().size(); paramTypes = new Class<?>[paramTypesLength]; paramTypeIsPrimitive = new boolean[paramTypesLength]; paramTypeIsArray = new boolean[paramTypesLength]; paramTypeComponentType = new Class<?>[paramTypesLength]; for (ProcParameter param : catProc.getParameters()) { VoltType type = VoltType.get((byte) param.getType()); if (type == VoltType.INTEGER) type = VoltType.BIGINT; if (type == VoltType.SMALLINT) type = VoltType.BIGINT; if (type == VoltType.TINYINT) type = VoltType.BIGINT; paramTypes[param.getIndex()] = type.classFromType(); paramTypeIsPrimitive[param.getIndex()] = paramTypes[param.getIndex()].isPrimitive(); paramTypeIsArray[param.getIndex()] = param.getIsarray(); assert(paramTypeIsArray[param.getIndex()] == false); paramTypeComponentType[param.getIndex()] = null; } } } final void initSQLStmt(SQLStmt stmt) { stmt.numFragGUIDs = stmt.catStmt.getFragments().size(); PlanFragment fragments[] = new PlanFragment[stmt.numFragGUIDs]; stmt.fragGUIDs = new long[stmt.numFragGUIDs]; int i = 0; for (PlanFragment frag : stmt.catStmt.getFragments()) { fragments[i] = frag; stmt.fragGUIDs[i] = CatalogUtil.getUniqueIdForFragment(frag); i++; } stmt.numStatementParamJavaTypes = stmt.catStmt.getParameters().size(); //StmtParameter parameters[] = new StmtParameter[stmt.numStatementParamJavaTypes]; stmt.statementParamJavaTypes = new byte[stmt.numStatementParamJavaTypes]; for (StmtParameter param : stmt.catStmt.getParameters()) { //parameters[i] = param; stmt.statementParamJavaTypes[param.getIndex()] = (byte)param.getJavatype(); i++; } } /* Package private but not final, to enable mock volt procedure objects */ ClientResponseImpl call(TransactionState txnState, Object... paramList) { m_currentTxnState = txnState; m_statusCode = Byte.MIN_VALUE; m_statusString = null; // kill the cache of the rng m_cachedRNG = null; if (ProcedureProfiler.profilingLevel != ProcedureProfiler.Level.DISABLED) { profiler.startCounter(catProc); } statsCollector.beginProcedure(); // in case sql was queued but executed batchQueryStmtIndex = 0; batchQueryArgsIndex = 0; VoltTable[] results = new VoltTable[0]; byte status = ClientResponseImpl.SUCCESS; if (paramList.length != paramTypesLength) { statsCollector.endProcedure( false, true); String msg = "PROCEDURE " + catProc.getTypeName() + " EXPECTS " + String.valueOf(paramTypesLength) + " PARAMS, BUT RECEIVED " + String.valueOf(paramList.length); status = ClientResponseImpl.GRACEFUL_FAILURE; return getErrorResponse(status, msg, null); } for (int i = 0; i < paramTypesLength; i++) { try { paramList[i] = tryToMakeCompatible( i, paramList[i]); } catch (Exception e) { statsCollector.endProcedure( false, true); String msg = "PROCEDURE " + catProc.getTypeName() + " TYPE ERROR FOR PARAMETER " + i + ": " + e.getMessage(); status = ClientResponseImpl.GRACEFUL_FAILURE; return getErrorResponse(status, msg, null); } } // Workload Trace // Create a new transaction record in the trace manager. This will give us back // a handle that we need to pass to the trace manager when we want to register a new query if ((ProcedureProfiler.profilingLevel == ProcedureProfiler.Level.INTRUSIVE) && (ProcedureProfiler.workloadTrace != null)) { m_workloadQueryHandles = new HashSet<Object>(); m_workloadXactHandle = ProcedureProfiler.workloadTrace.startTransaction(this, catProc, paramList); } ClientResponseImpl retval = null; boolean error = false; boolean abort = false; // run a regular java class if (catProc.getHasjava()) { try { if (log.isTraceEnabled()) { log.trace("invoking... procMethod=" + procMethod.getName() + ", class=" + getClass().getName()); } try { batchQueryArgs = new Object[MAX_BATCH_SIZE][]; parameterSets = new ParameterSet[MAX_BATCH_SIZE]; Object rawResult = procMethod.invoke(this, paramList); results = getResultsFromRawResults(rawResult); } catch (IllegalAccessException e) { // If reflection fails, invoke the same error handling that other exceptions do throw new InvocationTargetException(e); } finally { batchQueryArgs = null; parameterSets = null; } log.trace("invoked"); } catch (InvocationTargetException itex) { //itex.printStackTrace(); Throwable ex = itex.getCause(); if (ex instanceof VoltAbortException && !(ex instanceof EEException)) { abort = true; } else { error = true; } if (ex instanceof Error) { statsCollector.endProcedure( false, true); throw (Error)ex; } retval = getErrorResponse(ex); } } // single statement only work // (this could be made faster, but with less code re-use) else { assert(catProc.getStatements().size() == 1); try { batchQueryArgs = new Object[MAX_BATCH_SIZE][]; parameterSets = new ParameterSet[MAX_BATCH_SIZE]; if (!isNative) { // HSQL handling VoltTable table = hsql.runSQLWithSubstitutions(m_cachedSingleStmt[0], paramList); results = new VoltTable[] { table }; } else { results = executeQueriesInABatch(1, m_cachedSingleStmt, new Object[][] { paramList } , true); } } catch (SerializableException ex) { retval = getErrorResponse(ex); } finally { batchQueryArgs = null; parameterSets = null; } } if (ProcedureProfiler.profilingLevel != ProcedureProfiler.Level.DISABLED) profiler.stopCounter(); statsCollector.endProcedure( abort, error); // Workload Trace - Stop the transaction trace record. if ((ProcedureProfiler.profilingLevel == ProcedureProfiler.Level.INTRUSIVE) && (ProcedureProfiler.workloadTrace != null && m_workloadXactHandle != null)) { ProcedureProfiler.workloadTrace.stopTransaction(m_workloadXactHandle); } if (retval == null) retval = new ClientResponseImpl( status, m_statusCode, m_statusString, results, null); return retval; } /** * Given the results of a procedure, convert it into a sensible array of VoltTables. * @throws InvocationTargetException */ final private VoltTable[] getResultsFromRawResults(Object result) throws InvocationTargetException { if (result == null) { return new VoltTable[0]; } if (result instanceof VoltTable[]) { VoltTable[] retval = (VoltTable[]) result; for (VoltTable table : retval) if (table == null) { Exception e = new RuntimeException("VoltTable arrays with non-zero length cannot contain null values."); throw new InvocationTargetException(e); } return retval; } if (result instanceof VoltTable) { return new VoltTable[] { (VoltTable) result }; } if (result instanceof Long) { VoltTable t = new VoltTable(new VoltTable.ColumnInfo("", VoltType.BIGINT)); t.addRow(result); return new VoltTable[] { t }; } throw new RuntimeException("Procedure didn't return acceptable type."); } /** @throws Exception with a message describing why the types are incompatible. */ final private Object tryToMakeCompatible(int paramTypeIndex, Object param) throws Exception { if (param == null || param == VoltType.NULL_STRING || param == VoltType.NULL_DECIMAL) { if (paramTypeIsPrimitive[paramTypeIndex]) { VoltType type = VoltType.typeFromClass(paramTypes[paramTypeIndex]); switch (type) { case TINYINT: case SMALLINT: case INTEGER: case BIGINT: case FLOAT: return type.getNullValue(); } } // Pass null reference to the procedure run() method. These null values will be // converted to a serialize-able NULL representation for the EE in getCleanParams() // when the parameters are serialized for the plan fragment. return null; } if (param instanceof ExecutionSite.SystemProcedureExecutionContext) { return param; } Class<?> pclass = param.getClass(); boolean slotIsArray = paramTypeIsArray[paramTypeIndex]; if (slotIsArray != pclass.isArray()) throw new Exception("Array / Scalar parameter mismatch"); if (slotIsArray) { Class<?> pSubCls = pclass.getComponentType(); Class<?> sSubCls = paramTypeComponentType[paramTypeIndex]; if (pSubCls == sSubCls) { return param; } // if it's an empty array, let it through // this is a bit ugly as it might hide passing // arrays of the wrong type, but it "does the right thing" // more often that not I guess... else if (Array.getLength(param) == 0) { return Array.newInstance(sSubCls, 0); } else { /* * Arrays can be quite large so it doesn't make sense to silently do the conversion * and incur the performance hit. The client should serialize the correct invocation * parameters */ throw new Exception( "tryScalarMakeCompatible: Unable to match parameter array:" + sSubCls.getName() + " to provided " + pSubCls.getName()); } } /* * inline tryScalarMakeCompatible so we can save on reflection */ final Class<?> slot = paramTypes[paramTypeIndex]; if ((slot == long.class) && (pclass == Long.class || pclass == Integer.class || pclass == Short.class || pclass == Byte.class)) return param; if ((slot == int.class) && (pclass == Integer.class || pclass == Short.class || pclass == Byte.class)) return param; if ((slot == short.class) && (pclass == Short.class || pclass == Byte.class)) return param; if ((slot == byte.class) && (pclass == Byte.class)) return param; if ((slot == double.class) && (param instanceof Number)) return ((Number)param).doubleValue(); if ((slot == String.class) && (pclass == String.class)) return param; if (slot == TimestampType.class) { if (pclass == Long.class) return new TimestampType((Long)param); if (pclass == TimestampType.class) return param; // if a string is given for a date, use java's JDBC parsing if (pclass == String.class) { try { java.sql.Timestamp sqlTS = java.sql.Timestamp.valueOf((String) param); long timeInMicroSecs = sqlTS.getTime() * 1000; timeInMicroSecs += sqlTS.getNanos() / 1000; return new TimestampType(timeInMicroSecs); } // ignore errors if it's not the right format catch (IllegalArgumentException e) {} } } if (slot == BigDecimal.class) { if ((pclass == Long.class) || (pclass == Integer.class) || (pclass == Short.class) || (pclass == Byte.class)) { BigInteger bi = new BigInteger(param.toString()); BigDecimal bd = new BigDecimal(bi); bd.setScale(4, BigDecimal.ROUND_HALF_EVEN); return bd; } if (pclass == BigDecimal.class) { BigDecimal bd = (BigDecimal) param; bd.setScale(4, BigDecimal.ROUND_HALF_EVEN); return bd; } if (pclass == String.class) { BigDecimal bd = VoltDecimalHelper.deserializeBigDecimalFromString((String) param); return bd; } } if (slot == VoltTable.class && pclass == VoltTable.class) { return param; } // handle truncation for integers // Long targeting int parameter if ((slot == int.class) && (pclass == Long.class)) { long val = ((Number) param).longValue(); // if it's in the right range, and not null (target null), crop the value and return if ((val <= Integer.MAX_VALUE) && (val >= Integer.MIN_VALUE) && (val != VoltType.NULL_INTEGER)) return ((Number) param).intValue(); } // Long or Integer targeting short parameter if ((slot == short.class) && (pclass == Long.class || pclass == Integer.class)) { long val = ((Number) param).longValue(); // if it's in the right range, and not null (target null), crop the value and return if ((val <= Short.MAX_VALUE) && (val >= Short.MIN_VALUE) && (val != VoltType.NULL_SMALLINT)) return ((Number) param).shortValue(); } // Long, Integer or Short targeting byte parameter if ((slot == byte.class) && (pclass == Long.class || pclass == Integer.class || pclass == Short.class)) { long val = ((Number) param).longValue(); // if it's in the right range, and not null (target null), crop the value and return if ((val <= Byte.MAX_VALUE) && (val >= Byte.MIN_VALUE) && (val != VoltType.NULL_TINYINT)) return ((Number) param).byteValue(); } throw new Exception( "tryToMakeCompatible: Unable to match parameters or out of range for taget param: " + slot.getName() + " to provided " + pclass.getName()); } /** * Thrown from a stored procedure to indicate to VoltDB * that the procedure should be aborted and rolled back. */ public static class VoltAbortException extends RuntimeException { private static final long serialVersionUID = -1L; private String message = "No message specified."; /** * Constructs a new <code>AbortException</code> */ public VoltAbortException() {} /** * Constructs a new <code>AbortException</code> with the specified detail message. */ public VoltAbortException(String msg) { message = msg; } /** * Returns the detail message string of this <tt>AbortException</tt> * * @return The detail message. */ @Override public String getMessage() { return message; } } /** * Currently unsupported in VoltDB. * Batch load method for populating a table with a large number of records. * * Faster then calling {@link #voltQueueSQL(SQLStmt, Object...)} and {@link #voltExecuteSQL()} to * insert one row at a time. * @param clusterName Name of the cluster containing the database, containing the table * that the records will be loaded in. * @param databaseName Name of the database containing the table to be loaded. * @param tableName Name of the table records should be loaded in. * @param data {@link org.voltdb.VoltTable VoltTable} containing the records to be loaded. * {@link org.voltdb.VoltTable.ColumnInfo VoltTable.ColumnInfo} schema must match the schema of the table being * loaded. * @throws VoltAbortException */ public void voltLoadTable(String clusterName, String databaseName, String tableName, VoltTable data, int allowELT) throws VoltAbortException { if (data == null || data.getRowCount() == 0) { return; } try { m_site.loadTable(m_currentTxnState.txnId, clusterName, databaseName, tableName, data, allowELT); } catch (EEException e) { throw new VoltAbortException("Failed to load table: " + tableName); } } /** * Get a Java RNG seeded with the current transaction id. This will ensure that * two procedures for the same transaction, but running on different replicas, * can generate an identical stream of random numbers. This is required to endure * procedures have deterministic behavior. * * @return A deterministically-seeded java.util.Random instance. */ public Random getSeededRandomNumberGenerator() { // this value is memoized here and reset at the beginning of call(...). if (m_cachedRNG == null) { m_cachedRNG = new Random(m_currentTxnState.txnId); } return m_cachedRNG; } /** * Get the time that this procedure was accepted into the VoltDB cluster. This is the * effective, but not always actual, moment in time this procedure executes. Use this * method to get the current time instead of non-deterministic methods. Note that the * value will not be unique across transactions as it is only millisecond granularity. * * @return A java.util.Date instance with deterministic time for all replicas using * UTC (Universal Coordinated Time is like GMT). */ public Date getTransactionTime() { long ts = TransactionIdManager.getTimestampFromTransactionId(m_currentTxnState.txnId); return new Date(ts); } /** * Queue the SQL {@link org.voltdb.SQLStmt statement} for execution with the specified argument list. * * @param stmt {@link org.voltdb.SQLStmt Statement} to queue for execution. * @param args List of arguments to be bound as parameters for the {@link org.voltdb.SQLStmt statement} * @see <a href="#allowable_params">List of allowable parameter types</a> */ public void voltQueueSQL(final SQLStmt stmt, Object... args) { if (!isNative) { //HSQLProcedureWrapper does nothing smart. it just implements this interface with runStatement() VoltTable table = hsql.runSQLWithSubstitutions(stmt, args); queryResults.add(table); return; } if (batchQueryStmtIndex == batchQueryStmts.length) { throw new RuntimeException("Procedure attempted to queue more than " + batchQueryStmts.length + " statements in a batch."); } else { batchQueryStmts[batchQueryStmtIndex++] = stmt; batchQueryArgs[batchQueryArgsIndex++] = args; } } /** * Execute the currently queued SQL {@link org.voltdb.SQLStmt statements} and return * the result tables. * * @return Result {@link org.voltdb.VoltTable tables} generated by executing the queued * query {@link org.voltdb.SQLStmt statements} */ public VoltTable[] voltExecuteSQL() { return voltExecuteSQL(false); } /** * Execute the currently queued SQL {@link org.voltdb.SQLStmt statements} and return * the result tables. Boolean option allows caller to indicate if this is the final * batch for a procedure. If it's final, then additional optimizatons can be enabled. * * @param isFinalSQL Is this the final batch for a procedure? * @return Result {@link org.voltdb.VoltTable tables} generated by executing the queued * query {@link org.voltdb.SQLStmt statements} */ public VoltTable[] voltExecuteSQL(boolean isFinalSQL) { if (!isNative) { VoltTable[] batch_results = queryResults.toArray(new VoltTable[queryResults.size()]); queryResults.clear(); return batch_results; } assert (batchQueryStmtIndex == batchQueryArgsIndex); // if profiling is turned on, record the sql statements being run if (ProcedureProfiler.profilingLevel == ProcedureProfiler.Level.INTRUSIVE) { // Workload Trace - Start Query if (ProcedureProfiler.workloadTrace != null && m_workloadXactHandle != null) { m_workloadBatchId = ProcedureProfiler.workloadTrace.getNextBatchId(m_workloadXactHandle); for (int i = 0; i < batchQueryStmtIndex; i++) { Object queryHandle = ProcedureProfiler.workloadTrace.startQuery( m_workloadXactHandle, batchQueryStmts[i].catStmt, batchQueryArgs[i], m_workloadBatchId); m_workloadQueryHandles.add(queryHandle); } } } VoltTable[] retval = null; if (ProcedureProfiler.profilingLevel == ProcedureProfiler.Level.INTRUSIVE) { retval = executeQueriesInIndividualBatches(batchQueryStmtIndex, batchQueryStmts, batchQueryArgs, isFinalSQL); } else if (catProc.getSinglepartition() == false) { // check for duplicate sql statements // if so, do them individually for now boolean duplicate = false; for (int i = 0; i < batchQueryStmtIndex; i++) { for (int j = i + 1; i < batchQueryStmtIndex; i++) { if (batchQueryStmts[i] == batchQueryStmts[j]) duplicate = true; } } if (duplicate) { retval = executeQueriesInIndividualBatches( batchQueryStmtIndex, batchQueryStmts, batchQueryArgs, isFinalSQL); } else { retval = executeQueriesInABatch( batchQueryStmtIndex, batchQueryStmts, batchQueryArgs, isFinalSQL); } } else { retval = executeQueriesInABatch( batchQueryStmtIndex, batchQueryStmts, batchQueryArgs, isFinalSQL); } // Workload Trace - Stop Query if (ProcedureProfiler.profilingLevel == ProcedureProfiler.Level.INTRUSIVE) { if (ProcedureProfiler.workloadTrace != null) { for (Object handle : m_workloadQueryHandles) { if (handle != null) ProcedureProfiler.workloadTrace.stopQuery(handle); } // Make sure that we clear out our query handles so that the next // time they queue a query they will get a new batch id m_workloadQueryHandles.clear(); } } batchQueryStmtIndex = 0; batchQueryArgsIndex = 0; return retval; } private VoltTable[] executeQueriesInIndividualBatches(int stmtCount, SQLStmt[] batchStmts, Object[][] batchArgs, boolean finalTask) { assert(stmtCount > 0); assert(batchStmts != null); assert(batchArgs != null); VoltTable[] retval = new VoltTable[stmtCount]; for (int i = 0; i < stmtCount; i++) { assert(batchStmts[i] != null); assert(batchArgs[i] != null); SQLStmt[] subBatchStmts = new SQLStmt[1]; Object[][] subBatchArgs = new Object[1][]; subBatchStmts[0] = batchStmts[i]; subBatchArgs[0] = batchArgs[i]; boolean isThisLoopFinalTask = finalTask && (i == (stmtCount - 1)); VoltTable[] results = executeQueriesInABatch(1, subBatchStmts, subBatchArgs, isThisLoopFinalTask); assert(results != null); assert(results.length == 1); retval[i] = results[0]; } return retval; } private VoltTable[] executeQueriesInABatch(int stmtCount, SQLStmt[] batchStmts, Object[][] batchArgs, boolean finalTask) { assert(batchStmts != null); assert(batchArgs != null); assert(batchStmts.length > 0); assert(batchArgs.length > 0); if (stmtCount == 0) return new VoltTable[] {}; if (ProcedureProfiler.profilingLevel == ProcedureProfiler.Level.INTRUSIVE) { assert(batchStmts.length == 1); assert(batchStmts[0].numFragGUIDs == 1); ProcedureProfiler.startStatementCounter(batchStmts[0].fragGUIDs[0]); } else ProcedureProfiler.startStatementCounter(-1); final int batchSize = stmtCount; int fragmentIdIndex = 0; int parameterSetIndex = 0; boolean slowPath = false; for (int i = 0; i < batchSize; ++i) { final SQLStmt stmt = batchStmts[i]; // check if the statement has been oked by the compiler/loader if (stmt.catStmt == null) { String msg = "SQLStmt objects cannot be instantiated after"; msg += " VoltDB initialization. User may have instantiated a SQLStmt"; msg += " inside a stored procedure's run method."; throw new RuntimeException(msg); } // if any stmt is not single sited in this batch, the // full batch must take the slow path through the dtxn slowPath = slowPath || !(stmt.catStmt.getSinglepartition()); final Object[] args = batchArgs[i]; // check all the params final ParameterSet params = getCleanParams(stmt, args); final int numFrags = stmt.numFragGUIDs; final long fragGUIDs[] = stmt.fragGUIDs; for (int ii = 0; ii < numFrags; ii++) { fragmentIds[fragmentIdIndex++] = fragGUIDs[ii]; parameterSets[parameterSetIndex++] = params; } } if (slowPath) { return slowPath(batchSize, batchStmts, batchArgs, finalTask); } VoltTable[] results = null; try { results = m_site.executeQueryPlanFragmentsAndGetResults( fragmentIds, fragmentIdIndex, parameterSets, parameterSetIndex, m_currentTxnState.txnId, catProc.getReadonly()); } finally { ProcedureProfiler.stopStatementCounter(); } return results; } private ParameterSet getCleanParams(SQLStmt stmt, Object[] args) { final int numParamTypes = stmt.numStatementParamJavaTypes; final byte stmtParamTypes[] = stmt.statementParamJavaTypes; if (args.length != numParamTypes) { throw new ExpectedProcedureException( "Number of arguments provided was " + args.length + " where " + numParamTypes + " was expected for statement " + stmt.getText()); } for (int ii = 0; ii < numParamTypes; ii++) { // this only handles null values if (args[ii] != null) continue; VoltType type = VoltType.get(stmtParamTypes[ii]); if (type == VoltType.TINYINT) args[ii] = Byte.MIN_VALUE; else if (type == VoltType.SMALLINT) args[ii] = Short.MIN_VALUE; else if (type == VoltType.INTEGER) args[ii] = Integer.MIN_VALUE; else if (type == VoltType.BIGINT) args[ii] = Long.MIN_VALUE; else if (type == VoltType.FLOAT) args[ii] = DOUBLE_NULL; else if (type == VoltType.TIMESTAMP) args[ii] = new TimestampType(Long.MIN_VALUE); else if (type == VoltType.STRING) args[ii] = VoltType.NULL_STRING; else if (type == VoltType.DECIMAL) args[ii] = VoltType.NULL_DECIMAL; else throw new ExpectedProcedureException("Unknown type " + type + " can not be converted to NULL representation for arg " + ii + " for SQL stmt " + stmt.getText()); } final ParameterSet params = new ParameterSet(true); params.setParameters(args); return params; } /** * Derivation of StatsSource to expose timing information of procedure invocations. * */ private final class ProcedureStatsCollector extends SiteStatsSource { /** * Record procedure execution time ever N invocations */ final int timeCollectionInterval = 20; /** * Number of times this procedure has been invoked. */ private long m_invocations = 0; private long m_lastInvocations = 0; /** * Number of timed invocations */ private long m_timedInvocations = 0; private long m_lastTimedInvocations = 0; /** * Total amount of timed execution time */ private long m_totalTimedExecutionTime = 0; private long m_lastTotalTimedExecutionTime = 0; /** * Shortest amount of time this procedure has executed in */ private long m_minExecutionTime = Long.MAX_VALUE; private long m_lastMinExecutionTime = Long.MAX_VALUE; /** * Longest amount of time this procedure has executed in */ private long m_maxExecutionTime = Long.MIN_VALUE; private long m_lastMaxExecutionTime = Long.MIN_VALUE; /** * Time the procedure was last started */ private long m_currentStartTime = -1; /** * Count of the number of aborts (user initiated or DB initiated) */ private long m_abortCount = 0; private long m_lastAbortCount = 0; /** * Count of the number of errors that occured during procedure execution */ private long m_failureCount = 0; private long m_lastFailureCount = 0; /** * Whether to return results in intervals since polling or since the beginning */ private boolean m_interval = false; /** * Constructor requires no args because it has access to the enclosing classes members. */ public ProcedureStatsCollector() { super(m_site.getCorrespondingSiteId() + " " + catProc.getClassname(), m_site.getCorrespondingSiteId(), false); } /** * Called when a procedure begins executing. Caches the time the procedure starts. */ public final void beginProcedure() { if (m_invocations % timeCollectionInterval == 0) { m_currentStartTime = System.nanoTime(); } } /** * Called after a procedure is finished executing. Compares the start and end time and calculates * the statistics. */ public final void endProcedure(boolean aborted, boolean failed) { if (m_currentStartTime > 0) { final long endTime = System.nanoTime(); final int delta = (int)(endTime - m_currentStartTime); m_totalTimedExecutionTime += delta; m_timedInvocations++; m_minExecutionTime = Math.min( delta, m_minExecutionTime); m_maxExecutionTime = Math.max( delta, m_maxExecutionTime); m_lastMinExecutionTime = Math.min( delta, m_lastMinExecutionTime); m_lastMaxExecutionTime = Math.max( delta, m_lastMaxExecutionTime); m_currentStartTime = -1; } if (aborted) { m_abortCount++; } if (failed) { m_failureCount++; } m_invocations++; } /** * Update the rowValues array with the latest statistical information. * This method is overrides the super class version * which must also be called so that it can update its columns. * @param values Values of each column of the row of stats. Used as output. */ @Override protected void updateStatsRow(Object rowKey, Object rowValues[]) { super.updateStatsRow(rowKey, rowValues); rowValues[columnNameToIndex.get("PARTITION_ID")] = m_site.getCorrespondingPartitionId(); rowValues[columnNameToIndex.get("PROCEDURE")] = catProc.getClassname(); long invocations = m_invocations; long totalTimedExecutionTime = m_totalTimedExecutionTime; long timedInvocations = m_timedInvocations; long minExecutionTime = m_minExecutionTime; long maxExecutionTime = m_maxExecutionTime; long abortCount = m_abortCount; long failureCount = m_failureCount; if (m_interval) { invocations = m_invocations - m_lastInvocations; m_lastInvocations = m_invocations; totalTimedExecutionTime = m_totalTimedExecutionTime - m_lastTotalTimedExecutionTime; m_lastTotalTimedExecutionTime = m_totalTimedExecutionTime; timedInvocations = m_timedInvocations - m_lastTimedInvocations; m_lastTimedInvocations = m_timedInvocations; abortCount = m_abortCount - m_lastAbortCount; m_lastAbortCount = m_abortCount; failureCount = m_failureCount - m_lastFailureCount; m_lastFailureCount = m_failureCount; minExecutionTime = m_lastMinExecutionTime; maxExecutionTime = m_lastMaxExecutionTime; m_lastMinExecutionTime = Long.MAX_VALUE; m_lastMaxExecutionTime = Long.MIN_VALUE; } rowValues[columnNameToIndex.get("INVOCATIONS")] = invocations; rowValues[columnNameToIndex.get("TIMED_INVOCATIONS")] = timedInvocations; rowValues[columnNameToIndex.get("MIN_EXECUTION_TIME")] = minExecutionTime; rowValues[columnNameToIndex.get("MAX_EXECUTION_TIME")] = maxExecutionTime; if (timedInvocations != 0) { rowValues[columnNameToIndex.get("AVG_EXECUTION_TIME")] = (totalTimedExecutionTime / timedInvocations); } else { rowValues[columnNameToIndex.get("AVG_EXECUTION_TIME")] = 0L; } rowValues[columnNameToIndex.get("ABORTS")] = abortCount; rowValues[columnNameToIndex.get("FAILURES")] = failureCount; } /** * Specifies the columns of statistics that are added by this class to the schema of a statistical results. * @param columns List of columns that are in a stats row. */ @Override protected void populateColumnSchema(ArrayList<VoltTable.ColumnInfo> columns) { super.populateColumnSchema(columns); columns.add(new VoltTable.ColumnInfo("PARTITION_ID", VoltType.INTEGER)); columns.add(new VoltTable.ColumnInfo("PROCEDURE", VoltType.STRING)); columns.add(new VoltTable.ColumnInfo("INVOCATIONS", VoltType.BIGINT)); columns.add(new VoltTable.ColumnInfo("TIMED_INVOCATIONS", VoltType.BIGINT)); columns.add(new VoltTable.ColumnInfo("MIN_EXECUTION_TIME", VoltType.BIGINT)); columns.add(new VoltTable.ColumnInfo("MAX_EXECUTION_TIME", VoltType.BIGINT)); columns.add(new VoltTable.ColumnInfo("AVG_EXECUTION_TIME", VoltType.BIGINT)); columns.add(new VoltTable.ColumnInfo("ABORTS", VoltType.BIGINT)); columns.add(new VoltTable.ColumnInfo("FAILURES", VoltType.BIGINT)); } @Override protected Iterator<Object> getStatsRowKeyIterator(boolean interval) { m_interval = interval; return new Iterator<Object>() { boolean givenNext = false; @Override public boolean hasNext() { if (!m_interval) { if (m_invocations == 0) { return false; } } else if (m_invocations - m_lastInvocations == 0){ return false; } return !givenNext; } @Override public Object next() { if (!givenNext) { givenNext = true; return new Object(); } return null; } @Override public void remove() {} }; } @Override public String toString() { return catProc.getTypeName(); } } /** * Set the status code that will be returned to the client. This is not the same as the status * code returned by the server. If a procedure sets the status code and then rolls back or causes an error * the status code will still be propagated back to the client so it is always necessary to check * the server status code first. * @param statusCode */ public void setAppStatusCode(byte statusCode) { m_statusCode = statusCode; } public void setAppStatusString(String statusString) { m_statusString = statusString; } private VoltTable[] slowPath(int batchSize, SQLStmt[] batchStmts, Object[][] batchArgs, boolean finalTask) { VoltTable[] results = new VoltTable[batchSize]; FastSerializer fs = new FastSerializer(); // the set of dependency ids for the expected results of the batch // one per sql statment int[] depsToResume = new int[batchSize]; // these dependencies need to be received before the local stuff can run int[] depsForLocalTask = new int[batchSize]; // the list of frag ids to run locally long[] localFragIds = new long[batchSize]; // the list of frag ids to run remotely ArrayList<Long> distributedFragIds = new ArrayList<Long>(); ArrayList<Integer> distributedOutputDepIds = new ArrayList<Integer>(); // the set of parameters for the local tasks ByteBuffer[] localParams = new ByteBuffer[batchSize]; // the set of parameters for the distributed tasks ArrayList<ByteBuffer> distributedParams = new ArrayList<ByteBuffer>(); // check if all local fragment work is non-transactional - boolean localFragsAreNonTransactional = true; + boolean localFragsAreNonTransactional = false; // iterate over all sql in the batch, filling out the above data structures for (int i = 0; i < batchSize; ++i) { SQLStmt stmt = batchStmts[i]; // check if the statement has been oked by the compiler/loader if (stmt.catStmt == null) { String msg = "SQLStmt objects cannot be instantiated after"; msg += " VoltDB initialization. User may have instantiated a SQLStmt"; msg += " inside a stored procedure's run method."; throw new RuntimeException(msg); } // Figure out what is needed to resume the proc int collectorOutputDepId = m_currentTxnState.getNextDependencyId(); depsToResume[i] = collectorOutputDepId; // Build the set of params for the frags ParameterSet paramSet = getCleanParams(stmt, batchArgs[i]); fs.clear(); try { fs.writeObject(paramSet); } catch (IOException e) { e.printStackTrace(); assert(false); } ByteBuffer params = fs.getBuffer(); assert(params != null); // populate the actual lists of fragments and params int numFrags = stmt.catStmt.getFragments().size(); assert(numFrags > 0); assert(numFrags <= 2); if (numFrags == 1) { for (PlanFragment frag : stmt.catStmt.getFragments()) { assert(frag != null); assert(frag.getHasdependencies() == false); localFragIds[i] = CatalogUtil.getUniqueIdForFragment(frag); localParams[i] = params; // if any frag is transactional, update this check - if (frag.getNontransactional() == false) + if (frag.getNontransactional() == true) localFragsAreNonTransactional = true; } depsForLocalTask[i] = -1; } else { for (PlanFragment frag : stmt.catStmt.getFragments()) { assert(frag != null); // frags with no deps are usually collector frags that go to all partitions if (frag.getHasdependencies() == false) { distributedFragIds.add(CatalogUtil.getUniqueIdForFragment(frag)); distributedParams.add(params); } // frags with deps are usually aggregator frags else { localFragIds[i] = CatalogUtil.getUniqueIdForFragment(frag); localParams[i] = params; assert(frag.getHasdependencies()); int outputDepId = m_currentTxnState.getNextDependencyId() | DtxnConstants.MULTIPARTITION_DEPENDENCY; depsForLocalTask[i] = outputDepId; distributedOutputDepIds.add(outputDepId); // if any frag is transactional, update this check - if (frag.getNontransactional() == false) + if (frag.getNontransactional() == true) localFragsAreNonTransactional = true; } } } } // convert a bunch of arraylists into arrays // this should be easier, but we also want little-i ints rather than Integers long[] distributedFragIdArray = new long[distributedFragIds.size()]; int[] distributedOutputDepIdArray = new int[distributedFragIds.size()]; ByteBuffer[] distributedParamsArray = new ByteBuffer[distributedFragIds.size()]; assert(distributedFragIds.size() == distributedParams.size()); for (int i = 0; i < distributedFragIds.size(); i++) { distributedFragIdArray[i] = distributedFragIds.get(i); distributedOutputDepIdArray[i] = distributedOutputDepIds.get(i); distributedParamsArray[i] = distributedParams.get(i); } // instruct the dtxn what's needed to resume the proc m_currentTxnState.setupProcedureResume(finalTask, depsToResume); // create all the local work for the transaction FragmentTaskMessage localTask = new FragmentTaskMessage(m_currentTxnState.initiatorSiteId, m_site.getCorrespondingSiteId(), m_currentTxnState.txnId, m_currentTxnState.isReadOnly, localFragIds, depsToResume, localParams, false); for (int i = 0; i < depsForLocalTask.length; i++) { if (depsForLocalTask[i] < 0) continue; localTask.addInputDepId(i, depsForLocalTask[i]); } // note: non-transactional work only helps us if it's final work m_currentTxnState.createLocalFragmentWork(localTask, localFragsAreNonTransactional && finalTask); // create and distribute work for all sites in the transaction FragmentTaskMessage distributedTask = new FragmentTaskMessage(m_currentTxnState.initiatorSiteId, m_site.getCorrespondingSiteId(), m_currentTxnState.txnId, m_currentTxnState.isReadOnly, distributedFragIdArray, distributedOutputDepIdArray, distributedParamsArray, finalTask); m_currentTxnState.createAllParticipatingFragmentWork(distributedTask); // recursively call recurableRun and don't allow it to shutdown Map<Integer,List<VoltTable>> mapResults = m_site.recursableRun(m_currentTxnState); assert(mapResults != null); assert(depsToResume != null); assert(depsToResume.length == batchSize); // build an array of answers, assuming one result per expected id for (int i = 0; i < batchSize; i++) { List<VoltTable> matchingTablesForId = mapResults.get(depsToResume[i]); assert(matchingTablesForId != null); assert(matchingTablesForId.size() == 1); results[i] = matchingTablesForId.get(0); if (batchStmts[i].catStmt.getReplicatedtabledml()) { long newVal = results[i].asScalarLong() / numberOfPartitions; results[i] = new VoltTable(new VoltTable.ColumnInfo("", VoltType.BIGINT)); results[i].addRow(newVal); } } return results; } /** * * @param e * @return A ClientResponse containing error information */ private ClientResponseImpl getErrorResponse(Throwable e) { StackTraceElement[] stack = e.getStackTrace(); ArrayList<StackTraceElement> matches = new ArrayList<StackTraceElement>(); for (StackTraceElement ste : stack) { if (ste.getClassName() == getClass().getName()) matches.add(ste); } byte status = ClientResponseImpl.UNEXPECTED_FAILURE; StringBuilder msg = new StringBuilder(); if (e.getClass() == VoltAbortException.class) { status = ClientResponseImpl.USER_ABORT; msg.append("USER ABORT\n"); } else if (e.getClass() == org.voltdb.exceptions.ConstraintFailureException.class) { status = ClientResponseImpl.GRACEFUL_FAILURE; msg.append("CONSTRAINT VIOLATION\n"); } else if (e.getClass() == org.voltdb.exceptions.SQLException.class) { status = ClientResponseImpl.GRACEFUL_FAILURE; msg.append("SQL ERROR\n"); } else if (e.getClass() == org.voltdb.ExpectedProcedureException.class) { msg.append("HSQL-BACKEND ERROR\n"); if (e.getCause() != null) e = e.getCause(); } else { msg.append("UNEXPECTED FAILURE:\n"); } String exMsg = e.getMessage(); if (exMsg == null) if (e.getClass() == NullPointerException.class) { exMsg = "Null Pointer Exception"; } else { exMsg = "Possible Null Pointer Exception ("; exMsg += e.getClass().getSimpleName() + ")"; e.printStackTrace(); } msg.append(" ").append(exMsg); for (StackTraceElement ste : matches) { msg.append("\n at "); msg.append(ste.getClassName()).append(".").append(ste.getMethodName()); msg.append("(").append(ste.getFileName()).append(":"); msg.append(ste.getLineNumber()).append(")"); } return getErrorResponse( status, msg.toString(), e instanceof SerializableException ? (SerializableException)e : null); } private ClientResponseImpl getErrorResponse(byte status, String msg, SerializableException e) { StringBuilder msgOut = new StringBuilder(); msgOut.append("\n===============================================================================\n"); msgOut.append("VOLTDB ERROR: "); msgOut.append(msg); msgOut.append("\n===============================================================================\n"); log.trace(msgOut); return new ClientResponseImpl( status, m_statusCode, m_statusString, new VoltTable[0], msgOut.toString(), e); } }
false
true
private VoltTable[] slowPath(int batchSize, SQLStmt[] batchStmts, Object[][] batchArgs, boolean finalTask) { VoltTable[] results = new VoltTable[batchSize]; FastSerializer fs = new FastSerializer(); // the set of dependency ids for the expected results of the batch // one per sql statment int[] depsToResume = new int[batchSize]; // these dependencies need to be received before the local stuff can run int[] depsForLocalTask = new int[batchSize]; // the list of frag ids to run locally long[] localFragIds = new long[batchSize]; // the list of frag ids to run remotely ArrayList<Long> distributedFragIds = new ArrayList<Long>(); ArrayList<Integer> distributedOutputDepIds = new ArrayList<Integer>(); // the set of parameters for the local tasks ByteBuffer[] localParams = new ByteBuffer[batchSize]; // the set of parameters for the distributed tasks ArrayList<ByteBuffer> distributedParams = new ArrayList<ByteBuffer>(); // check if all local fragment work is non-transactional boolean localFragsAreNonTransactional = true; // iterate over all sql in the batch, filling out the above data structures for (int i = 0; i < batchSize; ++i) { SQLStmt stmt = batchStmts[i]; // check if the statement has been oked by the compiler/loader if (stmt.catStmt == null) { String msg = "SQLStmt objects cannot be instantiated after"; msg += " VoltDB initialization. User may have instantiated a SQLStmt"; msg += " inside a stored procedure's run method."; throw new RuntimeException(msg); } // Figure out what is needed to resume the proc int collectorOutputDepId = m_currentTxnState.getNextDependencyId(); depsToResume[i] = collectorOutputDepId; // Build the set of params for the frags ParameterSet paramSet = getCleanParams(stmt, batchArgs[i]); fs.clear(); try { fs.writeObject(paramSet); } catch (IOException e) { e.printStackTrace(); assert(false); } ByteBuffer params = fs.getBuffer(); assert(params != null); // populate the actual lists of fragments and params int numFrags = stmt.catStmt.getFragments().size(); assert(numFrags > 0); assert(numFrags <= 2); if (numFrags == 1) { for (PlanFragment frag : stmt.catStmt.getFragments()) { assert(frag != null); assert(frag.getHasdependencies() == false); localFragIds[i] = CatalogUtil.getUniqueIdForFragment(frag); localParams[i] = params; // if any frag is transactional, update this check if (frag.getNontransactional() == false) localFragsAreNonTransactional = true; } depsForLocalTask[i] = -1; } else { for (PlanFragment frag : stmt.catStmt.getFragments()) { assert(frag != null); // frags with no deps are usually collector frags that go to all partitions if (frag.getHasdependencies() == false) { distributedFragIds.add(CatalogUtil.getUniqueIdForFragment(frag)); distributedParams.add(params); } // frags with deps are usually aggregator frags else { localFragIds[i] = CatalogUtil.getUniqueIdForFragment(frag); localParams[i] = params; assert(frag.getHasdependencies()); int outputDepId = m_currentTxnState.getNextDependencyId() | DtxnConstants.MULTIPARTITION_DEPENDENCY; depsForLocalTask[i] = outputDepId; distributedOutputDepIds.add(outputDepId); // if any frag is transactional, update this check if (frag.getNontransactional() == false) localFragsAreNonTransactional = true; } } } } // convert a bunch of arraylists into arrays // this should be easier, but we also want little-i ints rather than Integers long[] distributedFragIdArray = new long[distributedFragIds.size()]; int[] distributedOutputDepIdArray = new int[distributedFragIds.size()]; ByteBuffer[] distributedParamsArray = new ByteBuffer[distributedFragIds.size()]; assert(distributedFragIds.size() == distributedParams.size()); for (int i = 0; i < distributedFragIds.size(); i++) { distributedFragIdArray[i] = distributedFragIds.get(i); distributedOutputDepIdArray[i] = distributedOutputDepIds.get(i); distributedParamsArray[i] = distributedParams.get(i); } // instruct the dtxn what's needed to resume the proc m_currentTxnState.setupProcedureResume(finalTask, depsToResume); // create all the local work for the transaction FragmentTaskMessage localTask = new FragmentTaskMessage(m_currentTxnState.initiatorSiteId, m_site.getCorrespondingSiteId(), m_currentTxnState.txnId, m_currentTxnState.isReadOnly, localFragIds, depsToResume, localParams, false); for (int i = 0; i < depsForLocalTask.length; i++) { if (depsForLocalTask[i] < 0) continue; localTask.addInputDepId(i, depsForLocalTask[i]); } // note: non-transactional work only helps us if it's final work m_currentTxnState.createLocalFragmentWork(localTask, localFragsAreNonTransactional && finalTask); // create and distribute work for all sites in the transaction FragmentTaskMessage distributedTask = new FragmentTaskMessage(m_currentTxnState.initiatorSiteId, m_site.getCorrespondingSiteId(), m_currentTxnState.txnId, m_currentTxnState.isReadOnly, distributedFragIdArray, distributedOutputDepIdArray, distributedParamsArray, finalTask); m_currentTxnState.createAllParticipatingFragmentWork(distributedTask); // recursively call recurableRun and don't allow it to shutdown Map<Integer,List<VoltTable>> mapResults = m_site.recursableRun(m_currentTxnState); assert(mapResults != null); assert(depsToResume != null); assert(depsToResume.length == batchSize); // build an array of answers, assuming one result per expected id for (int i = 0; i < batchSize; i++) { List<VoltTable> matchingTablesForId = mapResults.get(depsToResume[i]); assert(matchingTablesForId != null); assert(matchingTablesForId.size() == 1); results[i] = matchingTablesForId.get(0); if (batchStmts[i].catStmt.getReplicatedtabledml()) { long newVal = results[i].asScalarLong() / numberOfPartitions; results[i] = new VoltTable(new VoltTable.ColumnInfo("", VoltType.BIGINT)); results[i].addRow(newVal); } } return results; }
private VoltTable[] slowPath(int batchSize, SQLStmt[] batchStmts, Object[][] batchArgs, boolean finalTask) { VoltTable[] results = new VoltTable[batchSize]; FastSerializer fs = new FastSerializer(); // the set of dependency ids for the expected results of the batch // one per sql statment int[] depsToResume = new int[batchSize]; // these dependencies need to be received before the local stuff can run int[] depsForLocalTask = new int[batchSize]; // the list of frag ids to run locally long[] localFragIds = new long[batchSize]; // the list of frag ids to run remotely ArrayList<Long> distributedFragIds = new ArrayList<Long>(); ArrayList<Integer> distributedOutputDepIds = new ArrayList<Integer>(); // the set of parameters for the local tasks ByteBuffer[] localParams = new ByteBuffer[batchSize]; // the set of parameters for the distributed tasks ArrayList<ByteBuffer> distributedParams = new ArrayList<ByteBuffer>(); // check if all local fragment work is non-transactional boolean localFragsAreNonTransactional = false; // iterate over all sql in the batch, filling out the above data structures for (int i = 0; i < batchSize; ++i) { SQLStmt stmt = batchStmts[i]; // check if the statement has been oked by the compiler/loader if (stmt.catStmt == null) { String msg = "SQLStmt objects cannot be instantiated after"; msg += " VoltDB initialization. User may have instantiated a SQLStmt"; msg += " inside a stored procedure's run method."; throw new RuntimeException(msg); } // Figure out what is needed to resume the proc int collectorOutputDepId = m_currentTxnState.getNextDependencyId(); depsToResume[i] = collectorOutputDepId; // Build the set of params for the frags ParameterSet paramSet = getCleanParams(stmt, batchArgs[i]); fs.clear(); try { fs.writeObject(paramSet); } catch (IOException e) { e.printStackTrace(); assert(false); } ByteBuffer params = fs.getBuffer(); assert(params != null); // populate the actual lists of fragments and params int numFrags = stmt.catStmt.getFragments().size(); assert(numFrags > 0); assert(numFrags <= 2); if (numFrags == 1) { for (PlanFragment frag : stmt.catStmt.getFragments()) { assert(frag != null); assert(frag.getHasdependencies() == false); localFragIds[i] = CatalogUtil.getUniqueIdForFragment(frag); localParams[i] = params; // if any frag is transactional, update this check if (frag.getNontransactional() == true) localFragsAreNonTransactional = true; } depsForLocalTask[i] = -1; } else { for (PlanFragment frag : stmt.catStmt.getFragments()) { assert(frag != null); // frags with no deps are usually collector frags that go to all partitions if (frag.getHasdependencies() == false) { distributedFragIds.add(CatalogUtil.getUniqueIdForFragment(frag)); distributedParams.add(params); } // frags with deps are usually aggregator frags else { localFragIds[i] = CatalogUtil.getUniqueIdForFragment(frag); localParams[i] = params; assert(frag.getHasdependencies()); int outputDepId = m_currentTxnState.getNextDependencyId() | DtxnConstants.MULTIPARTITION_DEPENDENCY; depsForLocalTask[i] = outputDepId; distributedOutputDepIds.add(outputDepId); // if any frag is transactional, update this check if (frag.getNontransactional() == true) localFragsAreNonTransactional = true; } } } } // convert a bunch of arraylists into arrays // this should be easier, but we also want little-i ints rather than Integers long[] distributedFragIdArray = new long[distributedFragIds.size()]; int[] distributedOutputDepIdArray = new int[distributedFragIds.size()]; ByteBuffer[] distributedParamsArray = new ByteBuffer[distributedFragIds.size()]; assert(distributedFragIds.size() == distributedParams.size()); for (int i = 0; i < distributedFragIds.size(); i++) { distributedFragIdArray[i] = distributedFragIds.get(i); distributedOutputDepIdArray[i] = distributedOutputDepIds.get(i); distributedParamsArray[i] = distributedParams.get(i); } // instruct the dtxn what's needed to resume the proc m_currentTxnState.setupProcedureResume(finalTask, depsToResume); // create all the local work for the transaction FragmentTaskMessage localTask = new FragmentTaskMessage(m_currentTxnState.initiatorSiteId, m_site.getCorrespondingSiteId(), m_currentTxnState.txnId, m_currentTxnState.isReadOnly, localFragIds, depsToResume, localParams, false); for (int i = 0; i < depsForLocalTask.length; i++) { if (depsForLocalTask[i] < 0) continue; localTask.addInputDepId(i, depsForLocalTask[i]); } // note: non-transactional work only helps us if it's final work m_currentTxnState.createLocalFragmentWork(localTask, localFragsAreNonTransactional && finalTask); // create and distribute work for all sites in the transaction FragmentTaskMessage distributedTask = new FragmentTaskMessage(m_currentTxnState.initiatorSiteId, m_site.getCorrespondingSiteId(), m_currentTxnState.txnId, m_currentTxnState.isReadOnly, distributedFragIdArray, distributedOutputDepIdArray, distributedParamsArray, finalTask); m_currentTxnState.createAllParticipatingFragmentWork(distributedTask); // recursively call recurableRun and don't allow it to shutdown Map<Integer,List<VoltTable>> mapResults = m_site.recursableRun(m_currentTxnState); assert(mapResults != null); assert(depsToResume != null); assert(depsToResume.length == batchSize); // build an array of answers, assuming one result per expected id for (int i = 0; i < batchSize; i++) { List<VoltTable> matchingTablesForId = mapResults.get(depsToResume[i]); assert(matchingTablesForId != null); assert(matchingTablesForId.size() == 1); results[i] = matchingTablesForId.get(0); if (batchStmts[i].catStmt.getReplicatedtabledml()) { long newVal = results[i].asScalarLong() / numberOfPartitions; results[i] = new VoltTable(new VoltTable.ColumnInfo("", VoltType.BIGINT)); results[i].addRow(newVal); } } return results; }
diff --git a/src/com/android/providers/contacts/ContactsProvider2.java b/src/com/android/providers/contacts/ContactsProvider2.java index 49e7ab5..6d33836 100644 --- a/src/com/android/providers/contacts/ContactsProvider2.java +++ b/src/com/android/providers/contacts/ContactsProvider2.java @@ -1,7365 +1,7367 @@ /* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.android.providers.contacts; import com.android.common.content.SQLiteContentProvider; import com.android.common.content.SyncStateContentProviderHelper; import com.android.providers.contacts.ContactAggregator.AggregationSuggestionParameter; import com.android.providers.contacts.ContactLookupKey.LookupKeySegment; import com.android.providers.contacts.ContactsDatabaseHelper.AccountsColumns; import com.android.providers.contacts.ContactsDatabaseHelper.AggregatedPresenceColumns; import com.android.providers.contacts.ContactsDatabaseHelper.AggregationExceptionColumns; import com.android.providers.contacts.ContactsDatabaseHelper.Clauses; import com.android.providers.contacts.ContactsDatabaseHelper.ContactsColumns; import com.android.providers.contacts.ContactsDatabaseHelper.ContactsStatusUpdatesColumns; import com.android.providers.contacts.ContactsDatabaseHelper.DataColumns; import com.android.providers.contacts.ContactsDatabaseHelper.DataUsageStatColumns; import com.android.providers.contacts.ContactsDatabaseHelper.GroupsColumns; import com.android.providers.contacts.ContactsDatabaseHelper.MimetypesColumns; import com.android.providers.contacts.ContactsDatabaseHelper.NameLookupColumns; import com.android.providers.contacts.ContactsDatabaseHelper.NameLookupType; import com.android.providers.contacts.ContactsDatabaseHelper.PhoneColumns; import com.android.providers.contacts.ContactsDatabaseHelper.PhoneLookupColumns; import com.android.providers.contacts.ContactsDatabaseHelper.PhotoFilesColumns; import com.android.providers.contacts.ContactsDatabaseHelper.PresenceColumns; import com.android.providers.contacts.ContactsDatabaseHelper.RawContactsColumns; import com.android.providers.contacts.ContactsDatabaseHelper.SearchIndexColumns; import com.android.providers.contacts.ContactsDatabaseHelper.SettingsColumns; import com.android.providers.contacts.ContactsDatabaseHelper.StatusUpdatesColumns; import com.android.providers.contacts.ContactsDatabaseHelper.StreamItemPhotosColumns; import com.android.providers.contacts.ContactsDatabaseHelper.StreamItemsColumns; import com.android.providers.contacts.ContactsDatabaseHelper.Tables; import com.android.providers.contacts.ContactsDatabaseHelper.Views; import com.android.providers.contacts.util.DbQueryUtils; import com.android.vcard.VCardComposer; import com.android.vcard.VCardConfig; import com.google.android.collect.Lists; import com.google.android.collect.Maps; import com.google.android.collect.Sets; import com.google.common.annotations.VisibleForTesting; import android.accounts.Account; import android.accounts.AccountManager; import android.accounts.OnAccountsUpdateListener; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.SearchManager; import android.content.ContentProviderOperation; import android.content.ContentProviderResult; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.IContentService; import android.content.Intent; import android.content.OperationApplicationException; import android.content.SharedPreferences; import android.content.SyncAdapterType; import android.content.UriMatcher; import android.content.res.AssetFileDescriptor; import android.content.res.Resources; import android.database.CrossProcessCursor; import android.database.Cursor; import android.database.CursorWindow; import android.database.CursorWrapper; import android.database.DatabaseUtils; import android.database.MatrixCursor; import android.database.MatrixCursor.RowBuilder; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDoneException; import android.database.sqlite.SQLiteQueryBuilder; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.net.Uri.Builder; import android.os.Binder; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.os.Message; import android.os.ParcelFileDescriptor; import android.os.Process; import android.os.RemoteException; import android.os.StrictMode; import android.os.SystemClock; import android.os.SystemProperties; import android.preference.PreferenceManager; import android.provider.BaseColumns; import android.provider.ContactsContract; import android.provider.ContactsContract.AggregationExceptions; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.CommonDataKinds.GroupMembership; import android.provider.ContactsContract.CommonDataKinds.Im; import android.provider.ContactsContract.CommonDataKinds.Nickname; import android.provider.ContactsContract.CommonDataKinds.Note; import android.provider.ContactsContract.CommonDataKinds.Organization; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.CommonDataKinds.Photo; import android.provider.ContactsContract.CommonDataKinds.SipAddress; import android.provider.ContactsContract.CommonDataKinds.StructuredName; import android.provider.ContactsContract.CommonDataKinds.StructuredPostal; import android.provider.ContactsContract.ContactCounts; import android.provider.ContactsContract.Contacts; import android.provider.ContactsContract.Contacts.AggregationSuggestions; import android.provider.ContactsContract.Data; import android.provider.ContactsContract.DataUsageFeedback; import android.provider.ContactsContract.Directory; import android.provider.ContactsContract.DisplayPhoto; import android.provider.ContactsContract.Groups; import android.provider.ContactsContract.Intents; import android.provider.ContactsContract.PhoneLookup; import android.provider.ContactsContract.PhotoFiles; import android.provider.ContactsContract.ProviderStatus; import android.provider.ContactsContract.RawContacts; import android.provider.ContactsContract.SearchSnippetColumns; import android.provider.ContactsContract.Settings; import android.provider.ContactsContract.StatusUpdates; import android.provider.ContactsContract.StreamItemPhotos; import android.provider.ContactsContract.StreamItems; import android.provider.LiveFolders; import android.provider.OpenableColumns; import android.provider.SyncStateContract; import android.telephony.PhoneNumberUtils; import android.telephony.TelephonyManager; import android.text.TextUtils; import android.util.Log; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.concurrent.CountDownLatch; /** * Contacts content provider. The contract between this provider and applications * is defined in {@link ContactsContract}. */ public class ContactsProvider2 extends SQLiteContentProvider implements OnAccountsUpdateListener { private static final String TAG = "ContactsProvider"; private static final boolean VERBOSE_LOGGING = Log.isLoggable(TAG, Log.VERBOSE); private static final int BACKGROUND_TASK_INITIALIZE = 0; private static final int BACKGROUND_TASK_OPEN_WRITE_ACCESS = 1; private static final int BACKGROUND_TASK_IMPORT_LEGACY_CONTACTS = 2; private static final int BACKGROUND_TASK_UPDATE_ACCOUNTS = 3; private static final int BACKGROUND_TASK_UPDATE_LOCALE = 4; private static final int BACKGROUND_TASK_UPGRADE_AGGREGATION_ALGORITHM = 5; private static final int BACKGROUND_TASK_UPDATE_SEARCH_INDEX = 6; private static final int BACKGROUND_TASK_UPDATE_PROVIDER_STATUS = 7; private static final int BACKGROUND_TASK_UPDATE_DIRECTORIES = 8; private static final int BACKGROUND_TASK_CHANGE_LOCALE = 9; private static final int BACKGROUND_TASK_CLEANUP_PHOTOS = 10; /** Default for the maximum number of returned aggregation suggestions. */ private static final int DEFAULT_MAX_SUGGESTIONS = 5; /** Limit for the maximum number of social stream items to store under a raw contact. */ private static final int MAX_STREAM_ITEMS_PER_RAW_CONTACT = 5; /** Rate limit (in ms) for photo cleanup. Do it at most once per day. */ private static final int PHOTO_CLEANUP_RATE_LIMIT = 24 * 60 * 60 * 1000; /** * Property key for the legacy contact import version. The need for a version * as opposed to a boolean flag is that if we discover bugs in the contact import process, * we can trigger re-import by incrementing the import version. */ private static final String PROPERTY_CONTACTS_IMPORTED = "contacts_imported_v1"; private static final int PROPERTY_CONTACTS_IMPORT_VERSION = 1; private static final String PREF_LOCALE = "locale"; private static final String PROPERTY_AGGREGATION_ALGORITHM = "aggregation_v2"; private static final int PROPERTY_AGGREGATION_ALGORITHM_VERSION = 2; private static final String AGGREGATE_CONTACTS = "sync.contacts.aggregate"; private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); /** * Used to insert a column into strequent results, which enables SQL to sort the list using * the total times contacted. See also {@link #sStrequentFrequentProjectionMap}. */ private static final String TIMES_USED_SORT_COLUMN = "times_used_sort"; private static final String STREQUENT_ORDER_BY = Contacts.STARRED + " DESC, " + TIMES_USED_SORT_COLUMN + " DESC, " + Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC"; private static final String STREQUENT_LIMIT = "(SELECT COUNT(1) FROM " + Tables.CONTACTS + " WHERE " + Contacts.STARRED + "=1) + 25"; private static final String FREQUENT_ORDER_BY = DataUsageStatColumns.TIMES_USED + " DESC," + Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC"; /* package */ static final String UPDATE_TIMES_CONTACTED_CONTACTS_TABLE = "UPDATE " + Tables.CONTACTS + " SET " + Contacts.TIMES_CONTACTED + "=" + " CASE WHEN " + Contacts.TIMES_CONTACTED + " IS NULL THEN 1 ELSE " + " (" + Contacts.TIMES_CONTACTED + " + 1) END WHERE " + Contacts._ID + "=?"; /* package */ static final String UPDATE_TIMES_CONTACTED_RAWCONTACTS_TABLE = "UPDATE " + Tables.RAW_CONTACTS + " SET " + RawContacts.TIMES_CONTACTED + "=" + " CASE WHEN " + RawContacts.TIMES_CONTACTED + " IS NULL THEN 1 ELSE " + " (" + RawContacts.TIMES_CONTACTED + " + 1) END WHERE " + RawContacts.CONTACT_ID + "=?"; /* package */ static final String PHONEBOOK_COLLATOR_NAME = "PHONEBOOK"; // Regex for splitting query strings - we split on any group of non-alphanumeric characters, // excluding the @ symbol. /* package */ static final String QUERY_TOKENIZER_REGEX = "[^\\w@]+"; private static final int CONTACTS = 1000; private static final int CONTACTS_ID = 1001; private static final int CONTACTS_LOOKUP = 1002; private static final int CONTACTS_LOOKUP_ID = 1003; private static final int CONTACTS_ID_DATA = 1004; private static final int CONTACTS_FILTER = 1005; private static final int CONTACTS_STREQUENT = 1006; private static final int CONTACTS_STREQUENT_FILTER = 1007; private static final int CONTACTS_GROUP = 1008; private static final int CONTACTS_ID_PHOTO = 1009; private static final int CONTACTS_ID_DISPLAY_PHOTO = 1010; private static final int CONTACTS_LOOKUP_DISPLAY_PHOTO = 1011; private static final int CONTACTS_LOOKUP_ID_DISPLAY_PHOTO = 1012; private static final int CONTACTS_AS_VCARD = 1013; private static final int CONTACTS_AS_MULTI_VCARD = 1014; private static final int CONTACTS_LOOKUP_DATA = 1015; private static final int CONTACTS_LOOKUP_ID_DATA = 1016; private static final int CONTACTS_ID_ENTITIES = 1017; private static final int CONTACTS_LOOKUP_ENTITIES = 1018; private static final int CONTACTS_LOOKUP_ID_ENTITIES = 1019; private static final int CONTACTS_ID_STREAM_ITEMS = 1020; private static final int CONTACTS_LOOKUP_STREAM_ITEMS = 1021; private static final int CONTACTS_LOOKUP_ID_STREAM_ITEMS = 1022; private static final int CONTACTS_FREQUENT = 1023; private static final int RAW_CONTACTS = 2002; private static final int RAW_CONTACTS_ID = 2003; private static final int RAW_CONTACTS_DATA = 2004; private static final int RAW_CONTACT_ENTITY_ID = 2005; private static final int RAW_CONTACTS_ID_DISPLAY_PHOTO = 2006; private static final int RAW_CONTACTS_ID_STREAM_ITEMS = 2007; private static final int DATA = 3000; private static final int DATA_ID = 3001; private static final int PHONES = 3002; private static final int PHONES_ID = 3003; private static final int PHONES_FILTER = 3004; private static final int EMAILS = 3005; private static final int EMAILS_ID = 3006; private static final int EMAILS_LOOKUP = 3007; private static final int EMAILS_FILTER = 3008; private static final int POSTALS = 3009; private static final int POSTALS_ID = 3010; private static final int PHONE_LOOKUP = 4000; private static final int AGGREGATION_EXCEPTIONS = 6000; private static final int AGGREGATION_EXCEPTION_ID = 6001; private static final int STATUS_UPDATES = 7000; private static final int STATUS_UPDATES_ID = 7001; private static final int AGGREGATION_SUGGESTIONS = 8000; private static final int SETTINGS = 9000; private static final int GROUPS = 10000; private static final int GROUPS_ID = 10001; private static final int GROUPS_SUMMARY = 10003; private static final int SYNCSTATE = 11000; private static final int SYNCSTATE_ID = 11001; private static final int SEARCH_SUGGESTIONS = 12001; private static final int SEARCH_SHORTCUT = 12002; private static final int LIVE_FOLDERS_CONTACTS = 14000; private static final int LIVE_FOLDERS_CONTACTS_WITH_PHONES = 14001; private static final int LIVE_FOLDERS_CONTACTS_FAVORITES = 14002; private static final int LIVE_FOLDERS_CONTACTS_GROUP_NAME = 14003; private static final int RAW_CONTACT_ENTITIES = 15001; private static final int PROVIDER_STATUS = 16001; private static final int DIRECTORIES = 17001; private static final int DIRECTORIES_ID = 17002; private static final int COMPLETE_NAME = 18000; private static final int PROFILE = 19000; private static final int PROFILE_ENTITIES = 19001; private static final int PROFILE_DATA = 19002; private static final int PROFILE_DATA_ID = 19003; private static final int PROFILE_AS_VCARD = 19004; private static final int PROFILE_RAW_CONTACTS = 19005; private static final int PROFILE_RAW_CONTACTS_ID = 19006; private static final int PROFILE_RAW_CONTACTS_ID_DATA = 19007; private static final int PROFILE_RAW_CONTACTS_ID_ENTITIES = 19008; private static final int DATA_USAGE_FEEDBACK_ID = 20001; private static final int STREAM_ITEMS = 21000; private static final int STREAM_ITEMS_PHOTOS = 21001; private static final int STREAM_ITEMS_ID = 21002; private static final int STREAM_ITEMS_ID_PHOTOS = 21003; private static final int STREAM_ITEMS_ID_PHOTOS_ID = 21004; private static final int STREAM_ITEMS_LIMIT = 21005; private static final int DISPLAY_PHOTO = 22000; private static final int PHOTO_DIMENSIONS = 22001; private static final String SELECTION_FAVORITES_GROUPS_BY_RAW_CONTACT_ID = RawContactsColumns.CONCRETE_ID + "=? AND " + GroupsColumns.CONCRETE_ACCOUNT_NAME + "=" + RawContactsColumns.CONCRETE_ACCOUNT_NAME + " AND " + GroupsColumns.CONCRETE_ACCOUNT_TYPE + "=" + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + " AND (" + GroupsColumns.CONCRETE_DATA_SET + "=" + RawContactsColumns.CONCRETE_DATA_SET + " OR " + GroupsColumns.CONCRETE_DATA_SET + " IS NULL AND " + RawContactsColumns.CONCRETE_DATA_SET + " IS NULL)" + " AND " + Groups.FAVORITES + " != 0"; private static final String SELECTION_AUTO_ADD_GROUPS_BY_RAW_CONTACT_ID = RawContactsColumns.CONCRETE_ID + "=? AND " + GroupsColumns.CONCRETE_ACCOUNT_NAME + "=" + RawContactsColumns.CONCRETE_ACCOUNT_NAME + " AND " + GroupsColumns.CONCRETE_ACCOUNT_TYPE + "=" + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + " AND (" + GroupsColumns.CONCRETE_DATA_SET + "=" + RawContactsColumns.CONCRETE_DATA_SET + " OR " + GroupsColumns.CONCRETE_DATA_SET + " IS NULL AND " + RawContactsColumns.CONCRETE_DATA_SET + " IS NULL)" + " AND " + Groups.AUTO_ADD + " != 0"; private static final String[] PROJECTION_GROUP_ID = new String[]{Tables.GROUPS + "." + Groups._ID}; private static final String SELECTION_GROUPMEMBERSHIP_DATA = DataColumns.MIMETYPE_ID + "=? " + "AND " + GroupMembership.GROUP_ROW_ID + "=? " + "AND " + GroupMembership.RAW_CONTACT_ID + "=?"; private static final String SELECTION_STARRED_FROM_RAW_CONTACTS = "SELECT " + RawContacts.STARRED + " FROM " + Tables.RAW_CONTACTS + " WHERE " + RawContacts._ID + "=?"; public class AddressBookCursor extends CursorWrapper implements CrossProcessCursor { private final CrossProcessCursor mCursor; private final Bundle mBundle; public AddressBookCursor(CrossProcessCursor cursor, String[] titles, int[] counts) { super(cursor); mCursor = cursor; mBundle = new Bundle(); mBundle.putStringArray(ContactCounts.EXTRA_ADDRESS_BOOK_INDEX_TITLES, titles); mBundle.putIntArray(ContactCounts.EXTRA_ADDRESS_BOOK_INDEX_COUNTS, counts); } @Override public Bundle getExtras() { return mBundle; } @Override public void fillWindow(int pos, CursorWindow window) { mCursor.fillWindow(pos, window); } @Override public CursorWindow getWindow() { return mCursor.getWindow(); } @Override public boolean onMove(int oldPosition, int newPosition) { return mCursor.onMove(oldPosition, newPosition); } } private interface DataContactsQuery { public static final String TABLE = "data " + "JOIN raw_contacts ON (data.raw_contact_id = raw_contacts._id) " + "JOIN contacts ON (raw_contacts.contact_id = contacts._id)"; public static final String[] PROJECTION = new String[] { RawContactsColumns.CONCRETE_ID, RawContactsColumns.CONCRETE_ACCOUNT_TYPE, RawContactsColumns.CONCRETE_ACCOUNT_NAME, RawContactsColumns.CONCRETE_DATA_SET, DataColumns.CONCRETE_ID, ContactsColumns.CONCRETE_ID }; public static final int RAW_CONTACT_ID = 0; public static final int ACCOUNT_TYPE = 1; public static final int ACCOUNT_NAME = 2; public static final int DATA_SET = 3; public static final int DATA_ID = 4; public static final int CONTACT_ID = 5; } interface RawContactsQuery { String TABLE = Tables.RAW_CONTACTS; String[] COLUMNS = new String[] { RawContacts.DELETED, RawContacts.ACCOUNT_TYPE, RawContacts.ACCOUNT_NAME, RawContacts.DATA_SET, }; int DELETED = 0; int ACCOUNT_TYPE = 1; int ACCOUNT_NAME = 2; int DATA_SET = 3; } public static final String DEFAULT_ACCOUNT_TYPE = "com.google"; /** Sql where statement for filtering on groups. */ private static final String CONTACTS_IN_GROUP_SELECT = Contacts._ID + " IN " + "(SELECT " + RawContacts.CONTACT_ID + " FROM " + Tables.RAW_CONTACTS + " WHERE " + RawContactsColumns.CONCRETE_ID + " IN " + "(SELECT " + DataColumns.CONCRETE_RAW_CONTACT_ID + " FROM " + Tables.DATA_JOIN_MIMETYPES + " WHERE " + Data.MIMETYPE + "='" + GroupMembership.CONTENT_ITEM_TYPE + "' AND " + GroupMembership.GROUP_ROW_ID + "=" + "(SELECT " + Tables.GROUPS + "." + Groups._ID + " FROM " + Tables.GROUPS + " WHERE " + Groups.TITLE + "=?)))"; /** Sql for updating DIRTY flag on multiple raw contacts */ private static final String UPDATE_RAW_CONTACT_SET_DIRTY_SQL = "UPDATE " + Tables.RAW_CONTACTS + " SET " + RawContacts.DIRTY + "=1" + " WHERE " + RawContacts._ID + " IN ("; /** Sql for updating VERSION on multiple raw contacts */ private static final String UPDATE_RAW_CONTACT_SET_VERSION_SQL = "UPDATE " + Tables.RAW_CONTACTS + " SET " + RawContacts.VERSION + " = " + RawContacts.VERSION + " + 1" + " WHERE " + RawContacts._ID + " IN ("; // Current contacts - those contacted within the last 3 days (in seconds) private static final long EMAIL_FILTER_CURRENT = 3 * 24 * 60 * 60; // Recent contacts - those contacted within the last 30 days (in seconds) private static final long EMAIL_FILTER_RECENT = 30 * 24 * 60 * 60; private static final String TIME_SINCE_LAST_USED = "(strftime('%s', 'now') - " + DataUsageStatColumns.LAST_TIME_USED + "/1000)"; /* * Sorting order for email address suggestions: first starred, then the rest. * second in_visible_group, then the rest. * Within the four (starred/unstarred, in_visible_group/not-in_visible_group) groups * - three buckets: very recently contacted, then fairly * recently contacted, then the rest. Within each of the bucket - descending count * of times contacted (both for data row and for contact row). If all else fails, alphabetical. * (Super)primary email address is returned before other addresses for the same contact. */ private static final String EMAIL_FILTER_SORT_ORDER = Contacts.STARRED + " DESC, " + Contacts.IN_VISIBLE_GROUP + " DESC, " + "(CASE WHEN " + TIME_SINCE_LAST_USED + " < " + EMAIL_FILTER_CURRENT + " THEN 0 " + " WHEN " + TIME_SINCE_LAST_USED + " < " + EMAIL_FILTER_RECENT + " THEN 1 " + " ELSE 2 END), " + DataUsageStatColumns.TIMES_USED + " DESC, " + Contacts.DISPLAY_NAME + ", " + Data.CONTACT_ID + ", " + Data.IS_SUPER_PRIMARY + " DESC, " + Data.IS_PRIMARY + " DESC"; /** Currently same as {@link #EMAIL_FILTER_SORT_ORDER} */ private static final String PHONE_FILTER_SORT_ORDER = EMAIL_FILTER_SORT_ORDER; /** Name lookup types used for contact filtering */ private static final String CONTACT_LOOKUP_NAME_TYPES = NameLookupType.NAME_COLLATION_KEY + "," + NameLookupType.EMAIL_BASED_NICKNAME + "," + NameLookupType.NICKNAME; /** * If any of these columns are used in a Data projection, there is no point in * using the DISTINCT keyword, which can negatively affect performance. */ private static final String[] DISTINCT_DATA_PROHIBITING_COLUMNS = { Data._ID, Data.RAW_CONTACT_ID, Data.NAME_RAW_CONTACT_ID, RawContacts.ACCOUNT_NAME, RawContacts.ACCOUNT_TYPE, RawContacts.DATA_SET, RawContacts.ACCOUNT_TYPE_AND_DATA_SET, RawContacts.DIRTY, RawContacts.NAME_VERIFIED, RawContacts.SOURCE_ID, RawContacts.VERSION, }; private static final ProjectionMap sContactsColumns = ProjectionMap.builder() .add(Contacts.CUSTOM_RINGTONE) .add(Contacts.DISPLAY_NAME) .add(Contacts.DISPLAY_NAME_ALTERNATIVE) .add(Contacts.DISPLAY_NAME_SOURCE) .add(Contacts.IN_VISIBLE_GROUP) .add(Contacts.LAST_TIME_CONTACTED) .add(Contacts.LOOKUP_KEY) .add(Contacts.PHONETIC_NAME) .add(Contacts.PHONETIC_NAME_STYLE) .add(Contacts.PHOTO_ID) .add(Contacts.PHOTO_FILE_ID) .add(Contacts.PHOTO_URI) .add(Contacts.PHOTO_THUMBNAIL_URI) .add(Contacts.SEND_TO_VOICEMAIL) .add(Contacts.SORT_KEY_ALTERNATIVE) .add(Contacts.SORT_KEY_PRIMARY) .add(Contacts.STARRED) .add(Contacts.TIMES_CONTACTED) .add(Contacts.HAS_PHONE_NUMBER) .build(); private static final ProjectionMap sContactsPresenceColumns = ProjectionMap.builder() .add(Contacts.CONTACT_PRESENCE, Tables.AGGREGATED_PRESENCE + "." + StatusUpdates.PRESENCE) .add(Contacts.CONTACT_CHAT_CAPABILITY, Tables.AGGREGATED_PRESENCE + "." + StatusUpdates.CHAT_CAPABILITY) .add(Contacts.CONTACT_STATUS, ContactsStatusUpdatesColumns.CONCRETE_STATUS) .add(Contacts.CONTACT_STATUS_TIMESTAMP, ContactsStatusUpdatesColumns.CONCRETE_STATUS_TIMESTAMP) .add(Contacts.CONTACT_STATUS_RES_PACKAGE, ContactsStatusUpdatesColumns.CONCRETE_STATUS_RES_PACKAGE) .add(Contacts.CONTACT_STATUS_LABEL, ContactsStatusUpdatesColumns.CONCRETE_STATUS_LABEL) .add(Contacts.CONTACT_STATUS_ICON, ContactsStatusUpdatesColumns.CONCRETE_STATUS_ICON) .build(); private static final ProjectionMap sSnippetColumns = ProjectionMap.builder() .add(SearchSnippetColumns.SNIPPET) .build(); private static final ProjectionMap sRawContactColumns = ProjectionMap.builder() .add(RawContacts.ACCOUNT_NAME) .add(RawContacts.ACCOUNT_TYPE) .add(RawContacts.DATA_SET) .add(RawContacts.ACCOUNT_TYPE_AND_DATA_SET) .add(RawContacts.DIRTY) .add(RawContacts.NAME_VERIFIED) .add(RawContacts.SOURCE_ID) .add(RawContacts.VERSION) .build(); private static final ProjectionMap sRawContactSyncColumns = ProjectionMap.builder() .add(RawContacts.SYNC1) .add(RawContacts.SYNC2) .add(RawContacts.SYNC3) .add(RawContacts.SYNC4) .build(); private static final ProjectionMap sDataColumns = ProjectionMap.builder() .add(Data.DATA1) .add(Data.DATA2) .add(Data.DATA3) .add(Data.DATA4) .add(Data.DATA5) .add(Data.DATA6) .add(Data.DATA7) .add(Data.DATA8) .add(Data.DATA9) .add(Data.DATA10) .add(Data.DATA11) .add(Data.DATA12) .add(Data.DATA13) .add(Data.DATA14) .add(Data.DATA15) .add(Data.DATA_VERSION) .add(Data.IS_PRIMARY) .add(Data.IS_SUPER_PRIMARY) .add(Data.MIMETYPE) .add(Data.RES_PACKAGE) .add(Data.SYNC1) .add(Data.SYNC2) .add(Data.SYNC3) .add(Data.SYNC4) .add(GroupMembership.GROUP_SOURCE_ID) .build(); private static final ProjectionMap sContactPresenceColumns = ProjectionMap.builder() .add(Contacts.CONTACT_PRESENCE, Tables.AGGREGATED_PRESENCE + '.' + StatusUpdates.PRESENCE) .add(Contacts.CONTACT_CHAT_CAPABILITY, Tables.AGGREGATED_PRESENCE + '.' + StatusUpdates.CHAT_CAPABILITY) .add(Contacts.CONTACT_STATUS, ContactsStatusUpdatesColumns.CONCRETE_STATUS) .add(Contacts.CONTACT_STATUS_TIMESTAMP, ContactsStatusUpdatesColumns.CONCRETE_STATUS_TIMESTAMP) .add(Contacts.CONTACT_STATUS_RES_PACKAGE, ContactsStatusUpdatesColumns.CONCRETE_STATUS_RES_PACKAGE) .add(Contacts.CONTACT_STATUS_LABEL, ContactsStatusUpdatesColumns.CONCRETE_STATUS_LABEL) .add(Contacts.CONTACT_STATUS_ICON, ContactsStatusUpdatesColumns.CONCRETE_STATUS_ICON) .build(); private static final ProjectionMap sDataPresenceColumns = ProjectionMap.builder() .add(Data.PRESENCE, Tables.PRESENCE + "." + StatusUpdates.PRESENCE) .add(Data.CHAT_CAPABILITY, Tables.PRESENCE + "." + StatusUpdates.CHAT_CAPABILITY) .add(Data.STATUS, StatusUpdatesColumns.CONCRETE_STATUS) .add(Data.STATUS_TIMESTAMP, StatusUpdatesColumns.CONCRETE_STATUS_TIMESTAMP) .add(Data.STATUS_RES_PACKAGE, StatusUpdatesColumns.CONCRETE_STATUS_RES_PACKAGE) .add(Data.STATUS_LABEL, StatusUpdatesColumns.CONCRETE_STATUS_LABEL) .add(Data.STATUS_ICON, StatusUpdatesColumns.CONCRETE_STATUS_ICON) .build(); /** Contains just BaseColumns._COUNT */ private static final ProjectionMap sCountProjectionMap = ProjectionMap.builder() .add(BaseColumns._COUNT, "COUNT(*)") .build(); /** Contains just the contacts columns */ private static final ProjectionMap sContactsProjectionMap = ProjectionMap.builder() .add(Contacts._ID) .add(Contacts.HAS_PHONE_NUMBER) .add(Contacts.NAME_RAW_CONTACT_ID) .add(Contacts.IS_USER_PROFILE) .addAll(sContactsColumns) .addAll(sContactsPresenceColumns) .build(); /** Contains just the contacts columns */ private static final ProjectionMap sContactsProjectionWithSnippetMap = ProjectionMap.builder() .addAll(sContactsProjectionMap) .addAll(sSnippetColumns) .build(); /** Used for pushing starred contacts to the top of a times contacted list **/ private static final ProjectionMap sStrequentStarredProjectionMap = ProjectionMap.builder() .addAll(sContactsProjectionMap) .add(TIMES_USED_SORT_COLUMN, String.valueOf(Long.MAX_VALUE)) .build(); private static final ProjectionMap sStrequentFrequentProjectionMap = ProjectionMap.builder() .addAll(sContactsProjectionMap) .add(TIMES_USED_SORT_COLUMN, "SUM(" + DataUsageStatColumns.CONCRETE_TIMES_USED + ")") .build(); /** * Used for Strequent Uri with {@link ContactsContract#STREQUENT_PHONE_ONLY}, which allows * users to obtain part of Data columns. Right now Starred part just returns NULL for * those data columns (frequent part should return real ones in data table). **/ private static final ProjectionMap sStrequentPhoneOnlyStarredProjectionMap = ProjectionMap.builder() .addAll(sContactsProjectionMap) .add(TIMES_USED_SORT_COLUMN, String.valueOf(Long.MAX_VALUE)) .add(Phone.NUMBER, "NULL") .add(Phone.TYPE, "NULL") .add(Phone.LABEL, "NULL") .build(); /** * Used for Strequent Uri with {@link ContactsContract#STREQUENT_PHONE_ONLY}, which allows * users to obtain part of Data columns. We hard-code {@link Contacts#IS_USER_PROFILE} to NULL, * because sContactsProjectionMap specifies a field that doesn't exist in the view behind the * query that uses this projection map. **/ private static final ProjectionMap sStrequentPhoneOnlyFrequentProjectionMap = ProjectionMap.builder() .addAll(sContactsProjectionMap) .add(TIMES_USED_SORT_COLUMN, DataUsageStatColumns.CONCRETE_TIMES_USED) .add(Phone.NUMBER) .add(Phone.TYPE) .add(Phone.LABEL) .add(Contacts.IS_USER_PROFILE, "NULL") .build(); /** Contains just the contacts vCard columns */ private static final ProjectionMap sContactsVCardProjectionMap = ProjectionMap.builder() .add(Contacts._ID) .add(OpenableColumns.DISPLAY_NAME, Contacts.DISPLAY_NAME + " || '.vcf'") .add(OpenableColumns.SIZE, "NULL") .build(); /** Contains just the raw contacts columns */ private static final ProjectionMap sRawContactsProjectionMap = ProjectionMap.builder() .add(RawContacts._ID) .add(RawContacts.CONTACT_ID) .add(RawContacts.DELETED) .add(RawContacts.DISPLAY_NAME_PRIMARY) .add(RawContacts.DISPLAY_NAME_ALTERNATIVE) .add(RawContacts.DISPLAY_NAME_SOURCE) .add(RawContacts.PHONETIC_NAME) .add(RawContacts.PHONETIC_NAME_STYLE) .add(RawContacts.SORT_KEY_PRIMARY) .add(RawContacts.SORT_KEY_ALTERNATIVE) .add(RawContacts.TIMES_CONTACTED) .add(RawContacts.LAST_TIME_CONTACTED) .add(RawContacts.CUSTOM_RINGTONE) .add(RawContacts.SEND_TO_VOICEMAIL) .add(RawContacts.STARRED) .add(RawContacts.AGGREGATION_MODE) .add(RawContacts.RAW_CONTACT_IS_USER_PROFILE) .addAll(sRawContactColumns) .addAll(sRawContactSyncColumns) .build(); /** Contains the columns from the raw entity view*/ private static final ProjectionMap sRawEntityProjectionMap = ProjectionMap.builder() .add(RawContacts._ID) .add(RawContacts.CONTACT_ID) .add(RawContacts.Entity.DATA_ID) .add(RawContacts.DELETED) .add(RawContacts.STARRED) .add(RawContacts.RAW_CONTACT_IS_USER_PROFILE) .addAll(sRawContactColumns) .addAll(sRawContactSyncColumns) .addAll(sDataColumns) .build(); /** Contains the columns from the contact entity view*/ private static final ProjectionMap sEntityProjectionMap = ProjectionMap.builder() .add(Contacts.Entity._ID) .add(Contacts.Entity.CONTACT_ID) .add(Contacts.Entity.RAW_CONTACT_ID) .add(Contacts.Entity.DATA_ID) .add(Contacts.Entity.NAME_RAW_CONTACT_ID) .add(Contacts.Entity.DELETED) .add(Contacts.IS_USER_PROFILE) .addAll(sContactsColumns) .addAll(sContactPresenceColumns) .addAll(sRawContactColumns) .addAll(sRawContactSyncColumns) .addAll(sDataColumns) .addAll(sDataPresenceColumns) .build(); /** Contains columns from the data view */ private static final ProjectionMap sDataProjectionMap = ProjectionMap.builder() .add(Data._ID) .add(Data.RAW_CONTACT_ID) .add(Data.CONTACT_ID) .add(Data.NAME_RAW_CONTACT_ID) .add(RawContacts.RAW_CONTACT_IS_USER_PROFILE) .addAll(sDataColumns) .addAll(sDataPresenceColumns) .addAll(sRawContactColumns) .addAll(sContactsColumns) .addAll(sContactPresenceColumns) .build(); /** Contains columns from the data view */ private static final ProjectionMap sDistinctDataProjectionMap = ProjectionMap.builder() .add(Data._ID, "MIN(" + Data._ID + ")") .add(RawContacts.CONTACT_ID) .add(RawContacts.RAW_CONTACT_IS_USER_PROFILE) .addAll(sDataColumns) .addAll(sDataPresenceColumns) .addAll(sContactsColumns) .addAll(sContactPresenceColumns) .build(); /** Contains the data and contacts columns, for joined tables */ private static final ProjectionMap sPhoneLookupProjectionMap = ProjectionMap.builder() .add(PhoneLookup._ID, "contacts_view." + Contacts._ID) .add(PhoneLookup.LOOKUP_KEY, "contacts_view." + Contacts.LOOKUP_KEY) .add(PhoneLookup.DISPLAY_NAME, "contacts_view." + Contacts.DISPLAY_NAME) .add(PhoneLookup.LAST_TIME_CONTACTED, "contacts_view." + Contacts.LAST_TIME_CONTACTED) .add(PhoneLookup.TIMES_CONTACTED, "contacts_view." + Contacts.TIMES_CONTACTED) .add(PhoneLookup.STARRED, "contacts_view." + Contacts.STARRED) .add(PhoneLookup.IN_VISIBLE_GROUP, "contacts_view." + Contacts.IN_VISIBLE_GROUP) .add(PhoneLookup.PHOTO_ID, "contacts_view." + Contacts.PHOTO_ID) .add(PhoneLookup.PHOTO_URI, "contacts_view." + Contacts.PHOTO_URI) .add(PhoneLookup.PHOTO_THUMBNAIL_URI, "contacts_view." + Contacts.PHOTO_THUMBNAIL_URI) .add(PhoneLookup.CUSTOM_RINGTONE, "contacts_view." + Contacts.CUSTOM_RINGTONE) .add(PhoneLookup.HAS_PHONE_NUMBER, "contacts_view." + Contacts.HAS_PHONE_NUMBER) .add(PhoneLookup.SEND_TO_VOICEMAIL, "contacts_view." + Contacts.SEND_TO_VOICEMAIL) .add(PhoneLookup.NUMBER, Phone.NUMBER) .add(PhoneLookup.TYPE, Phone.TYPE) .add(PhoneLookup.LABEL, Phone.LABEL) .add(PhoneLookup.NORMALIZED_NUMBER, Phone.NORMALIZED_NUMBER) .build(); /** Contains the just the {@link Groups} columns */ private static final ProjectionMap sGroupsProjectionMap = ProjectionMap.builder() .add(Groups._ID) .add(Groups.ACCOUNT_NAME) .add(Groups.ACCOUNT_TYPE) .add(Groups.DATA_SET) .add(Groups.ACCOUNT_TYPE_AND_DATA_SET) .add(Groups.SOURCE_ID) .add(Groups.DIRTY) .add(Groups.VERSION) .add(Groups.RES_PACKAGE) .add(Groups.TITLE) .add(Groups.TITLE_RES) .add(Groups.GROUP_VISIBLE) .add(Groups.SYSTEM_ID) .add(Groups.DELETED) .add(Groups.NOTES) .add(Groups.ACTION) .add(Groups.ACTION_URI) .add(Groups.SHOULD_SYNC) .add(Groups.FAVORITES) .add(Groups.AUTO_ADD) .add(Groups.GROUP_IS_READ_ONLY) .add(Groups.SYNC1) .add(Groups.SYNC2) .add(Groups.SYNC3) .add(Groups.SYNC4) .build(); /** Contains {@link Groups} columns along with summary details */ private static final ProjectionMap sGroupsSummaryProjectionMap = ProjectionMap.builder() .addAll(sGroupsProjectionMap) .add(Groups.SUMMARY_COUNT, "(SELECT COUNT(" + ContactsColumns.CONCRETE_ID + ") FROM " + Tables.CONTACTS_JOIN_RAW_CONTACTS_DATA_FILTERED_BY_GROUPMEMBERSHIP + ")") .add(Groups.SUMMARY_WITH_PHONES, "(SELECT COUNT(" + ContactsColumns.CONCRETE_ID + ") FROM " + Tables.CONTACTS_JOIN_RAW_CONTACTS_DATA_FILTERED_BY_GROUPMEMBERSHIP + " WHERE " + Contacts.HAS_PHONE_NUMBER + ")") .build(); // This is only exposed as hidden API for the contacts app, so we can be very specific in // the filtering private static final ProjectionMap sGroupsSummaryProjectionMapWithGroupCountPerAccount = ProjectionMap.builder() .addAll(sGroupsSummaryProjectionMap) .add(Groups.SUMMARY_GROUP_COUNT_PER_ACCOUNT, "(SELECT COUNT(*) FROM " + Views.GROUPS + " WHERE " + "(" + Groups.ACCOUNT_NAME + "=" + GroupsColumns.CONCRETE_ACCOUNT_NAME + " AND " + Groups.ACCOUNT_TYPE + "=" + GroupsColumns.CONCRETE_ACCOUNT_TYPE + " AND " + Groups.DELETED + "=0 AND " + Groups.FAVORITES + "=0 AND " + Groups.AUTO_ADD + "=0" + ")" + " GROUP BY " + Groups.ACCOUNT_NAME + ", " + Groups.ACCOUNT_TYPE + ")") .build(); /** Contains the agg_exceptions columns */ private static final ProjectionMap sAggregationExceptionsProjectionMap = ProjectionMap.builder() .add(AggregationExceptionColumns._ID, Tables.AGGREGATION_EXCEPTIONS + "._id") .add(AggregationExceptions.TYPE) .add(AggregationExceptions.RAW_CONTACT_ID1) .add(AggregationExceptions.RAW_CONTACT_ID2) .build(); /** Contains the agg_exceptions columns */ private static final ProjectionMap sSettingsProjectionMap = ProjectionMap.builder() .add(Settings.ACCOUNT_NAME) .add(Settings.ACCOUNT_TYPE) .add(Settings.UNGROUPED_VISIBLE) .add(Settings.SHOULD_SYNC) .add(Settings.ANY_UNSYNCED, "(CASE WHEN MIN(" + Settings.SHOULD_SYNC + ",(SELECT " + "(CASE WHEN MIN(" + Groups.SHOULD_SYNC + ") IS NULL" + " THEN 1" + " ELSE MIN(" + Groups.SHOULD_SYNC + ")" + " END)" + " FROM " + Tables.GROUPS + " WHERE " + GroupsColumns.CONCRETE_ACCOUNT_NAME + "=" + SettingsColumns.CONCRETE_ACCOUNT_NAME + " AND " + GroupsColumns.CONCRETE_ACCOUNT_TYPE + "=" + SettingsColumns.CONCRETE_ACCOUNT_TYPE + "))=0" + " THEN 1" + " ELSE 0" + " END)") .add(Settings.UNGROUPED_COUNT, "(SELECT COUNT(*)" + " FROM (SELECT 1" + " FROM " + Tables.SETTINGS_JOIN_RAW_CONTACTS_DATA_MIMETYPES_CONTACTS + " GROUP BY " + Clauses.GROUP_BY_ACCOUNT_CONTACT_ID + " HAVING " + Clauses.HAVING_NO_GROUPS + "))") .add(Settings.UNGROUPED_WITH_PHONES, "(SELECT COUNT(*)" + " FROM (SELECT 1" + " FROM " + Tables.SETTINGS_JOIN_RAW_CONTACTS_DATA_MIMETYPES_CONTACTS + " WHERE " + Contacts.HAS_PHONE_NUMBER + " GROUP BY " + Clauses.GROUP_BY_ACCOUNT_CONTACT_ID + " HAVING " + Clauses.HAVING_NO_GROUPS + "))") .build(); /** Contains StatusUpdates columns */ private static final ProjectionMap sStatusUpdatesProjectionMap = ProjectionMap.builder() .add(PresenceColumns.RAW_CONTACT_ID) .add(StatusUpdates.DATA_ID, DataColumns.CONCRETE_ID) .add(StatusUpdates.IM_ACCOUNT) .add(StatusUpdates.IM_HANDLE) .add(StatusUpdates.PROTOCOL) // We cannot allow a null in the custom protocol field, because SQLite3 does not // properly enforce uniqueness of null values .add(StatusUpdates.CUSTOM_PROTOCOL, "(CASE WHEN " + StatusUpdates.CUSTOM_PROTOCOL + "=''" + " THEN NULL" + " ELSE " + StatusUpdates.CUSTOM_PROTOCOL + " END)") .add(StatusUpdates.PRESENCE) .add(StatusUpdates.CHAT_CAPABILITY) .add(StatusUpdates.STATUS) .add(StatusUpdates.STATUS_TIMESTAMP) .add(StatusUpdates.STATUS_RES_PACKAGE) .add(StatusUpdates.STATUS_ICON) .add(StatusUpdates.STATUS_LABEL) .build(); /** Contains StreamItems columns */ private static final ProjectionMap sStreamItemsProjectionMap = ProjectionMap.builder() .add(StreamItems._ID, StreamItemsColumns.CONCRETE_ID) .add(RawContacts.CONTACT_ID) .add(StreamItems.RAW_CONTACT_ID) .add(StreamItems.RES_PACKAGE) .add(StreamItems.RES_ICON) .add(StreamItems.RES_LABEL) .add(StreamItems.TEXT) .add(StreamItems.TIMESTAMP) .add(StreamItems.COMMENTS) .add(StreamItems.ACTION) .add(StreamItems.ACTION_URI) .build(); private static final ProjectionMap sStreamItemPhotosProjectionMap = ProjectionMap.builder() .add(StreamItemPhotos._ID, StreamItemPhotosColumns.CONCRETE_ID) .add(StreamItems.RAW_CONTACT_ID) .add(StreamItemPhotos.STREAM_ITEM_ID) .add(StreamItemPhotos.SORT_INDEX) .add(StreamItemPhotos.PHOTO_FILE_ID) .add(StreamItemPhotos.PHOTO_URI, "'" + DisplayPhoto.CONTENT_URI + "'||'/'||" + StreamItemPhotos.PHOTO_FILE_ID) .add(StreamItemPhotos.ACTION, StreamItemPhotosColumns.CONCRETE_ACTION) .add(StreamItemPhotos.ACTION_URI, StreamItemPhotosColumns.CONCRETE_ACTION_URI) .add(PhotoFiles.HEIGHT) .add(PhotoFiles.WIDTH) .add(PhotoFiles.FILESIZE) .build(); /** Contains Live Folders columns */ private static final ProjectionMap sLiveFoldersProjectionMap = ProjectionMap.builder() .add(LiveFolders._ID, Contacts._ID) .add(LiveFolders.NAME, Contacts.DISPLAY_NAME) // TODO: Put contact photo back when we have a way to display a default icon // for contacts without a photo // .add(LiveFolders.ICON_BITMAP, Photos.DATA) .build(); /** Contains {@link Directory} columns */ private static final ProjectionMap sDirectoryProjectionMap = ProjectionMap.builder() .add(Directory._ID) .add(Directory.PACKAGE_NAME) .add(Directory.TYPE_RESOURCE_ID) .add(Directory.DISPLAY_NAME) .add(Directory.DIRECTORY_AUTHORITY) .add(Directory.ACCOUNT_TYPE) .add(Directory.ACCOUNT_NAME) .add(Directory.EXPORT_SUPPORT) .add(Directory.SHORTCUT_SUPPORT) .add(Directory.PHOTO_SUPPORT) .build(); // where clause to update the status_updates table private static final String WHERE_CLAUSE_FOR_STATUS_UPDATES_TABLE = StatusUpdatesColumns.DATA_ID + " IN (SELECT Distinct " + StatusUpdates.DATA_ID + " FROM " + Tables.STATUS_UPDATES + " LEFT OUTER JOIN " + Tables.PRESENCE + " ON " + StatusUpdatesColumns.DATA_ID + " = " + StatusUpdates.DATA_ID + " WHERE "; private static final String[] EMPTY_STRING_ARRAY = new String[0]; /** * Notification ID for failure to import contacts. */ private static final int LEGACY_IMPORT_FAILED_NOTIFICATION = 1; private static final String DEFAULT_SNIPPET_ARG_START_MATCH = "["; private static final String DEFAULT_SNIPPET_ARG_END_MATCH = "]"; private static final String DEFAULT_SNIPPET_ARG_ELLIPSIS = "..."; private static final int DEFAULT_SNIPPET_ARG_MAX_TOKENS = -10; private boolean sIsPhoneInitialized; private boolean sIsPhone; private StringBuilder mSb = new StringBuilder(); private String[] mSelectionArgs1 = new String[1]; private String[] mSelectionArgs2 = new String[2]; private ArrayList<String> mSelectionArgs = Lists.newArrayList(); private Account mAccount; /** * Stores mapping from type Strings exposed via {@link DataUsageFeedback} to * type integers in {@link DataUsageStatColumns}. */ private static final Map<String, Integer> sDataUsageTypeMap; static { // Contacts URI matching table final UriMatcher matcher = sUriMatcher; matcher.addURI(ContactsContract.AUTHORITY, "contacts", CONTACTS); matcher.addURI(ContactsContract.AUTHORITY, "contacts/#", CONTACTS_ID); matcher.addURI(ContactsContract.AUTHORITY, "contacts/#/data", CONTACTS_ID_DATA); matcher.addURI(ContactsContract.AUTHORITY, "contacts/#/entities", CONTACTS_ID_ENTITIES); matcher.addURI(ContactsContract.AUTHORITY, "contacts/#/suggestions", AGGREGATION_SUGGESTIONS); matcher.addURI(ContactsContract.AUTHORITY, "contacts/#/suggestions/*", AGGREGATION_SUGGESTIONS); matcher.addURI(ContactsContract.AUTHORITY, "contacts/#/photo", CONTACTS_ID_PHOTO); matcher.addURI(ContactsContract.AUTHORITY, "contacts/#/display_photo", CONTACTS_ID_DISPLAY_PHOTO); matcher.addURI(ContactsContract.AUTHORITY, "contacts/#/stream_items", CONTACTS_ID_STREAM_ITEMS); matcher.addURI(ContactsContract.AUTHORITY, "contacts/filter", CONTACTS_FILTER); matcher.addURI(ContactsContract.AUTHORITY, "contacts/filter/*", CONTACTS_FILTER); matcher.addURI(ContactsContract.AUTHORITY, "contacts/lookup/*", CONTACTS_LOOKUP); matcher.addURI(ContactsContract.AUTHORITY, "contacts/lookup/*/data", CONTACTS_LOOKUP_DATA); matcher.addURI(ContactsContract.AUTHORITY, "contacts/lookup/*/#", CONTACTS_LOOKUP_ID); matcher.addURI(ContactsContract.AUTHORITY, "contacts/lookup/*/#/data", CONTACTS_LOOKUP_ID_DATA); matcher.addURI(ContactsContract.AUTHORITY, "contacts/lookup/*/display_photo", CONTACTS_LOOKUP_DISPLAY_PHOTO); matcher.addURI(ContactsContract.AUTHORITY, "contacts/lookup/*/#/display_photo", CONTACTS_LOOKUP_ID_DISPLAY_PHOTO); matcher.addURI(ContactsContract.AUTHORITY, "contacts/lookup/*/entities", CONTACTS_LOOKUP_ENTITIES); matcher.addURI(ContactsContract.AUTHORITY, "contacts/lookup/*/#/entities", CONTACTS_LOOKUP_ID_ENTITIES); matcher.addURI(ContactsContract.AUTHORITY, "contacts/lookup/*/stream_items", CONTACTS_LOOKUP_STREAM_ITEMS); matcher.addURI(ContactsContract.AUTHORITY, "contacts/lookup/*/#/stream_items", CONTACTS_LOOKUP_ID_STREAM_ITEMS); matcher.addURI(ContactsContract.AUTHORITY, "contacts/as_vcard/*", CONTACTS_AS_VCARD); matcher.addURI(ContactsContract.AUTHORITY, "contacts/as_multi_vcard/*", CONTACTS_AS_MULTI_VCARD); matcher.addURI(ContactsContract.AUTHORITY, "contacts/strequent/", CONTACTS_STREQUENT); matcher.addURI(ContactsContract.AUTHORITY, "contacts/strequent/filter/*", CONTACTS_STREQUENT_FILTER); matcher.addURI(ContactsContract.AUTHORITY, "contacts/group/*", CONTACTS_GROUP); matcher.addURI(ContactsContract.AUTHORITY, "contacts/frequent", CONTACTS_FREQUENT); matcher.addURI(ContactsContract.AUTHORITY, "raw_contacts", RAW_CONTACTS); matcher.addURI(ContactsContract.AUTHORITY, "raw_contacts/#", RAW_CONTACTS_ID); matcher.addURI(ContactsContract.AUTHORITY, "raw_contacts/#/data", RAW_CONTACTS_DATA); matcher.addURI(ContactsContract.AUTHORITY, "raw_contacts/#/display_photo", RAW_CONTACTS_ID_DISPLAY_PHOTO); matcher.addURI(ContactsContract.AUTHORITY, "raw_contacts/#/entity", RAW_CONTACT_ENTITY_ID); matcher.addURI(ContactsContract.AUTHORITY, "raw_contacts/#/stream_items", RAW_CONTACTS_ID_STREAM_ITEMS); matcher.addURI(ContactsContract.AUTHORITY, "raw_contact_entities", RAW_CONTACT_ENTITIES); matcher.addURI(ContactsContract.AUTHORITY, "data", DATA); matcher.addURI(ContactsContract.AUTHORITY, "data/#", DATA_ID); matcher.addURI(ContactsContract.AUTHORITY, "data/phones", PHONES); matcher.addURI(ContactsContract.AUTHORITY, "data/phones/#", PHONES_ID); matcher.addURI(ContactsContract.AUTHORITY, "data/phones/filter", PHONES_FILTER); matcher.addURI(ContactsContract.AUTHORITY, "data/phones/filter/*", PHONES_FILTER); matcher.addURI(ContactsContract.AUTHORITY, "data/emails", EMAILS); matcher.addURI(ContactsContract.AUTHORITY, "data/emails/#", EMAILS_ID); matcher.addURI(ContactsContract.AUTHORITY, "data/emails/lookup", EMAILS_LOOKUP); matcher.addURI(ContactsContract.AUTHORITY, "data/emails/lookup/*", EMAILS_LOOKUP); matcher.addURI(ContactsContract.AUTHORITY, "data/emails/filter", EMAILS_FILTER); matcher.addURI(ContactsContract.AUTHORITY, "data/emails/filter/*", EMAILS_FILTER); matcher.addURI(ContactsContract.AUTHORITY, "data/postals", POSTALS); matcher.addURI(ContactsContract.AUTHORITY, "data/postals/#", POSTALS_ID); /** "*" is in CSV form with data ids ("123,456,789") */ matcher.addURI(ContactsContract.AUTHORITY, "data/usagefeedback/*", DATA_USAGE_FEEDBACK_ID); matcher.addURI(ContactsContract.AUTHORITY, "groups", GROUPS); matcher.addURI(ContactsContract.AUTHORITY, "groups/#", GROUPS_ID); matcher.addURI(ContactsContract.AUTHORITY, "groups_summary", GROUPS_SUMMARY); matcher.addURI(ContactsContract.AUTHORITY, SyncStateContentProviderHelper.PATH, SYNCSTATE); matcher.addURI(ContactsContract.AUTHORITY, SyncStateContentProviderHelper.PATH + "/#", SYNCSTATE_ID); matcher.addURI(ContactsContract.AUTHORITY, "phone_lookup/*", PHONE_LOOKUP); matcher.addURI(ContactsContract.AUTHORITY, "aggregation_exceptions", AGGREGATION_EXCEPTIONS); matcher.addURI(ContactsContract.AUTHORITY, "aggregation_exceptions/*", AGGREGATION_EXCEPTION_ID); matcher.addURI(ContactsContract.AUTHORITY, "settings", SETTINGS); matcher.addURI(ContactsContract.AUTHORITY, "status_updates", STATUS_UPDATES); matcher.addURI(ContactsContract.AUTHORITY, "status_updates/#", STATUS_UPDATES_ID); matcher.addURI(ContactsContract.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, SEARCH_SUGGESTIONS); matcher.addURI(ContactsContract.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", SEARCH_SUGGESTIONS); matcher.addURI(ContactsContract.AUTHORITY, SearchManager.SUGGEST_URI_PATH_SHORTCUT + "/*", SEARCH_SHORTCUT); matcher.addURI(ContactsContract.AUTHORITY, "live_folders/contacts", LIVE_FOLDERS_CONTACTS); matcher.addURI(ContactsContract.AUTHORITY, "live_folders/contacts/*", LIVE_FOLDERS_CONTACTS_GROUP_NAME); matcher.addURI(ContactsContract.AUTHORITY, "live_folders/contacts_with_phones", LIVE_FOLDERS_CONTACTS_WITH_PHONES); matcher.addURI(ContactsContract.AUTHORITY, "live_folders/favorites", LIVE_FOLDERS_CONTACTS_FAVORITES); matcher.addURI(ContactsContract.AUTHORITY, "provider_status", PROVIDER_STATUS); matcher.addURI(ContactsContract.AUTHORITY, "directories", DIRECTORIES); matcher.addURI(ContactsContract.AUTHORITY, "directories/#", DIRECTORIES_ID); matcher.addURI(ContactsContract.AUTHORITY, "complete_name", COMPLETE_NAME); matcher.addURI(ContactsContract.AUTHORITY, "profile", PROFILE); matcher.addURI(ContactsContract.AUTHORITY, "profile/entities", PROFILE_ENTITIES); matcher.addURI(ContactsContract.AUTHORITY, "profile/data", PROFILE_DATA); matcher.addURI(ContactsContract.AUTHORITY, "profile/data/#", PROFILE_DATA_ID); matcher.addURI(ContactsContract.AUTHORITY, "profile/as_vcard", PROFILE_AS_VCARD); matcher.addURI(ContactsContract.AUTHORITY, "profile/raw_contacts", PROFILE_RAW_CONTACTS); matcher.addURI(ContactsContract.AUTHORITY, "profile/raw_contacts/#", PROFILE_RAW_CONTACTS_ID); matcher.addURI(ContactsContract.AUTHORITY, "profile/raw_contacts/#/data", PROFILE_RAW_CONTACTS_ID_DATA); matcher.addURI(ContactsContract.AUTHORITY, "profile/raw_contacts/#/entity", PROFILE_RAW_CONTACTS_ID_ENTITIES); matcher.addURI(ContactsContract.AUTHORITY, "stream_items", STREAM_ITEMS); matcher.addURI(ContactsContract.AUTHORITY, "stream_items/photo", STREAM_ITEMS_PHOTOS); matcher.addURI(ContactsContract.AUTHORITY, "stream_items/#", STREAM_ITEMS_ID); matcher.addURI(ContactsContract.AUTHORITY, "stream_items/#/photo", STREAM_ITEMS_ID_PHOTOS); matcher.addURI(ContactsContract.AUTHORITY, "stream_items/#/photo/#", STREAM_ITEMS_ID_PHOTOS_ID); matcher.addURI(ContactsContract.AUTHORITY, "stream_items_limit", STREAM_ITEMS_LIMIT); matcher.addURI(ContactsContract.AUTHORITY, "display_photo/*", DISPLAY_PHOTO); matcher.addURI(ContactsContract.AUTHORITY, "photo_dimensions", PHOTO_DIMENSIONS); HashMap<String, Integer> tmpTypeMap = new HashMap<String, Integer>(); tmpTypeMap.put(DataUsageFeedback.USAGE_TYPE_CALL, DataUsageStatColumns.USAGE_TYPE_INT_CALL); tmpTypeMap.put(DataUsageFeedback.USAGE_TYPE_LONG_TEXT, DataUsageStatColumns.USAGE_TYPE_INT_LONG_TEXT); tmpTypeMap.put(DataUsageFeedback.USAGE_TYPE_SHORT_TEXT, DataUsageStatColumns.USAGE_TYPE_INT_SHORT_TEXT); sDataUsageTypeMap = Collections.unmodifiableMap(tmpTypeMap); } private static class DirectoryInfo { String authority; String accountName; String accountType; } /** * Cached information about contact directories. */ private HashMap<String, DirectoryInfo> mDirectoryCache = new HashMap<String, DirectoryInfo>(); private boolean mDirectoryCacheValid = false; /** * An entry in group id cache. It maps the combination of (account type, account name, data set, * and source id) to group row id. */ public static class GroupIdCacheEntry { String accountType; String accountName; String dataSet; String sourceId; long groupId; } // We don't need a soft cache for groups - the assumption is that there will only // be a small number of contact groups. The cache is keyed off source id. The value // is a list of groups with this group id. private HashMap<String, ArrayList<GroupIdCacheEntry>> mGroupIdCache = Maps.newHashMap(); /** * Cached information about the contact ID and raw contact IDs that make up the user's * profile entry. */ private static class ProfileIdCache { boolean inited; long profileContactId; Set<Long> profileRawContactIds = Sets.newHashSet(); Set<Long> profileDataIds = Sets.newHashSet(); /** * Initializes the cache of profile contact and raw contact IDs. Does nothing if * the cache is already initialized (unless forceRefresh is set to true). * @param db The contacts database. * @param forceRefresh Whether to force re-initialization of the cache. */ private void init(SQLiteDatabase db, boolean forceRefresh) { if (!inited || forceRefresh) { profileContactId = 0; profileRawContactIds.clear(); profileDataIds.clear(); Cursor c = db.rawQuery("SELECT " + RawContactsColumns.CONCRETE_CONTACT_ID + "," + RawContactsColumns.CONCRETE_ID + "," + DataColumns.CONCRETE_ID + " FROM " + Tables.RAW_CONTACTS + " JOIN " + Tables.ACCOUNTS + " ON " + RawContactsColumns.CONCRETE_ID + "=" + AccountsColumns.PROFILE_RAW_CONTACT_ID + " JOIN " + Tables.DATA + " ON " + RawContactsColumns.CONCRETE_ID + "=" + DataColumns.CONCRETE_RAW_CONTACT_ID, null); try { while (c.moveToNext()) { if (profileContactId == 0) { profileContactId = c.getLong(0); } profileRawContactIds.add(c.getLong(1)); profileDataIds.add(c.getLong(2)); } } finally { c.close(); } } } } private ProfileIdCache mProfileIdCache; /** * Maximum dimension (height or width) of display photos. Larger images will be scaled * to fit. */ private int mMaxDisplayPhotoDim; /** * Maximum dimension (height or width) of photo thumbnails. */ private int mMaxThumbnailPhotoDim; private HashMap<String, DataRowHandler> mDataRowHandlers; private ContactsDatabaseHelper mDbHelper; private PhotoStore mPhotoStore; private NameSplitter mNameSplitter; private NameLookupBuilder mNameLookupBuilder; private PostalSplitter mPostalSplitter; private ContactDirectoryManager mContactDirectoryManager; private ContactAggregator mContactAggregator; private LegacyApiSupport mLegacyApiSupport; private GlobalSearchSupport mGlobalSearchSupport; private CommonNicknameCache mCommonNicknameCache; private SearchIndexManager mSearchIndexManager; private ContentValues mValues = new ContentValues(); private HashMap<String, Boolean> mAccountWritability = Maps.newHashMap(); private int mProviderStatus = ProviderStatus.STATUS_NORMAL; private boolean mProviderStatusUpdateNeeded; private long mEstimatedStorageRequirement = 0; private volatile CountDownLatch mReadAccessLatch; private volatile CountDownLatch mWriteAccessLatch; private boolean mAccountUpdateListenerRegistered; private boolean mOkToOpenAccess = true; private TransactionContext mTransactionContext = new TransactionContext(); private boolean mVisibleTouched = false; private boolean mSyncToNetwork; private Locale mCurrentLocale; private int mContactsAccountCount; private HandlerThread mBackgroundThread; private Handler mBackgroundHandler; private long mLastPhotoCleanup = 0; @Override public boolean onCreate() { super.onCreate(); try { return initialize(); } catch (RuntimeException e) { Log.e(TAG, "Cannot start provider", e); return false; } } private boolean initialize() { StrictMode.setThreadPolicy( new StrictMode.ThreadPolicy.Builder().detectAll().penaltyLog().build()); Resources resources = getContext().getResources(); mMaxDisplayPhotoDim = resources.getInteger( R.integer.config_max_display_photo_dim); mMaxThumbnailPhotoDim = resources.getInteger( R.integer.config_max_thumbnail_photo_dim); mProfileIdCache = new ProfileIdCache(); mDbHelper = (ContactsDatabaseHelper)getDatabaseHelper(); mContactDirectoryManager = new ContactDirectoryManager(this); mGlobalSearchSupport = new GlobalSearchSupport(this); // The provider is closed for business until fully initialized mReadAccessLatch = new CountDownLatch(1); mWriteAccessLatch = new CountDownLatch(1); mBackgroundThread = new HandlerThread("ContactsProviderWorker", Process.THREAD_PRIORITY_BACKGROUND); mBackgroundThread.start(); mBackgroundHandler = new Handler(mBackgroundThread.getLooper()) { @Override public void handleMessage(Message msg) { performBackgroundTask(msg.what, msg.obj); } }; scheduleBackgroundTask(BACKGROUND_TASK_INITIALIZE); scheduleBackgroundTask(BACKGROUND_TASK_IMPORT_LEGACY_CONTACTS); scheduleBackgroundTask(BACKGROUND_TASK_UPDATE_ACCOUNTS); scheduleBackgroundTask(BACKGROUND_TASK_UPDATE_LOCALE); scheduleBackgroundTask(BACKGROUND_TASK_UPGRADE_AGGREGATION_ALGORITHM); scheduleBackgroundTask(BACKGROUND_TASK_UPDATE_SEARCH_INDEX); scheduleBackgroundTask(BACKGROUND_TASK_UPDATE_PROVIDER_STATUS); scheduleBackgroundTask(BACKGROUND_TASK_OPEN_WRITE_ACCESS); scheduleBackgroundTask(BACKGROUND_TASK_CLEANUP_PHOTOS); return true; } /** * (Re)allocates all locale-sensitive structures. */ private void initForDefaultLocale() { Context context = getContext(); mLegacyApiSupport = new LegacyApiSupport(context, mDbHelper, this, mGlobalSearchSupport); mCurrentLocale = getLocale(); mNameSplitter = mDbHelper.createNameSplitter(); mNameLookupBuilder = new StructuredNameLookupBuilder(mNameSplitter); mPostalSplitter = new PostalSplitter(mCurrentLocale); mCommonNicknameCache = new CommonNicknameCache(mDbHelper.getReadableDatabase()); ContactLocaleUtils.getIntance().setLocale(mCurrentLocale); mContactAggregator = new ContactAggregator(this, mDbHelper, createPhotoPriorityResolver(context), mNameSplitter, mCommonNicknameCache); mContactAggregator.setEnabled(SystemProperties.getBoolean(AGGREGATE_CONTACTS, true)); mSearchIndexManager = new SearchIndexManager(this); mPhotoStore = new PhotoStore(getContext().getFilesDir(), mDbHelper); mDataRowHandlers = new HashMap<String, DataRowHandler>(); mDataRowHandlers.put(Email.CONTENT_ITEM_TYPE, new DataRowHandlerForEmail(context, mDbHelper, mContactAggregator)); mDataRowHandlers.put(Im.CONTENT_ITEM_TYPE, new DataRowHandlerForIm(context, mDbHelper, mContactAggregator)); mDataRowHandlers.put(Organization.CONTENT_ITEM_TYPE, new DataRowHandlerForOrganization(context, mDbHelper, mContactAggregator)); mDataRowHandlers.put(Phone.CONTENT_ITEM_TYPE, new DataRowHandlerForPhoneNumber(context, mDbHelper, mContactAggregator)); mDataRowHandlers.put(Nickname.CONTENT_ITEM_TYPE, new DataRowHandlerForNickname(context, mDbHelper, mContactAggregator)); mDataRowHandlers.put(StructuredName.CONTENT_ITEM_TYPE, new DataRowHandlerForStructuredName(context, mDbHelper, mContactAggregator, mNameSplitter, mNameLookupBuilder)); mDataRowHandlers.put(StructuredPostal.CONTENT_ITEM_TYPE, new DataRowHandlerForStructuredPostal(context, mDbHelper, mContactAggregator, mPostalSplitter)); mDataRowHandlers.put(GroupMembership.CONTENT_ITEM_TYPE, new DataRowHandlerForGroupMembership(context, mDbHelper, mContactAggregator, mGroupIdCache)); mDataRowHandlers.put(Photo.CONTENT_ITEM_TYPE, new DataRowHandlerForPhoto(context, mDbHelper, mContactAggregator, mPhotoStore)); mDataRowHandlers.put(Note.CONTENT_ITEM_TYPE, new DataRowHandlerForNote(context, mDbHelper, mContactAggregator)); } /** * Visible for testing. */ /* package */ PhotoPriorityResolver createPhotoPriorityResolver(Context context) { return new PhotoPriorityResolver(context); } protected void scheduleBackgroundTask(int task) { mBackgroundHandler.sendEmptyMessage(task); } protected void scheduleBackgroundTask(int task, Object arg) { mBackgroundHandler.sendMessage(mBackgroundHandler.obtainMessage(task, arg)); } protected void performBackgroundTask(int task, Object arg) { switch (task) { case BACKGROUND_TASK_INITIALIZE: { initForDefaultLocale(); mReadAccessLatch.countDown(); mReadAccessLatch = null; break; } case BACKGROUND_TASK_OPEN_WRITE_ACCESS: { if (mOkToOpenAccess) { mWriteAccessLatch.countDown(); mWriteAccessLatch = null; } break; } case BACKGROUND_TASK_IMPORT_LEGACY_CONTACTS: { if (isLegacyContactImportNeeded()) { importLegacyContactsInBackground(); } break; } case BACKGROUND_TASK_UPDATE_ACCOUNTS: { Context context = getContext(); if (!mAccountUpdateListenerRegistered) { AccountManager.get(context).addOnAccountsUpdatedListener(this, null, false); mAccountUpdateListenerRegistered = true; } Account[] accounts = AccountManager.get(context).getAccounts(); boolean accountsChanged = updateAccountsInBackground(accounts); updateContactsAccountCount(accounts); updateDirectoriesInBackground(accountsChanged); break; } case BACKGROUND_TASK_UPDATE_LOCALE: { updateLocaleInBackground(); break; } case BACKGROUND_TASK_CHANGE_LOCALE: { changeLocaleInBackground(); break; } case BACKGROUND_TASK_UPGRADE_AGGREGATION_ALGORITHM: { if (isAggregationUpgradeNeeded()) { upgradeAggregationAlgorithmInBackground(); } break; } case BACKGROUND_TASK_UPDATE_SEARCH_INDEX: { updateSearchIndexInBackground(); break; } case BACKGROUND_TASK_UPDATE_PROVIDER_STATUS: { updateProviderStatus(); break; } case BACKGROUND_TASK_UPDATE_DIRECTORIES: { if (arg != null) { mContactDirectoryManager.onPackageChanged((String) arg); } break; } case BACKGROUND_TASK_CLEANUP_PHOTOS: { // Check rate limit. long now = System.currentTimeMillis(); if (now - mLastPhotoCleanup > PHOTO_CLEANUP_RATE_LIMIT) { mLastPhotoCleanup = now; cleanupPhotoStore(); break; } } } } public void onLocaleChanged() { if (mProviderStatus != ProviderStatus.STATUS_NORMAL && mProviderStatus != ProviderStatus.STATUS_NO_ACCOUNTS_NO_CONTACTS) { return; } scheduleBackgroundTask(BACKGROUND_TASK_CHANGE_LOCALE); } /** * Verifies that the contacts database is properly configured for the current locale. * If not, changes the database locale to the current locale using an asynchronous task. * This needs to be done asynchronously because the process involves rebuilding * large data structures (name lookup, sort keys), which can take minutes on * a large set of contacts. */ protected void updateLocaleInBackground() { // The process is already running - postpone the change if (mProviderStatus == ProviderStatus.STATUS_CHANGING_LOCALE) { return; } final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext()); final String providerLocale = prefs.getString(PREF_LOCALE, null); final Locale currentLocale = mCurrentLocale; if (currentLocale.toString().equals(providerLocale)) { return; } int providerStatus = mProviderStatus; setProviderStatus(ProviderStatus.STATUS_CHANGING_LOCALE); mDbHelper.setLocale(this, currentLocale); prefs.edit().putString(PREF_LOCALE, currentLocale.toString()).apply(); setProviderStatus(providerStatus); } /** * Reinitializes the provider for a new locale. */ private void changeLocaleInBackground() { // Re-initializing the provider without stopping it. // Locking the database will prevent inserts/updates/deletes from // running at the same time, but queries may still be running // on other threads. Those queries may return inconsistent results. SQLiteDatabase db = mDbHelper.getWritableDatabase(); db.beginTransaction(); try { initForDefaultLocale(); db.setTransactionSuccessful(); } finally { db.endTransaction(); } updateLocaleInBackground(); } protected void updateSearchIndexInBackground() { mSearchIndexManager.updateIndex(); } protected void updateDirectoriesInBackground(boolean rescan) { mContactDirectoryManager.scanAllPackages(rescan); } private void updateProviderStatus() { if (mProviderStatus != ProviderStatus.STATUS_NORMAL && mProviderStatus != ProviderStatus.STATUS_NO_ACCOUNTS_NO_CONTACTS) { return; } if (mContactsAccountCount == 0 && DatabaseUtils.queryNumEntries(mDbHelper.getReadableDatabase(), Tables.CONTACTS, null) == 0) { setProviderStatus(ProviderStatus.STATUS_NO_ACCOUNTS_NO_CONTACTS); } else { setProviderStatus(ProviderStatus.STATUS_NORMAL); } } /* Visible for testing */ protected void cleanupPhotoStore() { SQLiteDatabase db = mDbHelper.getWritableDatabase(); // Assemble the set of photo store file IDs that are in use, and send those to the photo // store. Any photos that aren't in that set will be deleted, and any photos that no // longer exist in the photo store will be returned for us to clear out in the DB. Cursor c = db.query(Views.DATA, new String[]{Data._ID, Photo.PHOTO_FILE_ID}, Data.MIMETYPE + "=" + Photo.MIMETYPE + " AND " + Photo.PHOTO_FILE_ID + " IS NOT NULL", null, null, null, null); Set<Long> usedPhotoFileIds = Sets.newHashSet(); Map<Long, Long> photoFileIdToDataId = Maps.newHashMap(); try { while (c.moveToNext()) { long dataId = c.getLong(0); long photoFileId = c.getLong(1); usedPhotoFileIds.add(photoFileId); photoFileIdToDataId.put(photoFileId, dataId); } } finally { c.close(); } // Also query for all social stream item photos. c = db.query(Tables.STREAM_ITEM_PHOTOS, new String[]{ StreamItemPhotos._ID, StreamItemPhotos.STREAM_ITEM_ID, StreamItemPhotos.PHOTO_FILE_ID }, null, null, null, null, null); Map<Long, Long> photoFileIdToStreamItemPhotoId = Maps.newHashMap(); Map<Long, Long> streamItemPhotoIdToStreamItemId = Maps.newHashMap(); try { while (c.moveToNext()) { long streamItemPhotoId = c.getLong(0); long streamItemId = c.getLong(1); long photoFileId = c.getLong(2); usedPhotoFileIds.add(photoFileId); photoFileIdToStreamItemPhotoId.put(photoFileId, streamItemPhotoId); streamItemPhotoIdToStreamItemId.put(streamItemPhotoId, streamItemId); } } finally { c.close(); } // Run the photo store cleanup. Set<Long> missingPhotoIds = mPhotoStore.cleanup(usedPhotoFileIds); // If any of the keys we're using no longer exist, clean them up. if (!missingPhotoIds.isEmpty()) { ArrayList<ContentProviderOperation> ops = Lists.newArrayList(); for (long missingPhotoId : missingPhotoIds) { if (photoFileIdToDataId.containsKey(missingPhotoId)) { long dataId = photoFileIdToDataId.get(missingPhotoId); ContentValues updateValues = new ContentValues(); updateValues.putNull(Photo.PHOTO_FILE_ID); ops.add(ContentProviderOperation.newUpdate( ContentUris.withAppendedId(Data.CONTENT_URI, dataId)) .withValues(updateValues).build()); } if (photoFileIdToStreamItemPhotoId.containsKey(missingPhotoId)) { // For missing photos that were in stream item photos, just delete the stream // item photo. long streamItemPhotoId = photoFileIdToStreamItemPhotoId.get(missingPhotoId); long streamItemId = streamItemPhotoIdToStreamItemId.get(streamItemPhotoId); ops.add(ContentProviderOperation.newDelete( StreamItems.CONTENT_URI.buildUpon() .appendPath(String.valueOf(streamItemId)) .appendPath(StreamItems.StreamItemPhotos.CONTENT_DIRECTORY) .appendPath(String.valueOf(streamItemPhotoId)) .build()).build()); } } try { applyBatch(ops); } catch (OperationApplicationException oae) { // Not a fatal problem (and we'll try again on the next cleanup). Log.e(TAG, "Failed to clean up outdated photo references", oae); } } } /* Visible for testing */ @Override protected ContactsDatabaseHelper getDatabaseHelper(final Context context) { return ContactsDatabaseHelper.getInstance(context); } @VisibleForTesting /* package */ PhotoStore getPhotoStore() { return mPhotoStore; } /* package */ int getMaxDisplayPhotoDim() { return mMaxDisplayPhotoDim; } /* package */ int getMaxThumbnailPhotoDim() { return mMaxThumbnailPhotoDim; } /* package */ NameSplitter getNameSplitter() { return mNameSplitter; } /* package */ NameLookupBuilder getNameLookupBuilder() { return mNameLookupBuilder; } /* Visible for testing */ public ContactDirectoryManager getContactDirectoryManagerForTest() { return mContactDirectoryManager; } /* Visible for testing */ protected Locale getLocale() { return Locale.getDefault(); } protected boolean isLegacyContactImportNeeded() { int version = Integer.parseInt(mDbHelper.getProperty(PROPERTY_CONTACTS_IMPORTED, "0")); return version < PROPERTY_CONTACTS_IMPORT_VERSION; } protected LegacyContactImporter getLegacyContactImporter() { return new LegacyContactImporter(getContext(), this); } /** * Imports legacy contacts as a background task. */ private void importLegacyContactsInBackground() { Log.v(TAG, "Importing legacy contacts"); setProviderStatus(ProviderStatus.STATUS_UPGRADING); final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext()); mDbHelper.setLocale(this, mCurrentLocale); prefs.edit().putString(PREF_LOCALE, mCurrentLocale.toString()).commit(); LegacyContactImporter importer = getLegacyContactImporter(); if (importLegacyContacts(importer)) { onLegacyContactImportSuccess(); } else { onLegacyContactImportFailure(); } } /** * Unlocks the provider and declares that the import process is complete. */ private void onLegacyContactImportSuccess() { NotificationManager nm = (NotificationManager)getContext().getSystemService(Context.NOTIFICATION_SERVICE); nm.cancel(LEGACY_IMPORT_FAILED_NOTIFICATION); // Store a property in the database indicating that the conversion process succeeded mDbHelper.setProperty(PROPERTY_CONTACTS_IMPORTED, String.valueOf(PROPERTY_CONTACTS_IMPORT_VERSION)); setProviderStatus(ProviderStatus.STATUS_NORMAL); Log.v(TAG, "Completed import of legacy contacts"); } /** * Announces the provider status and keeps the provider locked. */ private void onLegacyContactImportFailure() { Context context = getContext(); NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); // Show a notification Notification n = new Notification(android.R.drawable.stat_notify_error, context.getString(R.string.upgrade_out_of_memory_notification_ticker), System.currentTimeMillis()); n.setLatestEventInfo(context, context.getString(R.string.upgrade_out_of_memory_notification_title), context.getString(R.string.upgrade_out_of_memory_notification_text), PendingIntent.getActivity(context, 0, new Intent(Intents.UI.LIST_DEFAULT), 0)); n.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT; nm.notify(LEGACY_IMPORT_FAILED_NOTIFICATION, n); setProviderStatus(ProviderStatus.STATUS_UPGRADE_OUT_OF_MEMORY); Log.v(TAG, "Failed to import legacy contacts"); // Do not let any database changes until this issue is resolved. mOkToOpenAccess = false; } /* Visible for testing */ /* package */ boolean importLegacyContacts(LegacyContactImporter importer) { boolean aggregatorEnabled = mContactAggregator.isEnabled(); mContactAggregator.setEnabled(false); try { if (importer.importContacts()) { // TODO aggregate all newly added raw contacts mContactAggregator.setEnabled(aggregatorEnabled); return true; } } catch (Throwable e) { Log.e(TAG, "Legacy contact import failed", e); } mEstimatedStorageRequirement = importer.getEstimatedStorageRequirement(); return false; } /** * Wipes all data from the contacts database. */ /* package */ void wipeData() { mDbHelper.wipeData(); mPhotoStore.clear(); mProviderStatus = ProviderStatus.STATUS_NO_ACCOUNTS_NO_CONTACTS; } /** * During intialization, this content provider will * block all attempts to change contacts data. In particular, it will hold * up all contact syncs. As soon as the import process is complete, all * processes waiting to write to the provider are unblocked and can proceed * to compete for the database transaction monitor. */ private void waitForAccess(CountDownLatch latch) { if (latch == null) { return; } while (true) { try { latch.await(); return; } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } @Override public Uri insert(Uri uri, ContentValues values) { waitForAccess(mWriteAccessLatch); return super.insert(uri, values); } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { if (mWriteAccessLatch != null) { // We are stuck trying to upgrade contacts db. The only update request // allowed in this case is an update of provider status, which will trigger // an attempt to upgrade contacts again. int match = sUriMatcher.match(uri); if (match == PROVIDER_STATUS) { Integer newStatus = values.getAsInteger(ProviderStatus.STATUS); if (newStatus != null && newStatus == ProviderStatus.STATUS_UPGRADING) { scheduleBackgroundTask(BACKGROUND_TASK_IMPORT_LEGACY_CONTACTS); return 1; } else { return 0; } } } waitForAccess(mWriteAccessLatch); return super.update(uri, values, selection, selectionArgs); } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { waitForAccess(mWriteAccessLatch); return super.delete(uri, selection, selectionArgs); } @Override public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations) throws OperationApplicationException { waitForAccess(mWriteAccessLatch); return super.applyBatch(operations); } @Override public int bulkInsert(Uri uri, ContentValues[] values) { waitForAccess(mWriteAccessLatch); return super.bulkInsert(uri, values); } @Override protected void onBeginTransaction() { if (VERBOSE_LOGGING) { Log.v(TAG, "onBeginTransaction"); } super.onBeginTransaction(); mContactAggregator.clearPendingAggregations(); mTransactionContext.clear(); } @Override protected void beforeTransactionCommit() { if (VERBOSE_LOGGING) { Log.v(TAG, "beforeTransactionCommit"); } super.beforeTransactionCommit(); flushTransactionalChanges(); mContactAggregator.aggregateInTransaction(mTransactionContext, mDb); if (mVisibleTouched) { mVisibleTouched = false; mDbHelper.updateAllVisible(); } updateSearchIndexInTransaction(); if (mProviderStatusUpdateNeeded) { updateProviderStatus(); mProviderStatusUpdateNeeded = false; } } private void updateSearchIndexInTransaction() { Set<Long> staleContacts = mTransactionContext.getStaleSearchIndexContactIds(); Set<Long> staleRawContacts = mTransactionContext.getStaleSearchIndexRawContactIds(); if (!staleContacts.isEmpty() || !staleRawContacts.isEmpty()) { mSearchIndexManager.updateIndexForRawContacts(staleContacts, staleRawContacts); mTransactionContext.clearSearchIndexUpdates(); } } private void flushTransactionalChanges() { if (VERBOSE_LOGGING) { Log.v(TAG, "flushTransactionChanges"); } // Determine whether we need to refresh the profile ID cache. boolean profileCacheRefreshNeeded = false; for (long rawContactId : mTransactionContext.getInsertedRawContactIds()) { mDbHelper.updateRawContactDisplayName(mDb, rawContactId); mContactAggregator.onRawContactInsert(mTransactionContext, mDb, rawContactId); } Map<Long, AccountWithDataSet> insertedProfileRawContactAccountMap = mTransactionContext.getInsertedProfileRawContactIds(); if (!insertedProfileRawContactAccountMap.isEmpty()) { for (long profileRawContactId : insertedProfileRawContactAccountMap.keySet()) { mDbHelper.updateRawContactDisplayName(mDb, profileRawContactId); mContactAggregator.onProfileRawContactInsert(mTransactionContext, mDb, profileRawContactId, insertedProfileRawContactAccountMap.get(profileRawContactId)); } profileCacheRefreshNeeded = true; } Set<Long> dirtyRawContacts = mTransactionContext.getDirtyRawContactIds(); if (!dirtyRawContacts.isEmpty()) { mSb.setLength(0); mSb.append(UPDATE_RAW_CONTACT_SET_DIRTY_SQL); appendIds(mSb, dirtyRawContacts); mSb.append(")"); mDb.execSQL(mSb.toString()); profileCacheRefreshNeeded = profileCacheRefreshNeeded || !Collections.disjoint(mProfileIdCache.profileRawContactIds, dirtyRawContacts); } Set<Long> updatedRawContacts = mTransactionContext.getUpdatedRawContactIds(); if (!updatedRawContacts.isEmpty()) { mSb.setLength(0); mSb.append(UPDATE_RAW_CONTACT_SET_VERSION_SQL); appendIds(mSb, updatedRawContacts); mSb.append(")"); mDb.execSQL(mSb.toString()); profileCacheRefreshNeeded = profileCacheRefreshNeeded || !Collections.disjoint(mProfileIdCache.profileRawContactIds, updatedRawContacts); } for (Map.Entry<Long, Object> entry : mTransactionContext.getUpdatedSyncStates()) { long id = entry.getKey(); if (mDbHelper.getSyncState().update(mDb, id, entry.getValue()) <= 0) { throw new IllegalStateException( "unable to update sync state, does it still exist?"); } } if (profileCacheRefreshNeeded) { // Force the profile ID cache to refresh. mProfileIdCache.init(mDb, true); } mTransactionContext.clear(); } /** * Appends comma separated ids. * @param ids Should not be empty */ private void appendIds(StringBuilder sb, Set<Long> ids) { for (long id : ids) { sb.append(id).append(','); } sb.setLength(sb.length() - 1); // Yank the last comma } /** * Checks whether the given contact ID represents the user's personal profile - if it is, calls * a permission check (for writing the profile if forWrite is true, for reading the profile * otherwise). If the contact ID is not the user's profile, no check is executed. * @param db The database. * @param contactId The contact ID to be checked. * @param forWrite Whether the caller is attempting to do a write (vs. read) operation. */ private void enforceProfilePermissionForContact(SQLiteDatabase db, long contactId, boolean forWrite) { mProfileIdCache.init(db, false); if (mProfileIdCache.profileContactId == contactId) { enforceProfilePermission(forWrite); } } /** * Checks whether the given raw contact ID is a member of the user's personal profile - if it * is, calls a permission check (for writing the profile if forWrite is true, for reading the * profile otherwise). If the raw contact ID is not in the user's profile, no check is * executed. * @param db The database. * @param rawContactId The raw contact ID to be checked. * @param forWrite Whether the caller is attempting to do a write (vs. read) operation. */ private void enforceProfilePermissionForRawContact(SQLiteDatabase db, long rawContactId, boolean forWrite) { mProfileIdCache.init(db, false); if (mProfileIdCache.profileRawContactIds.contains(rawContactId)) { enforceProfilePermission(forWrite); } } /** * Checks whether the given data ID is a member of the user's personal profile - if it is, * calls a permission check (for writing the profile if forWrite is true, for reading the * profile otherwise). If the data ID is not in the user's profile, no check is executed. * @param db The database. * @param dataId The data ID to be checked. * @param forWrite Whether the caller is attempting to do a write (vs. read) operation. */ private void enforceProfilePermissionForData(SQLiteDatabase db, long dataId, boolean forWrite) { mProfileIdCache.init(db, false); if (mProfileIdCache.profileDataIds.contains(dataId)) { enforceProfilePermission(forWrite); } } /** * Performs a permission check for WRITE_PROFILE or READ_PROFILE (depending on the parameter). * If the permission check fails, this will throw a SecurityException. * @param forWrite Whether the caller is attempting to do a write (vs. read) operation. */ private void enforceProfilePermission(boolean forWrite) { String profilePermission = forWrite ? "android.permission.WRITE_PROFILE" : "android.permission.READ_PROFILE"; getContext().enforceCallingOrSelfPermission(profilePermission, null); } @Override protected void notifyChange() { notifyChange(mSyncToNetwork); mSyncToNetwork = false; } protected void notifyChange(boolean syncToNetwork) { getContext().getContentResolver().notifyChange(ContactsContract.AUTHORITY_URI, null, syncToNetwork); } protected void setProviderStatus(int status) { if (mProviderStatus != status) { mProviderStatus = status; getContext().getContentResolver().notifyChange(ProviderStatus.CONTENT_URI, null, false); } } public DataRowHandler getDataRowHandler(final String mimeType) { DataRowHandler handler = mDataRowHandlers.get(mimeType); if (handler == null) { handler = new DataRowHandlerForCustomMimetype( getContext(), mDbHelper, mContactAggregator, mimeType); mDataRowHandlers.put(mimeType, handler); } return handler; } @Override protected Uri insertInTransaction(Uri uri, ContentValues values) { if (VERBOSE_LOGGING) { Log.v(TAG, "insertInTransaction: " + uri + " " + values); } final boolean callerIsSyncAdapter = readBooleanQueryParameter(uri, ContactsContract.CALLER_IS_SYNCADAPTER, false); final int match = sUriMatcher.match(uri); long id = 0; switch (match) { case SYNCSTATE: id = mDbHelper.getSyncState().insert(mDb, values); break; case CONTACTS: { insertContact(values); break; } case PROFILE: { throw new UnsupportedOperationException( "The profile contact is created automatically"); } case RAW_CONTACTS: { id = insertRawContact(uri, values, callerIsSyncAdapter, false); mSyncToNetwork |= !callerIsSyncAdapter; break; } case RAW_CONTACTS_DATA: { values.put(Data.RAW_CONTACT_ID, uri.getPathSegments().get(1)); id = insertData(values, callerIsSyncAdapter); mSyncToNetwork |= !callerIsSyncAdapter; break; } case RAW_CONTACTS_ID_STREAM_ITEMS: { values.put(StreamItems.RAW_CONTACT_ID, uri.getPathSegments().get(1)); id = insertStreamItem(uri, values); mSyncToNetwork |= !callerIsSyncAdapter; break; } case PROFILE_RAW_CONTACTS: { enforceProfilePermission(true); id = insertRawContact(uri, values, callerIsSyncAdapter, true); mSyncToNetwork |= !callerIsSyncAdapter; break; } case DATA: { id = insertData(values, callerIsSyncAdapter); mSyncToNetwork |= !callerIsSyncAdapter; break; } case GROUPS: { id = insertGroup(uri, values, callerIsSyncAdapter); mSyncToNetwork |= !callerIsSyncAdapter; break; } case SETTINGS: { id = insertSettings(uri, values); mSyncToNetwork |= !callerIsSyncAdapter; break; } case STATUS_UPDATES: { id = insertStatusUpdate(values); break; } case STREAM_ITEMS: { id = insertStreamItem(uri, values); mSyncToNetwork |= !callerIsSyncAdapter; break; } case STREAM_ITEMS_PHOTOS: { id = insertStreamItemPhoto(uri, values); mSyncToNetwork |= !callerIsSyncAdapter; break; } case STREAM_ITEMS_ID_PHOTOS: { values.put(StreamItemPhotos.STREAM_ITEM_ID, uri.getPathSegments().get(1)); id = insertStreamItemPhoto(uri, values); mSyncToNetwork |= !callerIsSyncAdapter; break; } default: mSyncToNetwork = true; return mLegacyApiSupport.insert(uri, values); } if (id < 0) { return null; } return ContentUris.withAppendedId(uri, id); } /** * If account is non-null then store it in the values. If the account is * already specified in the values then it must be consistent with the * account, if it is non-null. * * @param uri Current {@link Uri} being operated on. * @param values {@link ContentValues} to read and possibly update. * @throws IllegalArgumentException when only one of * {@link RawContacts#ACCOUNT_NAME} or * {@link RawContacts#ACCOUNT_TYPE} is specified, leaving the * other undefined. * @throws IllegalArgumentException when {@link RawContacts#ACCOUNT_NAME} * and {@link RawContacts#ACCOUNT_TYPE} are inconsistent between * the given {@link Uri} and {@link ContentValues}. */ private Account resolveAccount(Uri uri, ContentValues values) throws IllegalArgumentException { String accountName = getQueryParameter(uri, RawContacts.ACCOUNT_NAME); String accountType = getQueryParameter(uri, RawContacts.ACCOUNT_TYPE); final boolean partialUri = TextUtils.isEmpty(accountName) ^ TextUtils.isEmpty(accountType); String valueAccountName = values.getAsString(RawContacts.ACCOUNT_NAME); String valueAccountType = values.getAsString(RawContacts.ACCOUNT_TYPE); final boolean partialValues = TextUtils.isEmpty(valueAccountName) ^ TextUtils.isEmpty(valueAccountType); if (partialUri || partialValues) { // Throw when either account is incomplete throw new IllegalArgumentException(mDbHelper.exceptionMessage( "Must specify both or neither of ACCOUNT_NAME and ACCOUNT_TYPE", uri)); } // Accounts are valid by only checking one parameter, since we've // already ruled out partial accounts. final boolean validUri = !TextUtils.isEmpty(accountName); final boolean validValues = !TextUtils.isEmpty(valueAccountName); if (validValues && validUri) { // Check that accounts match when both present final boolean accountMatch = TextUtils.equals(accountName, valueAccountName) && TextUtils.equals(accountType, valueAccountType); if (!accountMatch) { throw new IllegalArgumentException(mDbHelper.exceptionMessage( "When both specified, ACCOUNT_NAME and ACCOUNT_TYPE must match", uri)); } } else if (validUri) { // Fill values from Uri when not present values.put(RawContacts.ACCOUNT_NAME, accountName); values.put(RawContacts.ACCOUNT_TYPE, accountType); } else if (validValues) { accountName = valueAccountName; accountType = valueAccountType; } else { return null; } // Use cached Account object when matches, otherwise create if (mAccount == null || !mAccount.name.equals(accountName) || !mAccount.type.equals(accountType)) { mAccount = new Account(accountName, accountType); } return mAccount; } /** * Resolves the account and builds an {@link AccountWithDataSet} based on the data set specified * in the URI or values (if any). * @param uri Current {@link Uri} being operated on. * @param values {@link ContentValues} to read and possibly update. */ private AccountWithDataSet resolveAccountWithDataSet(Uri uri, ContentValues values) { final Account account = resolveAccount(uri, values); AccountWithDataSet accountWithDataSet = null; if (account != null) { String dataSet = getQueryParameter(uri, RawContacts.DATA_SET); if (dataSet == null) { dataSet = values.getAsString(RawContacts.DATA_SET); } else { values.put(RawContacts.DATA_SET, dataSet); } accountWithDataSet = new AccountWithDataSet(account.name, account.type, dataSet); } return accountWithDataSet; } /** * Inserts an item in the contacts table * * @param values the values for the new row * @return the row ID of the newly created row */ private long insertContact(ContentValues values) { throw new UnsupportedOperationException("Aggregate contacts are created automatically"); } /** * Inserts an item in the raw contacts table * * @param uri the values for the new row * @param values the account this contact should be associated with. may be null. * @param callerIsSyncAdapter * @param forProfile Whether this raw contact is being inserted into the user's profile. * @return the row ID of the newly created row */ private long insertRawContact(Uri uri, ContentValues values, boolean callerIsSyncAdapter, boolean forProfile) { mValues.clear(); mValues.putAll(values); mValues.putNull(RawContacts.CONTACT_ID); AccountWithDataSet accountWithDataSet = resolveAccountWithDataSet(uri, mValues); if (values.containsKey(RawContacts.DELETED) && values.getAsInteger(RawContacts.DELETED) != 0) { mValues.put(RawContacts.AGGREGATION_MODE, RawContacts.AGGREGATION_MODE_DISABLED); } long rawContactId = mDb.insert(Tables.RAW_CONTACTS, RawContacts.CONTACT_ID, mValues); int aggregationMode = RawContacts.AGGREGATION_MODE_DEFAULT; if (forProfile) { // Profile raw contacts should never be aggregated by the aggregator; they are always // aggregated under a single profile contact. aggregationMode = RawContacts.AGGREGATION_MODE_DISABLED; } else if (mValues.containsKey(RawContacts.AGGREGATION_MODE)) { aggregationMode = mValues.getAsInteger(RawContacts.AGGREGATION_MODE); } mContactAggregator.markNewForAggregation(rawContactId, aggregationMode); if (forProfile) { // Trigger creation of the user profile Contact (or association with the existing one) // at the end of the transaction. mTransactionContext.profileRawContactInserted(rawContactId, accountWithDataSet); } else { // Trigger creation of a Contact based on this RawContact at the end of transaction mTransactionContext.rawContactInserted(rawContactId, accountWithDataSet); } if (!callerIsSyncAdapter) { addAutoAddMembership(rawContactId); final Long starred = values.getAsLong(RawContacts.STARRED); if (starred != null && starred != 0) { updateFavoritesMembership(rawContactId, starred != 0); } } mProviderStatusUpdateNeeded = true; return rawContactId; } private void addAutoAddMembership(long rawContactId) { final Long groupId = findGroupByRawContactId(SELECTION_AUTO_ADD_GROUPS_BY_RAW_CONTACT_ID, rawContactId); if (groupId != null) { insertDataGroupMembership(rawContactId, groupId); } } private Long findGroupByRawContactId(String selection, long rawContactId) { Cursor c = mDb.query(Tables.GROUPS + "," + Tables.RAW_CONTACTS, PROJECTION_GROUP_ID, selection, new String[]{Long.toString(rawContactId)}, null /* groupBy */, null /* having */, null /* orderBy */); try { while (c.moveToNext()) { return c.getLong(0); } return null; } finally { c.close(); } } private void updateFavoritesMembership(long rawContactId, boolean isStarred) { final Long groupId = findGroupByRawContactId(SELECTION_FAVORITES_GROUPS_BY_RAW_CONTACT_ID, rawContactId); if (groupId != null) { if (isStarred) { insertDataGroupMembership(rawContactId, groupId); } else { deleteDataGroupMembership(rawContactId, groupId); } } } private void insertDataGroupMembership(long rawContactId, long groupId) { ContentValues groupMembershipValues = new ContentValues(); groupMembershipValues.put(GroupMembership.GROUP_ROW_ID, groupId); groupMembershipValues.put(GroupMembership.RAW_CONTACT_ID, rawContactId); groupMembershipValues.put(DataColumns.MIMETYPE_ID, mDbHelper.getMimeTypeId(GroupMembership.CONTENT_ITEM_TYPE)); mDb.insert(Tables.DATA, null, groupMembershipValues); } private void deleteDataGroupMembership(long rawContactId, long groupId) { final String[] selectionArgs = { Long.toString(mDbHelper.getMimeTypeId(GroupMembership.CONTENT_ITEM_TYPE)), Long.toString(groupId), Long.toString(rawContactId)}; mDb.delete(Tables.DATA, SELECTION_GROUPMEMBERSHIP_DATA, selectionArgs); } /** * Inserts an item in the data table * * @param values the values for the new row * @return the row ID of the newly created row */ private long insertData(ContentValues values, boolean callerIsSyncAdapter) { long id = 0; mValues.clear(); mValues.putAll(values); long rawContactId = mValues.getAsLong(Data.RAW_CONTACT_ID); // If the data being inserted belongs to the user's profile entry, check for the // WRITE_PROFILE permission before proceeding. enforceProfilePermissionForRawContact(mDb, rawContactId, true); // Replace package with internal mapping final String packageName = mValues.getAsString(Data.RES_PACKAGE); if (packageName != null) { mValues.put(DataColumns.PACKAGE_ID, mDbHelper.getPackageId(packageName)); } mValues.remove(Data.RES_PACKAGE); // Replace mimetype with internal mapping final String mimeType = mValues.getAsString(Data.MIMETYPE); if (TextUtils.isEmpty(mimeType)) { throw new IllegalArgumentException(Data.MIMETYPE + " is required"); } mValues.put(DataColumns.MIMETYPE_ID, mDbHelper.getMimeTypeId(mimeType)); mValues.remove(Data.MIMETYPE); DataRowHandler rowHandler = getDataRowHandler(mimeType); id = rowHandler.insert(mDb, mTransactionContext, rawContactId, mValues); if (!callerIsSyncAdapter) { mTransactionContext.markRawContactDirty(rawContactId); } mTransactionContext.rawContactUpdated(rawContactId); return id; } /** * Inserts an item in the stream_items table. The account is checked against the * account in the raw contact for which the stream item is being inserted. If the * new stream item results in more stream items under this raw contact than the limit, * the oldest one will be deleted (note that if the stream item inserted was the * oldest, it will be immediately deleted, and this will return 0). * * @param uri the insertion URI * @param values the values for the new row * @return the stream item _ID of the newly created row, or 0 if it was not created */ private long insertStreamItem(Uri uri, ContentValues values) { long id = 0; mValues.clear(); mValues.putAll(values); long rawContactId = mValues.getAsLong(StreamItems.RAW_CONTACT_ID); // If the data being inserted belongs to the user's profile entry, check for the // WRITE_PROFILE permission before proceeding. enforceProfilePermissionForRawContact(mDb, rawContactId, true); // Ensure that the raw contact exists and belongs to the caller's account. Account account = resolveAccount(uri, mValues); enforceModifyingAccount(account, rawContactId); // Don't attempt to insert accounts params - they don't exist in the stream items table. mValues.remove(RawContacts.ACCOUNT_NAME); mValues.remove(RawContacts.ACCOUNT_TYPE); // Insert the new stream item. id = mDb.insert(Tables.STREAM_ITEMS, null, mValues); if (id == -1) { // Insertion failed. return 0; } // Check to see if we're over the limit for stream items under this raw contact. // It's possible that the inserted stream item is older than the the existing // ones, in which case it may be deleted immediately (resetting the ID to 0). id = cleanUpOldStreamItems(rawContactId, id); return id; } /** * Inserts an item in the stream_item_photos table. The account is checked against * the account in the raw contact that owns the stream item being modified. * * @param uri the insertion URI * @param values the values for the new row * @return the stream item photo _ID of the newly created row, or 0 if there was an issue * with processing the photo or creating the row */ private long insertStreamItemPhoto(Uri uri, ContentValues values) { long id = 0; mValues.clear(); mValues.putAll(values); long streamItemId = mValues.getAsLong(StreamItemPhotos.STREAM_ITEM_ID); if (streamItemId != 0) { long rawContactId = lookupRawContactIdForStreamId(streamItemId); // If the data being inserted belongs to the user's profile entry, check for the // WRITE_PROFILE permission before proceeding. enforceProfilePermissionForRawContact(mDb, rawContactId, true); // Ensure that the raw contact exists and belongs to the caller's account. Account account = resolveAccount(uri, mValues); enforceModifyingAccount(account, rawContactId); // Don't attempt to insert accounts params - they don't exist in the stream item // photos table. mValues.remove(RawContacts.ACCOUNT_NAME); mValues.remove(RawContacts.ACCOUNT_TYPE); // Process the photo and store it. if (processStreamItemPhoto(mValues, false)) { // Insert the stream item photo. id = mDb.insert(Tables.STREAM_ITEM_PHOTOS, null, mValues); } } return id; } /** * Processes the photo contained in the {@link ContactsContract.StreamItemPhotos#PHOTO} * field of the given values, attempting to store it in the photo store. If successful, * the resulting photo file ID will be added to the values for insert/update in the table. * <p> * If updating, it is valid for the picture to be empty or unspecified (the function will * still return true). If inserting, a valid picture must be specified. * @param values The content values provided by the caller. * @param forUpdate Whether this photo is being processed for update (vs. insert). * @return Whether the insert or update should proceed. */ private boolean processStreamItemPhoto(ContentValues values, boolean forUpdate) { if (!values.containsKey(StreamItemPhotos.PHOTO)) { return forUpdate; } byte[] photoBytes = values.getAsByteArray(StreamItemPhotos.PHOTO); if (photoBytes == null) { return forUpdate; } // Process the photo and store it. try { long photoFileId = mPhotoStore.insert(new PhotoProcessor(photoBytes, mMaxDisplayPhotoDim, mMaxThumbnailPhotoDim, true), true); if (photoFileId != 0) { values.put(StreamItemPhotos.PHOTO_FILE_ID, photoFileId); values.remove(StreamItemPhotos.PHOTO); return true; } else { // Couldn't store the photo, return 0. Log.e(TAG, "Could not process stream item photo for insert"); return false; } } catch (IOException ioe) { Log.e(TAG, "Could not process stream item photo for insert", ioe); return false; } } /** * Looks up the raw contact ID that owns the specified stream item. * @param streamItemId The ID of the stream item. * @return The associated raw contact ID, or -1 if no such stream item exists. */ private long lookupRawContactIdForStreamId(long streamItemId) { long rawContactId = -1; Cursor c = mDb.query(Tables.STREAM_ITEMS, new String[]{StreamItems.RAW_CONTACT_ID}, StreamItems._ID + "=?", new String[]{String.valueOf(streamItemId)}, null, null, null); try { if (c.moveToFirst()) { rawContactId = c.getLong(0); } } finally { c.close(); } return rawContactId; } /** * Checks whether the given raw contact ID is owned by the given account. * If the resolved account is null, this will return true iff the raw contact * is also associated with the "null" account. * * If the resolved account does not match, this will throw a security exception. * @param account The resolved account (may be null). * @param rawContactId The raw contact ID to check for. */ private void enforceModifyingAccount(Account account, long rawContactId) { String accountSelection = RawContactsColumns.CONCRETE_ID + "=? AND " + RawContactsColumns.CONCRETE_ACCOUNT_NAME + "=? AND " + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + "=?"; String noAccountSelection = RawContactsColumns.CONCRETE_ID + "=? AND " + RawContactsColumns.CONCRETE_ACCOUNT_NAME + " IS NULL AND " + RawContactsColumns.CONCRETE_ACCOUNT_TYPE + " IS NULL"; Cursor c; if (account != null) { c = mDb.query(Tables.RAW_CONTACTS, new String[]{RawContactsColumns.CONCRETE_ID}, accountSelection, new String[]{String.valueOf(rawContactId), mAccount.name, mAccount.type}, null, null, null); } else { c = mDb.query(Tables.RAW_CONTACTS, new String[]{RawContactsColumns.CONCRETE_ID}, noAccountSelection, new String[]{String.valueOf(rawContactId)}, null, null, null); } try { if(c.getCount() == 0) { throw new SecurityException("Caller account does not match raw contact ID " + rawContactId); } } finally { c.close(); } } /** * Checks whether the given selection of stream items matches up with the given * account. If any of the raw contacts fail the account check, this will throw a * security exception. * @param account The resolved account (may be null). * @param selection The selection. * @param selectionArgs The selection arguments. * @return The list of stream item IDs that would be included in this selection. */ private List<Long> enforceModifyingAccountForStreamItems(Account account, String selection, String[] selectionArgs) { List<Long> streamItemIds = Lists.newArrayList(); SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); setTablesAndProjectionMapForStreamItems(qb); Cursor c = qb.query(mDb, new String[]{StreamItems._ID, StreamItems.RAW_CONTACT_ID}, selection, selectionArgs, null, null, null); try { while (c.moveToNext()) { streamItemIds.add(c.getLong(0)); // Throw a security exception if the account doesn't match the raw contact's. enforceModifyingAccount(account, c.getLong(1)); } } finally { c.close(); } return streamItemIds; } /** * Checks whether the given selection of stream item photos matches up with the given * account. If any of the raw contacts fail the account check, this will throw a * security exception. * @param account The resolved account (may be null). * @param selection The selection. * @param selectionArgs The selection arguments. * @return The list of stream item photo IDs that would be included in this selection. */ private List<Long> enforceModifyingAccountForStreamItemPhotos(Account account, String selection, String[] selectionArgs) { List<Long> streamItemPhotoIds = Lists.newArrayList(); SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); setTablesAndProjectionMapForStreamItemPhotos(qb); Cursor c = qb.query(mDb, new String[]{StreamItemPhotos._ID, StreamItems.RAW_CONTACT_ID}, selection, selectionArgs, null, null, null); try { while (c.moveToNext()) { streamItemPhotoIds.add(c.getLong(0)); // Throw a security exception if the account doesn't match the raw contact's. enforceModifyingAccount(account, c.getLong(1)); } } finally { c.close(); } return streamItemPhotoIds; } /** * Queries the database for stream items under the given raw contact. If there are * more entries than {@link ContactsProvider2#MAX_STREAM_ITEMS_PER_RAW_CONTACT}, * the oldest entries (as determined by timestamp) will be deleted. * @param rawContactId The raw contact ID to examine for stream items. * @param insertedStreamItemId The ID of the stream item that was just inserted, * prompting this cleanup. Callers may pass 0 if no insertion prompted the * cleanup. * @return The ID of the inserted stream item if it still exists after cleanup; * 0 otherwise. */ private long cleanUpOldStreamItems(long rawContactId, long insertedStreamItemId) { long postCleanupInsertedStreamId = insertedStreamItemId; Cursor c = mDb.query(Tables.STREAM_ITEMS, new String[]{StreamItems._ID}, StreamItems.RAW_CONTACT_ID + "=?", new String[]{String.valueOf(rawContactId)}, null, null, StreamItems.TIMESTAMP + " DESC, " + StreamItems._ID + " DESC"); try { int streamItemCount = c.getCount(); if (streamItemCount <= MAX_STREAM_ITEMS_PER_RAW_CONTACT) { // Still under the limit - nothing to clean up! return insertedStreamItemId; } else { c.moveToLast(); while (c.getPosition() >= MAX_STREAM_ITEMS_PER_RAW_CONTACT) { long streamItemId = c.getLong(0); if (insertedStreamItemId == streamItemId) { // The stream item just inserted is being deleted. postCleanupInsertedStreamId = 0; } deleteStreamItem(c.getLong(0)); c.moveToPrevious(); } } } finally { c.close(); } return postCleanupInsertedStreamId; } public void updateRawContactDisplayName(SQLiteDatabase db, long rawContactId) { mDbHelper.updateRawContactDisplayName(db, rawContactId); } /** * Delete data row by row so that fixing of primaries etc work correctly. */ private int deleteData(String selection, String[] selectionArgs, boolean callerIsSyncAdapter) { int count = 0; // Note that the query will return data according to the access restrictions, // so we don't need to worry about deleting data we don't have permission to read. Cursor c = query(Data.CONTENT_URI, DataRowHandler.DataDeleteQuery.COLUMNS, selection, selectionArgs, null); try { while(c.moveToNext()) { long rawContactId = c.getLong(DataRowHandler.DataDeleteQuery.RAW_CONTACT_ID); // Check for write profile permission if the data belongs to the profile. enforceProfilePermissionForRawContact(mDb, rawContactId, true); String mimeType = c.getString(DataRowHandler.DataDeleteQuery.MIMETYPE); DataRowHandler rowHandler = getDataRowHandler(mimeType); count += rowHandler.delete(mDb, mTransactionContext, c); if (!callerIsSyncAdapter) { mTransactionContext.markRawContactDirty(rawContactId); } } } finally { c.close(); } return count; } /** * Delete a data row provided that it is one of the allowed mime types. */ public int deleteData(long dataId, String[] allowedMimeTypes) { // Note that the query will return data according to the access restrictions, // so we don't need to worry about deleting data we don't have permission to read. mSelectionArgs1[0] = String.valueOf(dataId); Cursor c = query(Data.CONTENT_URI, DataRowHandler.DataDeleteQuery.COLUMNS, Data._ID + "=?", mSelectionArgs1, null); try { if (!c.moveToFirst()) { return 0; } String mimeType = c.getString(DataRowHandler.DataDeleteQuery.MIMETYPE); boolean valid = false; for (int i = 0; i < allowedMimeTypes.length; i++) { if (TextUtils.equals(mimeType, allowedMimeTypes[i])) { valid = true; break; } } if (!valid) { throw new IllegalArgumentException("Data type mismatch: expected " + Lists.newArrayList(allowedMimeTypes)); } // Check for write profile permission if the data belongs to the profile. long rawContactId = c.getLong(DataRowHandler.DataDeleteQuery.RAW_CONTACT_ID); enforceProfilePermissionForRawContact(mDb, rawContactId, true); DataRowHandler rowHandler = getDataRowHandler(mimeType); return rowHandler.delete(mDb, mTransactionContext, c); } finally { c.close(); } } /** * Inserts an item in the groups table */ private long insertGroup(Uri uri, ContentValues values, boolean callerIsSyncAdapter) { mValues.clear(); mValues.putAll(values); final AccountWithDataSet accountWithDataSet = resolveAccountWithDataSet(uri, mValues); // Replace package with internal mapping final String packageName = mValues.getAsString(Groups.RES_PACKAGE); if (packageName != null) { mValues.put(GroupsColumns.PACKAGE_ID, mDbHelper.getPackageId(packageName)); } mValues.remove(Groups.RES_PACKAGE); final boolean isFavoritesGroup = mValues.getAsLong(Groups.FAVORITES) != null ? mValues.getAsLong(Groups.FAVORITES) != 0 : false; if (!callerIsSyncAdapter) { mValues.put(Groups.DIRTY, 1); } long result = mDb.insert(Tables.GROUPS, Groups.TITLE, mValues); if (!callerIsSyncAdapter && isFavoritesGroup) { // add all starred raw contacts to this group String selection; String[] selectionArgs; if (accountWithDataSet == null) { selection = RawContacts.ACCOUNT_NAME + " IS NULL AND " + RawContacts.ACCOUNT_TYPE + " IS NULL AND " + RawContacts.DATA_SET + " IS NULL"; selectionArgs = null; } else if (accountWithDataSet.getDataSet() == null) { selection = RawContacts.ACCOUNT_NAME + "=? AND " + RawContacts.ACCOUNT_TYPE + "=? AND " + RawContacts.DATA_SET + " IS NULL"; selectionArgs = new String[] { accountWithDataSet.getAccountName(), accountWithDataSet.getAccountType() }; } else { selection = RawContacts.ACCOUNT_NAME + "=? AND " + RawContacts.ACCOUNT_TYPE + "=? AND " + RawContacts.DATA_SET + "=?"; selectionArgs = new String[] { accountWithDataSet.getAccountName(), accountWithDataSet.getAccountType(), accountWithDataSet.getDataSet() }; } Cursor c = mDb.query(Tables.RAW_CONTACTS, new String[]{RawContacts._ID, RawContacts.STARRED}, selection, selectionArgs, null, null, null); try { while (c.moveToNext()) { if (c.getLong(1) != 0) { final long rawContactId = c.getLong(0); insertDataGroupMembership(rawContactId, result); mTransactionContext.markRawContactDirty(rawContactId); } } } finally { c.close(); } } if (mValues.containsKey(Groups.GROUP_VISIBLE)) { mVisibleTouched = true; } return result; } private long insertSettings(Uri uri, ContentValues values) { final long id = mDb.insert(Tables.SETTINGS, null, values); if (values.containsKey(Settings.UNGROUPED_VISIBLE)) { mVisibleTouched = true; } return id; } /** * Inserts a status update. */ public long insertStatusUpdate(ContentValues values) { final String handle = values.getAsString(StatusUpdates.IM_HANDLE); final Integer protocol = values.getAsInteger(StatusUpdates.PROTOCOL); String customProtocol = null; if (protocol != null && protocol == Im.PROTOCOL_CUSTOM) { customProtocol = values.getAsString(StatusUpdates.CUSTOM_PROTOCOL); if (TextUtils.isEmpty(customProtocol)) { throw new IllegalArgumentException( "CUSTOM_PROTOCOL is required when PROTOCOL=PROTOCOL_CUSTOM"); } } long rawContactId = -1; long contactId = -1; Long dataId = values.getAsLong(StatusUpdates.DATA_ID); String accountType = null; String accountName = null; mSb.setLength(0); mSelectionArgs.clear(); if (dataId != null) { // Lookup the contact info for the given data row. mSb.append(Tables.DATA + "." + Data._ID + "=?"); mSelectionArgs.add(String.valueOf(dataId)); } else { // Lookup the data row to attach this presence update to if (TextUtils.isEmpty(handle) || protocol == null) { throw new IllegalArgumentException("PROTOCOL and IM_HANDLE are required"); } // TODO: generalize to allow other providers to match against email boolean matchEmail = Im.PROTOCOL_GOOGLE_TALK == protocol; String mimeTypeIdIm = String.valueOf(mDbHelper.getMimeTypeIdForIm()); if (matchEmail) { String mimeTypeIdEmail = String.valueOf(mDbHelper.getMimeTypeIdForEmail()); // The following hack forces SQLite to use the (mimetype_id,data1) index, otherwise // the "OR" conjunction confuses it and it switches to a full scan of // the raw_contacts table. // This code relies on the fact that Im.DATA and Email.DATA are in fact the same // column - Data.DATA1 mSb.append(DataColumns.MIMETYPE_ID + " IN (?,?)" + " AND " + Data.DATA1 + "=?" + " AND ((" + DataColumns.MIMETYPE_ID + "=? AND " + Im.PROTOCOL + "=?"); mSelectionArgs.add(mimeTypeIdEmail); mSelectionArgs.add(mimeTypeIdIm); mSelectionArgs.add(handle); mSelectionArgs.add(mimeTypeIdIm); mSelectionArgs.add(String.valueOf(protocol)); if (customProtocol != null) { mSb.append(" AND " + Im.CUSTOM_PROTOCOL + "=?"); mSelectionArgs.add(customProtocol); } mSb.append(") OR (" + DataColumns.MIMETYPE_ID + "=?))"); mSelectionArgs.add(mimeTypeIdEmail); } else { mSb.append(DataColumns.MIMETYPE_ID + "=?" + " AND " + Im.PROTOCOL + "=?" + " AND " + Im.DATA + "=?"); mSelectionArgs.add(mimeTypeIdIm); mSelectionArgs.add(String.valueOf(protocol)); mSelectionArgs.add(handle); if (customProtocol != null) { mSb.append(" AND " + Im.CUSTOM_PROTOCOL + "=?"); mSelectionArgs.add(customProtocol); } } if (values.containsKey(StatusUpdates.DATA_ID)) { mSb.append(" AND " + DataColumns.CONCRETE_ID + "=?"); mSelectionArgs.add(values.getAsString(StatusUpdates.DATA_ID)); } } Cursor cursor = null; try { cursor = mDb.query(DataContactsQuery.TABLE, DataContactsQuery.PROJECTION, mSb.toString(), mSelectionArgs.toArray(EMPTY_STRING_ARRAY), null, null, Clauses.CONTACT_VISIBLE + " DESC, " + Data.RAW_CONTACT_ID); if (cursor.moveToFirst()) { dataId = cursor.getLong(DataContactsQuery.DATA_ID); rawContactId = cursor.getLong(DataContactsQuery.RAW_CONTACT_ID); accountType = cursor.getString(DataContactsQuery.ACCOUNT_TYPE); accountName = cursor.getString(DataContactsQuery.ACCOUNT_NAME); contactId = cursor.getLong(DataContactsQuery.CONTACT_ID); } else { // No contact found, return a null URI return -1; } } finally { if (cursor != null) { cursor.close(); } } if (values.containsKey(StatusUpdates.PRESENCE)) { if (customProtocol == null) { // We cannot allow a null in the custom protocol field, because SQLite3 does not // properly enforce uniqueness of null values customProtocol = ""; } mValues.clear(); mValues.put(StatusUpdates.DATA_ID, dataId); mValues.put(PresenceColumns.RAW_CONTACT_ID, rawContactId); mValues.put(PresenceColumns.CONTACT_ID, contactId); mValues.put(StatusUpdates.PROTOCOL, protocol); mValues.put(StatusUpdates.CUSTOM_PROTOCOL, customProtocol); mValues.put(StatusUpdates.IM_HANDLE, handle); if (values.containsKey(StatusUpdates.IM_ACCOUNT)) { mValues.put(StatusUpdates.IM_ACCOUNT, values.getAsString(StatusUpdates.IM_ACCOUNT)); } mValues.put(StatusUpdates.PRESENCE, values.getAsString(StatusUpdates.PRESENCE)); mValues.put(StatusUpdates.CHAT_CAPABILITY, values.getAsString(StatusUpdates.CHAT_CAPABILITY)); // Insert the presence update mDb.replace(Tables.PRESENCE, null, mValues); } if (values.containsKey(StatusUpdates.STATUS)) { String status = values.getAsString(StatusUpdates.STATUS); String resPackage = values.getAsString(StatusUpdates.STATUS_RES_PACKAGE); Integer labelResource = values.getAsInteger(StatusUpdates.STATUS_LABEL); if (TextUtils.isEmpty(resPackage) && (labelResource == null || labelResource == 0) && protocol != null) { labelResource = Im.getProtocolLabelResource(protocol); } Long iconResource = values.getAsLong(StatusUpdates.STATUS_ICON); // TODO compute the default icon based on the protocol if (TextUtils.isEmpty(status)) { mDbHelper.deleteStatusUpdate(dataId); } else { Long timestamp = values.getAsLong(StatusUpdates.STATUS_TIMESTAMP); if (timestamp != null) { mDbHelper.replaceStatusUpdate(dataId, timestamp, status, resPackage, iconResource, labelResource); } else { mDbHelper.insertStatusUpdate(dataId, status, resPackage, iconResource, labelResource); } // For forward compatibility with the new stream item API, insert this status update // there as well. If we already have a stream item from this source, update that // one instead of inserting a new one (since the semantics of the old status update // API is to only have a single record). if (rawContactId != -1 && !TextUtils.isEmpty(status)) { ContentValues streamItemValues = new ContentValues(); streamItemValues.put(StreamItems.RAW_CONTACT_ID, rawContactId); streamItemValues.put(StreamItems.TEXT, status); streamItemValues.put(StreamItems.COMMENTS, ""); streamItemValues.put(StreamItems.RES_PACKAGE, resPackage); streamItemValues.put(StreamItems.RES_ICON, iconResource); streamItemValues.put(StreamItems.RES_LABEL, labelResource); streamItemValues.put(StreamItems.TIMESTAMP, timestamp == null ? System.currentTimeMillis() : timestamp); // Note: The following is basically a workaround for the fact that status // updates didn't do any sort of account enforcement, while social stream item // updates do. We can't expect callers of the old API to start passing account // information along, so we just populate the account params appropriately for // the raw contact. Data set is not relevant here, as we only check account // name and type. if (accountName != null && accountType != null) { streamItemValues.put(RawContacts.ACCOUNT_NAME, accountName); streamItemValues.put(RawContacts.ACCOUNT_TYPE, accountType); } // Check for an existing stream item from this source, and insert or update. Uri streamUri = StreamItems.CONTENT_URI; Cursor c = query(streamUri, new String[]{StreamItems._ID}, StreamItems.RAW_CONTACT_ID + "=?", new String[]{String.valueOf(rawContactId)}, null); try { if (c.getCount() > 0) { c.moveToFirst(); update(ContentUris.withAppendedId(streamUri, c.getLong(0)), streamItemValues, null, null); } else { insert(streamUri, streamItemValues); } } finally { c.close(); } } } } if (contactId != -1) { mContactAggregator.updateLastStatusUpdateId(contactId); } return dataId; } @Override protected int deleteInTransaction(Uri uri, String selection, String[] selectionArgs) { if (VERBOSE_LOGGING) { Log.v(TAG, "deleteInTransaction: " + uri); } flushTransactionalChanges(); final boolean callerIsSyncAdapter = readBooleanQueryParameter(uri, ContactsContract.CALLER_IS_SYNCADAPTER, false); final int match = sUriMatcher.match(uri); switch (match) { case SYNCSTATE: return mDbHelper.getSyncState().delete(mDb, selection, selectionArgs); case SYNCSTATE_ID: String selectionWithId = (SyncStateContract.Columns._ID + "=" + ContentUris.parseId(uri) + " ") + (selection == null ? "" : " AND (" + selection + ")"); return mDbHelper.getSyncState().delete(mDb, selectionWithId, selectionArgs); case CONTACTS: { // TODO return 0; } case CONTACTS_ID: { long contactId = ContentUris.parseId(uri); return deleteContact(contactId, callerIsSyncAdapter); } case CONTACTS_LOOKUP: { final List<String> pathSegments = uri.getPathSegments(); final int segmentCount = pathSegments.size(); if (segmentCount < 3) { throw new IllegalArgumentException(mDbHelper.exceptionMessage( "Missing a lookup key", uri)); } final String lookupKey = pathSegments.get(2); final long contactId = lookupContactIdByLookupKey(mDb, lookupKey); return deleteContact(contactId, callerIsSyncAdapter); } case CONTACTS_LOOKUP_ID: { // lookup contact by id and lookup key to see if they still match the actual record final List<String> pathSegments = uri.getPathSegments(); final String lookupKey = pathSegments.get(2); SQLiteQueryBuilder lookupQb = new SQLiteQueryBuilder(); setTablesAndProjectionMapForContacts(lookupQb, uri, null); long contactId = ContentUris.parseId(uri); String[] args; if (selectionArgs == null) { args = new String[2]; } else { args = new String[selectionArgs.length + 2]; System.arraycopy(selectionArgs, 0, args, 2, selectionArgs.length); } args[0] = String.valueOf(contactId); args[1] = Uri.encode(lookupKey); lookupQb.appendWhere(Contacts._ID + "=? AND " + Contacts.LOOKUP_KEY + "=?"); final SQLiteDatabase db = mDbHelper.getReadableDatabase(); Cursor c = query(db, lookupQb, null, selection, args, null, null, null); try { if (c.getCount() == 1) { // contact was unmodified so go ahead and delete it return deleteContact(contactId, callerIsSyncAdapter); } else { // row was changed (e.g. the merging might have changed), we got multiple // rows or the supplied selection filtered the record out return 0; } } finally { c.close(); } } case RAW_CONTACTS: { int numDeletes = 0; Cursor c = mDb.query(Tables.RAW_CONTACTS, new String[]{RawContacts._ID, RawContacts.CONTACT_ID}, appendAccountToSelection(uri, selection), selectionArgs, null, null, null); try { while (c.moveToNext()) { final long rawContactId = c.getLong(0); long contactId = c.getLong(1); numDeletes += deleteRawContact(rawContactId, contactId, callerIsSyncAdapter); } } finally { c.close(); } return numDeletes; } case RAW_CONTACTS_ID: { final long rawContactId = ContentUris.parseId(uri); return deleteRawContact(rawContactId, mDbHelper.getContactId(rawContactId), callerIsSyncAdapter); } case DATA: { mSyncToNetwork |= !callerIsSyncAdapter; return deleteData(appendAccountToSelection(uri, selection), selectionArgs, callerIsSyncAdapter); } case DATA_ID: case PHONES_ID: case EMAILS_ID: case POSTALS_ID: { long dataId = ContentUris.parseId(uri); mSyncToNetwork |= !callerIsSyncAdapter; mSelectionArgs1[0] = String.valueOf(dataId); return deleteData(Data._ID + "=?", mSelectionArgs1, callerIsSyncAdapter); } case GROUPS_ID: { mSyncToNetwork |= !callerIsSyncAdapter; return deleteGroup(uri, ContentUris.parseId(uri), callerIsSyncAdapter); } case GROUPS: { int numDeletes = 0; Cursor c = mDb.query(Tables.GROUPS, new String[]{Groups._ID}, appendAccountToSelection(uri, selection), selectionArgs, null, null, null); try { while (c.moveToNext()) { numDeletes += deleteGroup(uri, c.getLong(0), callerIsSyncAdapter); } } finally { c.close(); } if (numDeletes > 0) { mSyncToNetwork |= !callerIsSyncAdapter; } return numDeletes; } case SETTINGS: { mSyncToNetwork |= !callerIsSyncAdapter; return deleteSettings(uri, appendAccountToSelection(uri, selection), selectionArgs); } case STATUS_UPDATES: { return deleteStatusUpdates(selection, selectionArgs); } case STREAM_ITEMS: { mSyncToNetwork |= !callerIsSyncAdapter; return deleteStreamItems(uri, new ContentValues(), selection, selectionArgs); } case STREAM_ITEMS_ID: { mSyncToNetwork |= !callerIsSyncAdapter; return deleteStreamItems(uri, new ContentValues(), StreamItemsColumns.CONCRETE_ID + "=?", new String[]{uri.getLastPathSegment()}); } case STREAM_ITEMS_ID_PHOTOS: { mSyncToNetwork |= !callerIsSyncAdapter; return deleteStreamItemPhotos(uri, new ContentValues(), selection, selectionArgs); } case STREAM_ITEMS_ID_PHOTOS_ID: { mSyncToNetwork |= !callerIsSyncAdapter; String streamItemId = uri.getPathSegments().get(1); String streamItemPhotoId = uri.getPathSegments().get(3); return deleteStreamItemPhotos(uri, new ContentValues(), StreamItemPhotosColumns.CONCRETE_ID + "=? AND " + StreamItemPhotos.STREAM_ITEM_ID + "=?", new String[]{streamItemPhotoId, streamItemId}); } default: { mSyncToNetwork = true; return mLegacyApiSupport.delete(uri, selection, selectionArgs); } } } public int deleteGroup(Uri uri, long groupId, boolean callerIsSyncAdapter) { mGroupIdCache.clear(); final long groupMembershipMimetypeId = mDbHelper .getMimeTypeId(GroupMembership.CONTENT_ITEM_TYPE); mDb.delete(Tables.DATA, DataColumns.MIMETYPE_ID + "=" + groupMembershipMimetypeId + " AND " + GroupMembership.GROUP_ROW_ID + "=" + groupId, null); try { if (callerIsSyncAdapter) { return mDb.delete(Tables.GROUPS, Groups._ID + "=" + groupId, null); } else { mValues.clear(); mValues.put(Groups.DELETED, 1); mValues.put(Groups.DIRTY, 1); return mDb.update(Tables.GROUPS, mValues, Groups._ID + "=" + groupId, null); } } finally { mVisibleTouched = true; } } private int deleteSettings(Uri uri, String selection, String[] selectionArgs) { final int count = mDb.delete(Tables.SETTINGS, selection, selectionArgs); mVisibleTouched = true; return count; } private int deleteContact(long contactId, boolean callerIsSyncAdapter) { enforceProfilePermissionForContact(mDb, contactId, true); mSelectionArgs1[0] = Long.toString(contactId); Cursor c = mDb.query(Tables.RAW_CONTACTS, new String[]{RawContacts._ID}, RawContacts.CONTACT_ID + "=?", mSelectionArgs1, null, null, null); try { while (c.moveToNext()) { long rawContactId = c.getLong(0); markRawContactAsDeleted(rawContactId, callerIsSyncAdapter); } } finally { c.close(); } mProviderStatusUpdateNeeded = true; return mDb.delete(Tables.CONTACTS, Contacts._ID + "=" + contactId, null); } public int deleteRawContact(long rawContactId, long contactId, boolean callerIsSyncAdapter) { enforceProfilePermissionForRawContact(mDb, rawContactId, true); mContactAggregator.invalidateAggregationExceptionCache(); mProviderStatusUpdateNeeded = true; if (callerIsSyncAdapter) { mDb.delete(Tables.PRESENCE, PresenceColumns.RAW_CONTACT_ID + "=" + rawContactId, null); int count = mDb.delete(Tables.RAW_CONTACTS, RawContacts._ID + "=" + rawContactId, null); mContactAggregator.updateDisplayNameForContact(mDb, contactId); return count; } else { mDbHelper.removeContactIfSingleton(rawContactId); return markRawContactAsDeleted(rawContactId, callerIsSyncAdapter); } } private int deleteStatusUpdates(String selection, String[] selectionArgs) { // delete from both tables: presence and status_updates // TODO should account type/name be appended to the where clause? if (VERBOSE_LOGGING) { Log.v(TAG, "deleting data from status_updates for " + selection); } mDb.delete(Tables.STATUS_UPDATES, getWhereClauseForStatusUpdatesTable(selection), selectionArgs); return mDb.delete(Tables.PRESENCE, selection, selectionArgs); } private int deleteStreamItems(Uri uri, ContentValues values, String selection, String[] selectionArgs) { // First query for the stream items to be deleted, and check that they belong // to the account. Account account = resolveAccount(uri, values); List<Long> streamItemIds = enforceModifyingAccountForStreamItems( account, selection, selectionArgs); // If no security exception has been thrown, we're fine to delete. for (long streamItemId : streamItemIds) { deleteStreamItem(streamItemId); } mVisibleTouched = true; return streamItemIds.size(); } private int deleteStreamItem(long streamItemId) { // Note that this does not enforce the modifying account. deleteStreamItemPhotos(streamItemId); return mDb.delete(Tables.STREAM_ITEMS, StreamItems._ID + "=?", new String[]{String.valueOf(streamItemId)}); } private int deleteStreamItemPhotos(Uri uri, ContentValues values, String selection, String[] selectionArgs) { // First query for the stream item photos to be deleted, and check that they // belong to the account. Account account = resolveAccount(uri, values); enforceModifyingAccountForStreamItemPhotos(account, selection, selectionArgs); // If no security exception has been thrown, we're fine to delete. return mDb.delete(Tables.STREAM_ITEM_PHOTOS, selection, selectionArgs); } private int deleteStreamItemPhotos(long streamItemId) { // Note that this does not enforce the modifying account. return mDb.delete(Tables.STREAM_ITEM_PHOTOS, StreamItemPhotos.STREAM_ITEM_ID + "=?", new String[]{String.valueOf(streamItemId)}); } private int markRawContactAsDeleted(long rawContactId, boolean callerIsSyncAdapter) { mSyncToNetwork = true; mValues.clear(); mValues.put(RawContacts.DELETED, 1); mValues.put(RawContacts.AGGREGATION_MODE, RawContacts.AGGREGATION_MODE_DISABLED); mValues.put(RawContactsColumns.AGGREGATION_NEEDED, 1); mValues.putNull(RawContacts.CONTACT_ID); mValues.put(RawContacts.DIRTY, 1); return updateRawContact(rawContactId, mValues, callerIsSyncAdapter); } @Override protected int updateInTransaction(Uri uri, ContentValues values, String selection, String[] selectionArgs) { if (VERBOSE_LOGGING) { Log.v(TAG, "updateInTransaction: " + uri); } int count = 0; final int match = sUriMatcher.match(uri); if (match == SYNCSTATE_ID && selection == null) { long rowId = ContentUris.parseId(uri); Object data = values.get(ContactsContract.SyncState.DATA); mTransactionContext.syncStateUpdated(rowId, data); return 1; } flushTransactionalChanges(); final boolean callerIsSyncAdapter = readBooleanQueryParameter(uri, ContactsContract.CALLER_IS_SYNCADAPTER, false); switch(match) { case SYNCSTATE: return mDbHelper.getSyncState().update(mDb, values, appendAccountToSelection(uri, selection), selectionArgs); case SYNCSTATE_ID: { selection = appendAccountToSelection(uri, selection); String selectionWithId = (SyncStateContract.Columns._ID + "=" + ContentUris.parseId(uri) + " ") + (selection == null ? "" : " AND (" + selection + ")"); return mDbHelper.getSyncState().update(mDb, values, selectionWithId, selectionArgs); } case CONTACTS: { count = updateContactOptions(values, selection, selectionArgs, callerIsSyncAdapter); break; } case CONTACTS_ID: { count = updateContactOptions(ContentUris.parseId(uri), values, callerIsSyncAdapter); break; } case PROFILE: { // Restrict update to the user's profile. StringBuilder profileSelection = new StringBuilder(); profileSelection.append(Contacts.IS_USER_PROFILE + "=1"); if (!TextUtils.isEmpty(selection)) { profileSelection.append(" AND (").append(selection).append(")"); } count = updateContactOptions(values, profileSelection.toString(), selectionArgs, callerIsSyncAdapter); break; } case CONTACTS_LOOKUP: case CONTACTS_LOOKUP_ID: { final List<String> pathSegments = uri.getPathSegments(); final int segmentCount = pathSegments.size(); if (segmentCount < 3) { throw new IllegalArgumentException(mDbHelper.exceptionMessage( "Missing a lookup key", uri)); } final String lookupKey = pathSegments.get(2); final long contactId = lookupContactIdByLookupKey(mDb, lookupKey); count = updateContactOptions(contactId, values, callerIsSyncAdapter); break; } case RAW_CONTACTS_DATA: { final String rawContactId = uri.getPathSegments().get(1); String selectionWithId = (Data.RAW_CONTACT_ID + "=" + rawContactId + " ") + (selection == null ? "" : " AND " + selection); count = updateData(uri, values, selectionWithId, selectionArgs, callerIsSyncAdapter); break; } case DATA: { count = updateData(uri, values, appendAccountToSelection(uri, selection), selectionArgs, callerIsSyncAdapter); if (count > 0) { mSyncToNetwork |= !callerIsSyncAdapter; } break; } case DATA_ID: case PHONES_ID: case EMAILS_ID: case POSTALS_ID: { count = updateData(uri, values, selection, selectionArgs, callerIsSyncAdapter); if (count > 0) { mSyncToNetwork |= !callerIsSyncAdapter; } break; } case RAW_CONTACTS: { selection = appendAccountToSelection(uri, selection); count = updateRawContacts(values, selection, selectionArgs, callerIsSyncAdapter); break; } case RAW_CONTACTS_ID: { long rawContactId = ContentUris.parseId(uri); if (selection != null) { selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId)); count = updateRawContacts(values, RawContacts._ID + "=?" + " AND(" + selection + ")", selectionArgs, callerIsSyncAdapter); } else { mSelectionArgs1[0] = String.valueOf(rawContactId); count = updateRawContacts(values, RawContacts._ID + "=?", mSelectionArgs1, callerIsSyncAdapter); } break; } case PROFILE_RAW_CONTACTS: { // Restrict update to the user's profile. StringBuilder profileSelection = new StringBuilder(); profileSelection.append(RawContacts.RAW_CONTACT_IS_USER_PROFILE + "=1"); if (!TextUtils.isEmpty(selection)) { profileSelection.append(" AND (").append(selection).append(")"); } count = updateRawContacts(values, profileSelection.toString(), selectionArgs, callerIsSyncAdapter); break; } case GROUPS: { count = updateGroups(uri, values, appendAccountToSelection(uri, selection), selectionArgs, callerIsSyncAdapter); if (count > 0) { mSyncToNetwork |= !callerIsSyncAdapter; } break; } case GROUPS_ID: { long groupId = ContentUris.parseId(uri); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(groupId)); String selectionWithId = Groups._ID + "=? " + (selection == null ? "" : " AND " + selection); count = updateGroups(uri, values, selectionWithId, selectionArgs, callerIsSyncAdapter); if (count > 0) { mSyncToNetwork |= !callerIsSyncAdapter; } break; } case AGGREGATION_EXCEPTIONS: { count = updateAggregationException(mDb, values); break; } case SETTINGS: { count = updateSettings(uri, values, appendAccountToSelection(uri, selection), selectionArgs); mSyncToNetwork |= !callerIsSyncAdapter; break; } case STATUS_UPDATES: { count = updateStatusUpdate(uri, values, selection, selectionArgs); break; } case STREAM_ITEMS: { count = updateStreamItems(uri, values, selection, selectionArgs); break; } case STREAM_ITEMS_ID: { count = updateStreamItems(uri, values, StreamItemsColumns.CONCRETE_ID + "=?", new String[]{uri.getLastPathSegment()}); break; } case STREAM_ITEMS_PHOTOS: { count = updateStreamItemPhotos(uri, values, selection, selectionArgs); break; } case STREAM_ITEMS_ID_PHOTOS: { String streamItemId = uri.getPathSegments().get(1); count = updateStreamItemPhotos(uri, values, StreamItemPhotos.STREAM_ITEM_ID + "=?", new String[]{streamItemId}); break; } case STREAM_ITEMS_ID_PHOTOS_ID: { String streamItemId = uri.getPathSegments().get(1); String streamItemPhotoId = uri.getPathSegments().get(3); count = updateStreamItemPhotos(uri, values, StreamItemPhotosColumns.CONCRETE_ID + "=? AND " + StreamItemPhotosColumns.CONCRETE_STREAM_ITEM_ID + "=?", new String[]{streamItemPhotoId, streamItemId}); break; } case DIRECTORIES: { mContactDirectoryManager.scanPackagesByUid(Binder.getCallingUid()); count = 1; break; } case DATA_USAGE_FEEDBACK_ID: { if (handleDataUsageFeedback(uri)) { count = 1; } else { count = 0; } break; } default: { mSyncToNetwork = true; return mLegacyApiSupport.update(uri, values, selection, selectionArgs); } } return count; } private int updateStatusUpdate(Uri uri, ContentValues values, String selection, String[] selectionArgs) { // update status_updates table, if status is provided // TODO should account type/name be appended to the where clause? int updateCount = 0; ContentValues settableValues = getSettableColumnsForStatusUpdatesTable(values); if (settableValues.size() > 0) { updateCount = mDb.update(Tables.STATUS_UPDATES, settableValues, getWhereClauseForStatusUpdatesTable(selection), selectionArgs); } // now update the Presence table settableValues = getSettableColumnsForPresenceTable(values); if (settableValues.size() > 0) { updateCount = mDb.update(Tables.PRESENCE, settableValues, selection, selectionArgs); } // TODO updateCount is not entirely a valid count of updated rows because 2 tables could // potentially get updated in this method. return updateCount; } private int updateStreamItems(Uri uri, ContentValues values, String selection, String[] selectionArgs) { // Stream items can't be moved to a new raw contact. values.remove(StreamItems.RAW_CONTACT_ID); // Check that the stream items being updated belong to the account. Account account = resolveAccount(uri, values); enforceModifyingAccountForStreamItems(account, selection, selectionArgs); // Don't attempt to update accounts params - they don't exist in the stream items table. values.remove(RawContacts.ACCOUNT_NAME); values.remove(RawContacts.ACCOUNT_TYPE); // If there's been no exception, the update should be fine. return mDb.update(Tables.STREAM_ITEMS, values, selection, selectionArgs); } private int updateStreamItemPhotos(Uri uri, ContentValues values, String selection, String[] selectionArgs) { // Stream item photos can't be moved to a new stream item. values.remove(StreamItemPhotos.STREAM_ITEM_ID); // Check that the stream item photos being updated belong to the account. Account account = resolveAccount(uri, values); enforceModifyingAccountForStreamItemPhotos(account, selection, selectionArgs); // Don't attempt to update accounts params - they don't exist in the stream item // photos table. values.remove(RawContacts.ACCOUNT_NAME); values.remove(RawContacts.ACCOUNT_TYPE); // Process the photo (since we're updating, it's valid for the photo to not be present). if (processStreamItemPhoto(values, true)) { // If there's been no exception, the update should be fine. return mDb.update(Tables.STREAM_ITEM_PHOTOS, values, selection, selectionArgs); } return 0; } /** * Build a where clause to select the rows to be updated in status_updates table. */ private String getWhereClauseForStatusUpdatesTable(String selection) { mSb.setLength(0); mSb.append(WHERE_CLAUSE_FOR_STATUS_UPDATES_TABLE); mSb.append(selection); mSb.append(")"); return mSb.toString(); } private ContentValues getSettableColumnsForStatusUpdatesTable(ContentValues values) { mValues.clear(); ContactsDatabaseHelper.copyStringValue(mValues, StatusUpdates.STATUS, values, StatusUpdates.STATUS); ContactsDatabaseHelper.copyStringValue(mValues, StatusUpdates.STATUS_TIMESTAMP, values, StatusUpdates.STATUS_TIMESTAMP); ContactsDatabaseHelper.copyStringValue(mValues, StatusUpdates.STATUS_RES_PACKAGE, values, StatusUpdates.STATUS_RES_PACKAGE); ContactsDatabaseHelper.copyStringValue(mValues, StatusUpdates.STATUS_LABEL, values, StatusUpdates.STATUS_LABEL); ContactsDatabaseHelper.copyStringValue(mValues, StatusUpdates.STATUS_ICON, values, StatusUpdates.STATUS_ICON); return mValues; } private ContentValues getSettableColumnsForPresenceTable(ContentValues values) { mValues.clear(); ContactsDatabaseHelper.copyStringValue(mValues, StatusUpdates.PRESENCE, values, StatusUpdates.PRESENCE); ContactsDatabaseHelper.copyStringValue(mValues, StatusUpdates.CHAT_CAPABILITY, values, StatusUpdates.CHAT_CAPABILITY); return mValues; } private int updateGroups(Uri uri, ContentValues values, String selectionWithId, String[] selectionArgs, boolean callerIsSyncAdapter) { mGroupIdCache.clear(); ContentValues updatedValues; if (!callerIsSyncAdapter && !values.containsKey(Groups.DIRTY)) { updatedValues = mValues; updatedValues.clear(); updatedValues.putAll(values); updatedValues.put(Groups.DIRTY, 1); } else { updatedValues = values; } int count = mDb.update(Tables.GROUPS, updatedValues, selectionWithId, selectionArgs); if (updatedValues.containsKey(Groups.GROUP_VISIBLE)) { mVisibleTouched = true; } // TODO: This will not work for groups that have a data set specified, since the content // resolver will not be able to request a sync for the right source (unless it is updated // to key off account with data set). if (updatedValues.containsKey(Groups.SHOULD_SYNC) && updatedValues.getAsInteger(Groups.SHOULD_SYNC) != 0) { Cursor c = mDb.query(Tables.GROUPS, new String[]{Groups.ACCOUNT_NAME, Groups.ACCOUNT_TYPE}, selectionWithId, selectionArgs, null, null, null); String accountName; String accountType; try { while (c.moveToNext()) { accountName = c.getString(0); accountType = c.getString(1); if (!TextUtils.isEmpty(accountName) && !TextUtils.isEmpty(accountType)) { Account account = new Account(accountName, accountType); ContentResolver.requestSync(account, ContactsContract.AUTHORITY, new Bundle()); break; } } } finally { c.close(); } } return count; } private int updateSettings(Uri uri, ContentValues values, String selection, String[] selectionArgs) { final int count = mDb.update(Tables.SETTINGS, values, selection, selectionArgs); if (values.containsKey(Settings.UNGROUPED_VISIBLE)) { mVisibleTouched = true; } return count; } private int updateRawContacts(ContentValues values, String selection, String[] selectionArgs, boolean callerIsSyncAdapter) { if (values.containsKey(RawContacts.CONTACT_ID)) { throw new IllegalArgumentException(RawContacts.CONTACT_ID + " should not be included " + "in content values. Contact IDs are assigned automatically"); } if (!callerIsSyncAdapter) { selection = DatabaseUtils.concatenateWhere(selection, RawContacts.RAW_CONTACT_IS_READ_ONLY + "=0"); } int count = 0; Cursor cursor = mDb.query(Views.RAW_CONTACTS, new String[] { RawContacts._ID }, selection, selectionArgs, null, null, null); try { while (cursor.moveToNext()) { long rawContactId = cursor.getLong(0); updateRawContact(rawContactId, values, callerIsSyncAdapter); count++; } } finally { cursor.close(); } return count; } private int updateRawContact(long rawContactId, ContentValues values, boolean callerIsSyncAdapter) { // Enforce profile permissions if the raw contact is in the user's profile. enforceProfilePermissionForRawContact(mDb, rawContactId, true); final String selection = RawContacts._ID + " = ?"; mSelectionArgs1[0] = Long.toString(rawContactId); final boolean requestUndoDelete = (values.containsKey(RawContacts.DELETED) && values.getAsInteger(RawContacts.DELETED) == 0); int previousDeleted = 0; String accountType = null; String accountName = null; String dataSet = null; if (requestUndoDelete) { Cursor cursor = mDb.query(RawContactsQuery.TABLE, RawContactsQuery.COLUMNS, selection, mSelectionArgs1, null, null, null); try { if (cursor.moveToFirst()) { previousDeleted = cursor.getInt(RawContactsQuery.DELETED); accountType = cursor.getString(RawContactsQuery.ACCOUNT_TYPE); accountName = cursor.getString(RawContactsQuery.ACCOUNT_NAME); dataSet = cursor.getString(RawContactsQuery.DATA_SET); } } finally { cursor.close(); } values.put(ContactsContract.RawContacts.AGGREGATION_MODE, ContactsContract.RawContacts.AGGREGATION_MODE_DEFAULT); } int count = mDb.update(Tables.RAW_CONTACTS, values, selection, mSelectionArgs1); if (count != 0) { if (values.containsKey(RawContacts.AGGREGATION_MODE)) { int aggregationMode = values.getAsInteger(RawContacts.AGGREGATION_MODE); // As per ContactsContract documentation, changing aggregation mode // to DEFAULT should not trigger aggregation if (aggregationMode != RawContacts.AGGREGATION_MODE_DEFAULT) { mContactAggregator.markForAggregation(rawContactId, aggregationMode, false); } } if (values.containsKey(RawContacts.STARRED)) { if (!callerIsSyncAdapter) { updateFavoritesMembership(rawContactId, values.getAsLong(RawContacts.STARRED) != 0); } mContactAggregator.updateStarred(rawContactId); } else { // if this raw contact is being associated with an account, then update the // favorites group membership based on whether or not this contact is starred. // If it is starred, add a group membership, if one doesn't already exist // otherwise delete any matching group memberships. if (!callerIsSyncAdapter && values.containsKey(RawContacts.ACCOUNT_NAME)) { boolean starred = 0 != DatabaseUtils.longForQuery(mDb, SELECTION_STARRED_FROM_RAW_CONTACTS, new String[]{Long.toString(rawContactId)}); updateFavoritesMembership(rawContactId, starred); } } // if this raw contact is being associated with an account, then add a // group membership to the group marked as AutoAdd, if any. if (!callerIsSyncAdapter && values.containsKey(RawContacts.ACCOUNT_NAME)) { addAutoAddMembership(rawContactId); } if (values.containsKey(RawContacts.SOURCE_ID)) { mContactAggregator.updateLookupKeyForRawContact(mDb, rawContactId); } if (values.containsKey(RawContacts.NAME_VERIFIED)) { // If setting NAME_VERIFIED for this raw contact, reset it for all // other raw contacts in the same aggregate if (values.getAsInteger(RawContacts.NAME_VERIFIED) != 0) { mDbHelper.resetNameVerifiedForOtherRawContacts(rawContactId); } mContactAggregator.updateDisplayNameForRawContact(mDb, rawContactId); } if (requestUndoDelete && previousDeleted == 1) { mTransactionContext.rawContactInserted(rawContactId, new AccountWithDataSet(accountName, accountType, dataSet)); } } return count; } private int updateData(Uri uri, ContentValues values, String selection, String[] selectionArgs, boolean callerIsSyncAdapter) { mValues.clear(); mValues.putAll(values); mValues.remove(Data._ID); mValues.remove(Data.RAW_CONTACT_ID); mValues.remove(Data.MIMETYPE); String packageName = values.getAsString(Data.RES_PACKAGE); if (packageName != null) { mValues.remove(Data.RES_PACKAGE); mValues.put(DataColumns.PACKAGE_ID, mDbHelper.getPackageId(packageName)); } if (!callerIsSyncAdapter) { selection = DatabaseUtils.concatenateWhere(selection, Data.IS_READ_ONLY + "=0"); } int count = 0; // Note that the query will return data according to the access restrictions, // so we don't need to worry about updating data we don't have permission to read. // This query will be allowed to return profiles, and we'll do the permission check // within the loop. Cursor c = queryLocal(uri.buildUpon() .appendQueryParameter(ContactsContract.ALLOW_PROFILE, "1").build(), DataRowHandler.DataUpdateQuery.COLUMNS, selection, selectionArgs, null, -1 /* directory ID */, true /* suppress profile check */); try { while(c.moveToNext()) { // Check profile permission for the raw contact that owns each data record. long rawContactId = c.getLong(DataRowHandler.DataUpdateQuery.RAW_CONTACT_ID); enforceProfilePermissionForRawContact(mDb, rawContactId, true); count += updateData(mValues, c, callerIsSyncAdapter); } } finally { c.close(); } return count; } private int updateData(ContentValues values, Cursor c, boolean callerIsSyncAdapter) { if (values.size() == 0) { return 0; } final String mimeType = c.getString(DataRowHandler.DataUpdateQuery.MIMETYPE); DataRowHandler rowHandler = getDataRowHandler(mimeType); boolean updated = rowHandler.update(mDb, mTransactionContext, values, c, callerIsSyncAdapter); if (Photo.CONTENT_ITEM_TYPE.equals(mimeType)) { scheduleBackgroundTask(BACKGROUND_TASK_CLEANUP_PHOTOS); } return updated ? 1 : 0; } private int updateContactOptions(ContentValues values, String selection, String[] selectionArgs, boolean callerIsSyncAdapter) { int count = 0; Cursor cursor = mDb.query(Views.CONTACTS, new String[] { Contacts._ID, Contacts.IS_USER_PROFILE }, selection, selectionArgs, null, null, null); try { while (cursor.moveToNext()) { long contactId = cursor.getLong(0); // Check for profile write permission before updating a user's profile contact. boolean isProfile = cursor.getInt(1) == 1; if (isProfile) { enforceProfilePermission(true); } updateContactOptions(contactId, values, callerIsSyncAdapter); count++; } } finally { cursor.close(); } return count; } private int updateContactOptions(long contactId, ContentValues values, boolean callerIsSyncAdapter) { // Check write permission if the contact is the user's profile. enforceProfilePermissionForContact(mDb, contactId, true); mValues.clear(); ContactsDatabaseHelper.copyStringValue(mValues, RawContacts.CUSTOM_RINGTONE, values, Contacts.CUSTOM_RINGTONE); ContactsDatabaseHelper.copyLongValue(mValues, RawContacts.SEND_TO_VOICEMAIL, values, Contacts.SEND_TO_VOICEMAIL); ContactsDatabaseHelper.copyLongValue(mValues, RawContacts.LAST_TIME_CONTACTED, values, Contacts.LAST_TIME_CONTACTED); ContactsDatabaseHelper.copyLongValue(mValues, RawContacts.TIMES_CONTACTED, values, Contacts.TIMES_CONTACTED); ContactsDatabaseHelper.copyLongValue(mValues, RawContacts.STARRED, values, Contacts.STARRED); // Nothing to update - just return if (mValues.size() == 0) { return 0; } if (mValues.containsKey(RawContacts.STARRED)) { // Mark dirty when changing starred to trigger sync mValues.put(RawContacts.DIRTY, 1); } mSelectionArgs1[0] = String.valueOf(contactId); mDb.update(Tables.RAW_CONTACTS, mValues, RawContacts.CONTACT_ID + "=?" + " AND " + RawContacts.RAW_CONTACT_IS_READ_ONLY + "=0", mSelectionArgs1); if (mValues.containsKey(RawContacts.STARRED) && !callerIsSyncAdapter) { Cursor cursor = mDb.query(Views.RAW_CONTACTS, new String[] { RawContacts._ID }, RawContacts.CONTACT_ID + "=?", mSelectionArgs1, null, null, null); try { while (cursor.moveToNext()) { long rawContactId = cursor.getLong(0); updateFavoritesMembership(rawContactId, mValues.getAsLong(RawContacts.STARRED) != 0); } } finally { cursor.close(); } } // Copy changeable values to prevent automatically managed fields from // being explicitly updated by clients. mValues.clear(); ContactsDatabaseHelper.copyStringValue(mValues, RawContacts.CUSTOM_RINGTONE, values, Contacts.CUSTOM_RINGTONE); ContactsDatabaseHelper.copyLongValue(mValues, RawContacts.SEND_TO_VOICEMAIL, values, Contacts.SEND_TO_VOICEMAIL); ContactsDatabaseHelper.copyLongValue(mValues, RawContacts.LAST_TIME_CONTACTED, values, Contacts.LAST_TIME_CONTACTED); ContactsDatabaseHelper.copyLongValue(mValues, RawContacts.TIMES_CONTACTED, values, Contacts.TIMES_CONTACTED); ContactsDatabaseHelper.copyLongValue(mValues, RawContacts.STARRED, values, Contacts.STARRED); int rslt = mDb.update(Tables.CONTACTS, mValues, Contacts._ID + "=?", mSelectionArgs1); if (values.containsKey(Contacts.LAST_TIME_CONTACTED) && !values.containsKey(Contacts.TIMES_CONTACTED)) { mDb.execSQL(UPDATE_TIMES_CONTACTED_CONTACTS_TABLE, mSelectionArgs1); mDb.execSQL(UPDATE_TIMES_CONTACTED_RAWCONTACTS_TABLE, mSelectionArgs1); } return rslt; } private int updateAggregationException(SQLiteDatabase db, ContentValues values) { int exceptionType = values.getAsInteger(AggregationExceptions.TYPE); long rcId1 = values.getAsInteger(AggregationExceptions.RAW_CONTACT_ID1); long rcId2 = values.getAsInteger(AggregationExceptions.RAW_CONTACT_ID2); long rawContactId1; long rawContactId2; if (rcId1 < rcId2) { rawContactId1 = rcId1; rawContactId2 = rcId2; } else { rawContactId2 = rcId1; rawContactId1 = rcId2; } if (exceptionType == AggregationExceptions.TYPE_AUTOMATIC) { mSelectionArgs2[0] = String.valueOf(rawContactId1); mSelectionArgs2[1] = String.valueOf(rawContactId2); db.delete(Tables.AGGREGATION_EXCEPTIONS, AggregationExceptions.RAW_CONTACT_ID1 + "=? AND " + AggregationExceptions.RAW_CONTACT_ID2 + "=?", mSelectionArgs2); } else { ContentValues exceptionValues = new ContentValues(3); exceptionValues.put(AggregationExceptions.TYPE, exceptionType); exceptionValues.put(AggregationExceptions.RAW_CONTACT_ID1, rawContactId1); exceptionValues.put(AggregationExceptions.RAW_CONTACT_ID2, rawContactId2); db.replace(Tables.AGGREGATION_EXCEPTIONS, AggregationExceptions._ID, exceptionValues); } mContactAggregator.invalidateAggregationExceptionCache(); mContactAggregator.markForAggregation(rawContactId1, RawContacts.AGGREGATION_MODE_DEFAULT, true); mContactAggregator.markForAggregation(rawContactId2, RawContacts.AGGREGATION_MODE_DEFAULT, true); mContactAggregator.aggregateContact(mTransactionContext, db, rawContactId1); mContactAggregator.aggregateContact(mTransactionContext, db, rawContactId2); // The return value is fake - we just confirm that we made a change, not count actual // rows changed. return 1; } public void onAccountsUpdated(Account[] accounts) { scheduleBackgroundTask(BACKGROUND_TASK_UPDATE_ACCOUNTS); } protected boolean updateAccountsInBackground(Account[] accounts) { // TODO : Check the unit test. boolean accountsChanged = false; mDb = mDbHelper.getWritableDatabase(); mDb.beginTransaction(); try { Set<AccountWithDataSet> existingAccountsWithDataSets = findValidAccountsWithDataSets(Tables.ACCOUNTS); // Add a row to the ACCOUNTS table (with no data set) for each new account. for (Account account : accounts) { AccountWithDataSet accountWithDataSet = new AccountWithDataSet( account.name, account.type, null); if (!existingAccountsWithDataSets.contains(accountWithDataSet)) { accountsChanged = true; // Add an account entry with an empty data set to match the account. mDb.execSQL("INSERT INTO " + Tables.ACCOUNTS + " (" + RawContacts.ACCOUNT_NAME + ", " + RawContacts.ACCOUNT_TYPE + ", " + RawContacts.DATA_SET + ") VALUES (?, ?, ?)", new String[] { accountWithDataSet.getAccountName(), accountWithDataSet.getAccountType(), accountWithDataSet.getDataSet() }); } } // Check each of the existing sub-accounts against the account list. If the owning // account no longer exists, the sub-account and all its data should be deleted. List<AccountWithDataSet> accountsWithDataSetsToDelete = new ArrayList<AccountWithDataSet>(); List<Account> accountList = Arrays.asList(accounts); for (AccountWithDataSet accountWithDataSet : existingAccountsWithDataSets) { Account owningAccount = new Account( accountWithDataSet.getAccountName(), accountWithDataSet.getAccountType()); if (!accountList.contains(owningAccount)) { accountsWithDataSetsToDelete.add(accountWithDataSet); } } if (!accountsWithDataSetsToDelete.isEmpty()) { accountsChanged = true; for (AccountWithDataSet accountWithDataSet : accountsWithDataSetsToDelete) { Log.d(TAG, "removing data for removed account " + accountWithDataSet); String[] accountParams = new String[] { accountWithDataSet.getAccountName(), accountWithDataSet.getAccountType() }; String[] accountWithDataSetParams = accountWithDataSet.getDataSet() == null ? accountParams : new String[] { accountWithDataSet.getAccountName(), accountWithDataSet.getAccountType(), accountWithDataSet.getDataSet() }; String groupsDataSetClause = " AND " + Groups.DATA_SET + (accountWithDataSet.getDataSet() == null ? " IS NULL" : " = ?"); String rawContactsDataSetClause = " AND " + RawContacts.DATA_SET + (accountWithDataSet.getDataSet() == null ? " IS NULL" : " = ?"); mDb.execSQL( "DELETE FROM " + Tables.GROUPS + " WHERE " + Groups.ACCOUNT_NAME + " = ?" + " AND " + Groups.ACCOUNT_TYPE + " = ?" + groupsDataSetClause, accountWithDataSetParams); mDb.execSQL( "DELETE FROM " + Tables.PRESENCE + " WHERE " + PresenceColumns.RAW_CONTACT_ID + " IN (" + "SELECT " + RawContacts._ID + " FROM " + Tables.RAW_CONTACTS + " WHERE " + RawContacts.ACCOUNT_NAME + " = ?" + " AND " + RawContacts.ACCOUNT_TYPE + " = ?" + rawContactsDataSetClause + ")", accountWithDataSetParams); mDb.execSQL( "DELETE FROM " + Tables.RAW_CONTACTS + " WHERE " + RawContacts.ACCOUNT_NAME + " = ?" + " AND " + RawContacts.ACCOUNT_TYPE + " = ?" + rawContactsDataSetClause, accountWithDataSetParams); mDb.execSQL( "DELETE FROM " + Tables.SETTINGS + " WHERE " + Settings.ACCOUNT_NAME + " = ?" + " AND " + Settings.ACCOUNT_TYPE + " = ?", accountParams); mDb.execSQL( "DELETE FROM " + Tables.ACCOUNTS + " WHERE " + RawContacts.ACCOUNT_NAME + "=?" + " AND " + RawContacts.ACCOUNT_TYPE + "=?" + rawContactsDataSetClause, accountWithDataSetParams); mDb.execSQL( "DELETE FROM " + Tables.DIRECTORIES + " WHERE " + Directory.ACCOUNT_NAME + "=?" + " AND " + Directory.ACCOUNT_TYPE + "=?", accountParams); resetDirectoryCache(); } // Find all aggregated contacts that used to contain the raw contacts // we have just deleted and see if they are still referencing the deleted // names or photos. If so, fix up those contacts. HashSet<Long> orphanContactIds = Sets.newHashSet(); Cursor cursor = mDb.rawQuery("SELECT " + Contacts._ID + " FROM " + Tables.CONTACTS + " WHERE (" + Contacts.NAME_RAW_CONTACT_ID + " NOT NULL AND " + Contacts.NAME_RAW_CONTACT_ID + " NOT IN " + "(SELECT " + RawContacts._ID + " FROM " + Tables.RAW_CONTACTS + "))" + " OR (" + Contacts.PHOTO_ID + " NOT NULL AND " + Contacts.PHOTO_ID + " NOT IN " + "(SELECT " + Data._ID + " FROM " + Tables.DATA + "))", null); try { while (cursor.moveToNext()) { orphanContactIds.add(cursor.getLong(0)); } } finally { cursor.close(); } for (Long contactId : orphanContactIds) { mContactAggregator.updateAggregateData(mTransactionContext, contactId); } mDbHelper.updateAllVisible(); updateSearchIndexInTransaction(); } // Now that we've done the account-based additions and subtractions from the Accounts // table, check for raw contacts that have been added with a data set and add Accounts // entries for those if necessary. existingAccountsWithDataSets = findValidAccountsWithDataSets(Tables.ACCOUNTS); Set<AccountWithDataSet> rawContactAccountsWithDataSets = findValidAccountsWithDataSets(Tables.RAW_CONTACTS); rawContactAccountsWithDataSets.removeAll(existingAccountsWithDataSets); // Any remaining raw contact sub-accounts need to be added to the Accounts table. for (AccountWithDataSet accountWithDataSet : rawContactAccountsWithDataSets) { accountsChanged = true; // Add an account entry to match the raw contact. mDb.execSQL("INSERT INTO " + Tables.ACCOUNTS + " (" + RawContacts.ACCOUNT_NAME + ", " + RawContacts.ACCOUNT_TYPE + ", " + RawContacts.DATA_SET + ") VALUES (?, ?, ?)", new String[] { accountWithDataSet.getAccountName(), accountWithDataSet.getAccountType(), accountWithDataSet.getDataSet() }); } if (accountsChanged) { // TODO: Should sync state take data set into consideration? mDbHelper.getSyncState().onAccountsChanged(mDb, accounts); } mDb.setTransactionSuccessful(); } finally { mDb.endTransaction(); } mAccountWritability.clear(); if (accountsChanged) { updateContactsAccountCount(accounts); updateProviderStatus(); } return accountsChanged; } private void updateContactsAccountCount(Account[] accounts) { int count = 0; for (Account account : accounts) { if (isContactsAccount(account)) { count++; } } mContactsAccountCount = count; } protected boolean isContactsAccount(Account account) { final IContentService cs = ContentResolver.getContentService(); try { return cs.getIsSyncable(account, ContactsContract.AUTHORITY) > 0; } catch (RemoteException e) { Log.e(TAG, "Cannot obtain sync flag for account: " + account, e); return false; } } public void onPackageChanged(String packageName) { scheduleBackgroundTask(BACKGROUND_TASK_UPDATE_DIRECTORIES, packageName); } /** * Finds all distinct account types and data sets present in the specified table. */ private Set<AccountWithDataSet> findValidAccountsWithDataSets(String table) { Set<AccountWithDataSet> accountsWithDataSets = new HashSet<AccountWithDataSet>(); Cursor c = mDb.rawQuery( "SELECT DISTINCT " + RawContacts.ACCOUNT_NAME + "," + RawContacts.ACCOUNT_TYPE + "," + RawContacts.DATA_SET + " FROM " + table, null); try { while (c.moveToNext()) { if (!c.isNull(0) || !c.isNull(1)) { accountsWithDataSets.add( new AccountWithDataSet(c.getString(0), c.getString(1), c.getString(2))); } } } finally { c.close(); } return accountsWithDataSets; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { waitForAccess(mReadAccessLatch); String directory = getQueryParameter(uri, ContactsContract.DIRECTORY_PARAM_KEY); if (directory == null) { return wrapCursor(uri, queryLocal(uri, projection, selection, selectionArgs, sortOrder, -1, false)); } else if (directory.equals("0")) { return wrapCursor(uri, queryLocal(uri, projection, selection, selectionArgs, sortOrder, Directory.DEFAULT, false)); } else if (directory.equals("1")) { return wrapCursor(uri, queryLocal(uri, projection, selection, selectionArgs, sortOrder, Directory.LOCAL_INVISIBLE, false)); } DirectoryInfo directoryInfo = getDirectoryAuthority(directory); if (directoryInfo == null) { Log.e(TAG, "Invalid directory ID: " + uri); return null; } Builder builder = new Uri.Builder(); builder.scheme(ContentResolver.SCHEME_CONTENT); builder.authority(directoryInfo.authority); builder.encodedPath(uri.getEncodedPath()); if (directoryInfo.accountName != null) { builder.appendQueryParameter(RawContacts.ACCOUNT_NAME, directoryInfo.accountName); } if (directoryInfo.accountType != null) { builder.appendQueryParameter(RawContacts.ACCOUNT_TYPE, directoryInfo.accountType); } String limit = getLimit(uri); if (limit != null) { builder.appendQueryParameter(ContactsContract.LIMIT_PARAM_KEY, limit); } Uri directoryUri = builder.build(); if (projection == null) { projection = getDefaultProjection(uri); } Cursor cursor = getContext().getContentResolver().query(directoryUri, projection, selection, selectionArgs, sortOrder); if (cursor == null) { return null; } CrossProcessCursor crossProcessCursor = getCrossProcessCursor(cursor); if (crossProcessCursor != null) { return wrapCursor(uri, cursor); } else { return matrixCursorFromCursor(wrapCursor(uri, cursor)); } } private Cursor wrapCursor(Uri uri, Cursor cursor) { // If the cursor doesn't contain a snippet column, don't bother wrapping it. if (cursor.getColumnIndex(SearchSnippetColumns.SNIPPET) < 0) { if (VERBOSE_LOGGING) { return new InstrumentedCursorWrapper(cursor, uri, TAG); } else { return cursor; } } // Parse out snippet arguments for use when snippets are retrieved from the cursor. String[] args = null; String snippetArgs = getQueryParameter(uri, SearchSnippetColumns.SNIPPET_ARGS_PARAM_KEY); if (snippetArgs != null) { args = snippetArgs.split(","); } String query = uri.getLastPathSegment(); String startMatch = args != null && args.length > 0 ? args[0] : DEFAULT_SNIPPET_ARG_START_MATCH; String endMatch = args != null && args.length > 1 ? args[1] : DEFAULT_SNIPPET_ARG_END_MATCH; String ellipsis = args != null && args.length > 2 ? args[2] : DEFAULT_SNIPPET_ARG_ELLIPSIS; int maxTokens = args != null && args.length > 3 ? Integer.parseInt(args[3]) : DEFAULT_SNIPPET_ARG_MAX_TOKENS; if (VERBOSE_LOGGING) { return new InstrumentedCursorWrapper(new SnippetizingCursorWrapper( cursor, query, startMatch, endMatch, ellipsis, maxTokens), uri, TAG); } else { return new SnippetizingCursorWrapper(cursor, query, startMatch, endMatch, ellipsis, maxTokens); } } private CrossProcessCursor getCrossProcessCursor(Cursor cursor) { Cursor c = cursor; if (c instanceof CrossProcessCursor) { return (CrossProcessCursor) c; } else if (c instanceof CursorWindow) { return getCrossProcessCursor(((CursorWrapper) c).getWrappedCursor()); } else { return null; } } public MatrixCursor matrixCursorFromCursor(Cursor cursor) { MatrixCursor newCursor = new MatrixCursor(cursor.getColumnNames()); int numColumns = cursor.getColumnCount(); String data[] = new String[numColumns]; cursor.moveToPosition(-1); while (cursor.moveToNext()) { for (int i = 0; i < numColumns; i++) { data[i] = cursor.getString(i); } newCursor.addRow(data); } return newCursor; } private static final class DirectoryQuery { public static final String[] COLUMNS = new String[] { Directory._ID, Directory.DIRECTORY_AUTHORITY, Directory.ACCOUNT_NAME, Directory.ACCOUNT_TYPE }; public static final int DIRECTORY_ID = 0; public static final int AUTHORITY = 1; public static final int ACCOUNT_NAME = 2; public static final int ACCOUNT_TYPE = 3; } /** * Reads and caches directory information for the database. */ private DirectoryInfo getDirectoryAuthority(String directoryId) { synchronized (mDirectoryCache) { if (!mDirectoryCacheValid) { mDirectoryCache.clear(); SQLiteDatabase db = mDbHelper.getReadableDatabase(); Cursor cursor = db.query(Tables.DIRECTORIES, DirectoryQuery.COLUMNS, null, null, null, null, null); try { while (cursor.moveToNext()) { DirectoryInfo info = new DirectoryInfo(); String id = cursor.getString(DirectoryQuery.DIRECTORY_ID); info.authority = cursor.getString(DirectoryQuery.AUTHORITY); info.accountName = cursor.getString(DirectoryQuery.ACCOUNT_NAME); info.accountType = cursor.getString(DirectoryQuery.ACCOUNT_TYPE); mDirectoryCache.put(id, info); } } finally { cursor.close(); } mDirectoryCacheValid = true; } return mDirectoryCache.get(directoryId); } } public void resetDirectoryCache() { synchronized(mDirectoryCache) { mDirectoryCacheValid = false; } } private Cursor queryLocal(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder, long directoryId, final boolean suppressProfileCheck) { if (VERBOSE_LOGGING) { Log.v(TAG, "query: " + uri); } final SQLiteDatabase db = mDbHelper.getReadableDatabase(); SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); String groupBy = null; String limit = getLimit(uri); // Column name for appendProfileRestriction(). We append the profile check to the original // selection if it's not null. String profileRestrictionColumnName = null; final int match = sUriMatcher.match(uri); switch (match) { case SYNCSTATE: return mDbHelper.getSyncState().query(db, projection, selection, selectionArgs, sortOrder); case CONTACTS: { setTablesAndProjectionMapForContacts(qb, uri, projection); appendLocalDirectorySelectionIfNeeded(qb, directoryId); profileRestrictionColumnName = Contacts.IS_USER_PROFILE; sortOrder = prependProfileSortIfNeeded(uri, sortOrder, suppressProfileCheck); break; } case CONTACTS_ID: { long contactId = ContentUris.parseId(uri); enforceProfilePermissionForContact(db, contactId, false); setTablesAndProjectionMapForContacts(qb, uri, projection); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(Contacts._ID + "=?"); break; } case CONTACTS_LOOKUP: case CONTACTS_LOOKUP_ID: { List<String> pathSegments = uri.getPathSegments(); int segmentCount = pathSegments.size(); if (segmentCount < 3) { throw new IllegalArgumentException(mDbHelper.exceptionMessage( "Missing a lookup key", uri)); } String lookupKey = pathSegments.get(2); if (segmentCount == 4) { long contactId = Long.parseLong(pathSegments.get(3)); enforceProfilePermissionForContact(db, contactId, false); SQLiteQueryBuilder lookupQb = new SQLiteQueryBuilder(); setTablesAndProjectionMapForContacts(lookupQb, uri, projection); Cursor c = queryWithContactIdAndLookupKey(lookupQb, db, uri, projection, selection, selectionArgs, sortOrder, groupBy, limit, Contacts._ID, contactId, Contacts.LOOKUP_KEY, lookupKey); if (c != null) { return c; } } setTablesAndProjectionMapForContacts(qb, uri, projection); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(lookupContactIdByLookupKey(db, lookupKey))); qb.appendWhere(Contacts._ID + "=?"); break; } case CONTACTS_LOOKUP_DATA: case CONTACTS_LOOKUP_ID_DATA: { List<String> pathSegments = uri.getPathSegments(); int segmentCount = pathSegments.size(); if (segmentCount < 4) { throw new IllegalArgumentException(mDbHelper.exceptionMessage( "Missing a lookup key", uri)); } String lookupKey = pathSegments.get(2); if (segmentCount == 5) { long contactId = Long.parseLong(pathSegments.get(3)); enforceProfilePermissionForContact(db, contactId, false); SQLiteQueryBuilder lookupQb = new SQLiteQueryBuilder(); setTablesAndProjectionMapForData(lookupQb, uri, projection, false); lookupQb.appendWhere(" AND "); Cursor c = queryWithContactIdAndLookupKey(lookupQb, db, uri, projection, selection, selectionArgs, sortOrder, groupBy, limit, Data.CONTACT_ID, contactId, Data.LOOKUP_KEY, lookupKey); if (c != null) { return c; } // TODO see if the contact exists but has no data rows (rare) } setTablesAndProjectionMapForData(qb, uri, projection, false); long contactId = lookupContactIdByLookupKey(db, lookupKey); enforceProfilePermissionForContact(db, contactId, false); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(" AND " + Data.CONTACT_ID + "=?"); break; } case CONTACTS_ID_STREAM_ITEMS: { long contactId = Long.parseLong(uri.getPathSegments().get(1)); enforceProfilePermissionForContact(db, contactId, false); setTablesAndProjectionMapForStreamItems(qb); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(RawContactsColumns.CONCRETE_CONTACT_ID + "=?"); break; } case CONTACTS_LOOKUP_STREAM_ITEMS: case CONTACTS_LOOKUP_ID_STREAM_ITEMS: { List<String> pathSegments = uri.getPathSegments(); int segmentCount = pathSegments.size(); if (segmentCount < 4) { throw new IllegalArgumentException(mDbHelper.exceptionMessage( "Missing a lookup key", uri)); } String lookupKey = pathSegments.get(2); if (segmentCount == 5) { long contactId = Long.parseLong(pathSegments.get(3)); enforceProfilePermissionForContact(db, contactId, false); SQLiteQueryBuilder lookupQb = new SQLiteQueryBuilder(); setTablesAndProjectionMapForStreamItems(lookupQb); Cursor c = queryWithContactIdAndLookupKey(lookupQb, db, uri, projection, selection, selectionArgs, sortOrder, groupBy, limit, RawContacts.CONTACT_ID, contactId, Contacts.LOOKUP_KEY, lookupKey); if (c != null) { return c; } } setTablesAndProjectionMapForStreamItems(qb); long contactId = lookupContactIdByLookupKey(db, lookupKey); enforceProfilePermissionForContact(db, contactId, false); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(RawContacts.CONTACT_ID + "=?"); break; } case CONTACTS_AS_VCARD: { final String lookupKey = Uri.encode(uri.getPathSegments().get(2)); long contactId = lookupContactIdByLookupKey(db, lookupKey); enforceProfilePermissionForContact(db, contactId, false); qb.setTables(Views.CONTACTS); qb.setProjectionMap(sContactsVCardProjectionMap); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(Contacts._ID + "=?"); break; } case CONTACTS_AS_MULTI_VCARD: { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss"); String currentDateString = dateFormat.format(new Date()).toString(); return db.rawQuery( "SELECT" + " 'vcards_' || ? || '.vcf' AS " + OpenableColumns.DISPLAY_NAME + "," + " NULL AS " + OpenableColumns.SIZE, new String[] { currentDateString }); } case CONTACTS_FILTER: { String filterParam = ""; if (uri.getPathSegments().size() > 2) { filterParam = uri.getLastPathSegment(); } setTablesAndProjectionMapForContactsWithSnippet( qb, uri, projection, filterParam, directoryId); profileRestrictionColumnName = Contacts.IS_USER_PROFILE; sortOrder = prependProfileSortIfNeeded(uri, sortOrder, suppressProfileCheck); break; } case CONTACTS_STREQUENT_FILTER: case CONTACTS_STREQUENT: { // Basically the resultant SQL should look like this: // (SQL for listing starred items) // UNION ALL // (SQL for listing frequently contacted items) // ORDER BY ... final boolean phoneOnly = readBooleanQueryParameter( uri, ContactsContract.STREQUENT_PHONE_ONLY, false); if (match == CONTACTS_STREQUENT_FILTER && uri.getPathSegments().size() > 3) { String filterParam = uri.getLastPathSegment(); StringBuilder sb = new StringBuilder(); sb.append(Contacts._ID + " IN "); appendContactFilterAsNestedQuery(sb, filterParam); selection = DbQueryUtils.concatenateClauses(selection, sb.toString()); } String[] subProjection = null; if (projection != null) { subProjection = appendProjectionArg(projection, TIMES_USED_SORT_COLUMN); } // Build the first query for starred setTablesAndProjectionMapForContacts(qb, uri, projection, false); qb.setProjectionMap(phoneOnly ? sStrequentPhoneOnlyStarredProjectionMap : sStrequentStarredProjectionMap); qb.appendWhere(DbQueryUtils.concatenateClauses( selection, Contacts.IS_USER_PROFILE + "=0")); if (phoneOnly) { qb.appendWhere(" AND " + Contacts.HAS_PHONE_NUMBER + "=1"); } qb.setStrict(true); final String starredQuery = qb.buildQuery(subProjection, Contacts.STARRED + "=1", Contacts._ID, null, null, null); // Reset the builder. qb = new SQLiteQueryBuilder(); qb.setStrict(true); // Build the second query for frequent part. final String frequentQuery; if (phoneOnly) { final StringBuilder tableBuilder = new StringBuilder(); // In phone only mode, we need to look at view_data instead of // contacts/raw_contacts to obtain actual phone numbers. One problem is that // view_data is much larger than view_contacts, so our query might become much // slower. // // To avoid the possible slow down, we start from data usage table and join // view_data to the table, assuming data usage table is quite smaller than // data rows (almost always it should be), and we don't want any phone // numbers not used by the user. This way sqlite is able to drop a number of // rows in view_data in the early stage of data lookup. tableBuilder.append(Tables.DATA_USAGE_STAT + " INNER JOIN " + Views.DATA + " " + Tables.DATA + " ON (" + DataUsageStatColumns.CONCRETE_DATA_ID + "=" + DataColumns.CONCRETE_ID + " AND " + DataUsageStatColumns.CONCRETE_USAGE_TYPE + "=" + DataUsageStatColumns.USAGE_TYPE_INT_CALL + ")"); appendContactPresenceJoin(tableBuilder, projection, RawContacts.CONTACT_ID); appendContactStatusUpdateJoin(tableBuilder, projection, ContactsColumns.LAST_STATUS_UPDATE_ID); qb.setTables(tableBuilder.toString()); qb.setProjectionMap(sStrequentPhoneOnlyFrequentProjectionMap); qb.appendWhere(DbQueryUtils.concatenateClauses( selection, Contacts.STARRED + "=0 OR " + Contacts.STARRED + " IS NULL", MimetypesColumns.MIMETYPE + " IN (" + "'" + Phone.CONTENT_ITEM_TYPE + "', " + "'" + SipAddress.CONTENT_ITEM_TYPE + "')")); frequentQuery = qb.buildQuery(subProjection, null, null, null, null, null); } else { setTablesAndProjectionMapForContacts(qb, uri, projection, true); qb.setProjectionMap(sStrequentFrequentProjectionMap); qb.appendWhere(DbQueryUtils.concatenateClauses( selection, "(" + Contacts.STARRED + " =0 OR " + Contacts.STARRED + " IS NULL)", Contacts.IS_USER_PROFILE + "=0")); frequentQuery = qb.buildQuery(subProjection, null, Contacts._ID, null, null, null); } // Put them together final String unionQuery = qb.buildUnionQuery(new String[] {starredQuery, frequentQuery}, STREQUENT_ORDER_BY, STREQUENT_LIMIT); // Here, we need to use selection / selectionArgs (supplied from users) "twice", // as we want them both for starred items and for frequently contacted items. // // e.g. if the user specify selection = "starred =?" and selectionArgs = "0", // the resultant SQL should be like: // SELECT ... WHERE starred =? AND ... // UNION ALL // SELECT ... WHERE starred =? AND ... String[] doubledSelectionArgs = null; if (selectionArgs != null) { final int length = selectionArgs.length; doubledSelectionArgs = new String[length * 2]; System.arraycopy(selectionArgs, 0, doubledSelectionArgs, 0, length); System.arraycopy(selectionArgs, 0, doubledSelectionArgs, length, length); } Cursor cursor = db.rawQuery(unionQuery, doubledSelectionArgs); if (cursor != null) { cursor.setNotificationUri(getContext().getContentResolver(), ContactsContract.AUTHORITY_URI); } return cursor; } case CONTACTS_FREQUENT: { setTablesAndProjectionMapForContacts(qb, uri, projection, true); qb.setProjectionMap(sStrequentFrequentProjectionMap); qb.appendWhere(Contacts.IS_USER_PROFILE + "=0"); groupBy = Contacts._ID; if (!TextUtils.isEmpty(sortOrder)) { sortOrder = FREQUENT_ORDER_BY + ", " + sortOrder; } else { sortOrder = FREQUENT_ORDER_BY; } break; } case CONTACTS_GROUP: { setTablesAndProjectionMapForContacts(qb, uri, projection); if (uri.getPathSegments().size() > 2) { qb.appendWhere(CONTACTS_IN_GROUP_SELECT); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); } break; } case PROFILE: { enforceProfilePermission(false); setTablesAndProjectionMapForContacts(qb, uri, projection); qb.appendWhere(Contacts.IS_USER_PROFILE + "=1"); break; } case PROFILE_ENTITIES: { enforceProfilePermission(false); setTablesAndProjectionMapForEntities(qb, uri, projection); qb.appendWhere(" AND " + Contacts.IS_USER_PROFILE + "=1"); break; } case PROFILE_DATA: { enforceProfilePermission(false); setTablesAndProjectionMapForData(qb, uri, projection, false); qb.appendWhere(" AND " + RawContacts.RAW_CONTACT_IS_USER_PROFILE + "=1"); break; } case PROFILE_DATA_ID: { enforceProfilePermission(false); setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(" AND " + Data._ID + "=? AND " + RawContacts.RAW_CONTACT_IS_USER_PROFILE + "=1"); break; } case PROFILE_AS_VCARD: { enforceProfilePermission(false); qb.setTables(Views.CONTACTS); qb.setProjectionMap(sContactsVCardProjectionMap); qb.appendWhere(Contacts.IS_USER_PROFILE + "=1"); break; } case CONTACTS_ID_DATA: { long contactId = Long.parseLong(uri.getPathSegments().get(1)); setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(" AND " + RawContacts.CONTACT_ID + "=?"); break; } case CONTACTS_ID_PHOTO: { long contactId = Long.parseLong(uri.getPathSegments().get(1)); enforceProfilePermissionForContact(db, contactId, false); setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(" AND " + RawContacts.CONTACT_ID + "=?"); qb.appendWhere(" AND " + Data._ID + "=" + Contacts.PHOTO_ID); break; } case CONTACTS_ID_ENTITIES: { long contactId = Long.parseLong(uri.getPathSegments().get(1)); setTablesAndProjectionMapForEntities(qb, uri, projection); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(" AND " + RawContacts.CONTACT_ID + "=?"); break; } case CONTACTS_LOOKUP_ENTITIES: case CONTACTS_LOOKUP_ID_ENTITIES: { List<String> pathSegments = uri.getPathSegments(); int segmentCount = pathSegments.size(); if (segmentCount < 4) { throw new IllegalArgumentException(mDbHelper.exceptionMessage( "Missing a lookup key", uri)); } String lookupKey = pathSegments.get(2); if (segmentCount == 5) { long contactId = Long.parseLong(pathSegments.get(3)); SQLiteQueryBuilder lookupQb = new SQLiteQueryBuilder(); setTablesAndProjectionMapForEntities(lookupQb, uri, projection); lookupQb.appendWhere(" AND "); Cursor c = queryWithContactIdAndLookupKey(lookupQb, db, uri, projection, selection, selectionArgs, sortOrder, groupBy, limit, Contacts.Entity.CONTACT_ID, contactId, Contacts.Entity.LOOKUP_KEY, lookupKey); if (c != null) { return c; } } setTablesAndProjectionMapForEntities(qb, uri, projection); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(lookupContactIdByLookupKey(db, lookupKey))); qb.appendWhere(" AND " + Contacts.Entity.CONTACT_ID + "=?"); break; } case STREAM_ITEMS: { setTablesAndProjectionMapForStreamItems(qb); break; } case STREAM_ITEMS_ID: { setTablesAndProjectionMapForStreamItems(qb); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(StreamItemsColumns.CONCRETE_ID + "=?"); break; } case STREAM_ITEMS_LIMIT: { MatrixCursor cursor = new MatrixCursor(new String[]{StreamItems.MAX_ITEMS}, 1); cursor.addRow(new Object[]{MAX_STREAM_ITEMS_PER_RAW_CONTACT}); return cursor; } case STREAM_ITEMS_PHOTOS: { setTablesAndProjectionMapForStreamItemPhotos(qb); break; } case STREAM_ITEMS_ID_PHOTOS: { setTablesAndProjectionMapForStreamItemPhotos(qb); String streamItemId = uri.getPathSegments().get(1); selectionArgs = insertSelectionArg(selectionArgs, streamItemId); qb.appendWhere(StreamItemPhotosColumns.CONCRETE_STREAM_ITEM_ID + "=?"); break; } case STREAM_ITEMS_ID_PHOTOS_ID: { setTablesAndProjectionMapForStreamItemPhotos(qb); String streamItemId = uri.getPathSegments().get(1); String streamItemPhotoId = uri.getPathSegments().get(3); selectionArgs = insertSelectionArg(selectionArgs, streamItemPhotoId); selectionArgs = insertSelectionArg(selectionArgs, streamItemId); qb.appendWhere(StreamItemPhotosColumns.CONCRETE_STREAM_ITEM_ID + "=? AND " + StreamItemPhotosColumns.CONCRETE_ID + "=?"); break; } case PHOTO_DIMENSIONS: { MatrixCursor cursor = new MatrixCursor( new String[]{DisplayPhoto.DISPLAY_MAX_DIM, DisplayPhoto.THUMBNAIL_MAX_DIM}, 1); cursor.addRow(new Object[]{mMaxDisplayPhotoDim, mMaxThumbnailPhotoDim}); return cursor; } case PHONES: { setTablesAndProjectionMapForData(qb, uri, projection, false); qb.appendWhere(" AND " + Data.MIMETYPE + " = '" + Phone.CONTENT_ITEM_TYPE + "'"); break; } case PHONES_ID: { setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(" AND " + Data.MIMETYPE + " = '" + Phone.CONTENT_ITEM_TYPE + "'"); qb.appendWhere(" AND " + Data._ID + "=?"); break; } case PHONES_FILTER: { String typeParam = uri.getQueryParameter(DataUsageFeedback.USAGE_TYPE); + profileRestrictionColumnName = RawContacts.RAW_CONTACT_IS_USER_PROFILE; Integer typeInt = sDataUsageTypeMap.get(typeParam); if (typeInt == null) { typeInt = DataUsageStatColumns.USAGE_TYPE_INT_CALL; } setTablesAndProjectionMapForData(qb, uri, projection, true, typeInt); qb.appendWhere(" AND " + Data.MIMETYPE + " = '" + Phone.CONTENT_ITEM_TYPE + "'"); if (uri.getPathSegments().size() > 2) { String filterParam = uri.getLastPathSegment(); StringBuilder sb = new StringBuilder(); sb.append(" AND ("); boolean hasCondition = false; boolean orNeeded = false; String normalizedName = NameNormalizer.normalize(filterParam); if (normalizedName.length() > 0) { sb.append(Data.RAW_CONTACT_ID + " IN " + "(SELECT " + RawContactsColumns.CONCRETE_ID + " FROM " + Tables.SEARCH_INDEX + " JOIN " + Tables.RAW_CONTACTS + " ON (" + Tables.SEARCH_INDEX + "." + SearchIndexColumns.CONTACT_ID + "=" + RawContactsColumns.CONCRETE_CONTACT_ID + ")" + " WHERE " + SearchIndexColumns.NAME + " MATCH "); DatabaseUtils.appendEscapedSQLString(sb, sanitizeMatch(filterParam) + "*"); sb.append(")"); orNeeded = true; hasCondition = true; } String number = PhoneNumberUtils.normalizeNumber(filterParam); if (!TextUtils.isEmpty(number)) { if (orNeeded) { sb.append(" OR "); } sb.append(Data._ID + " IN (SELECT DISTINCT " + PhoneLookupColumns.DATA_ID + " FROM " + Tables.PHONE_LOOKUP + " WHERE " + PhoneLookupColumns.NORMALIZED_NUMBER + " LIKE '"); sb.append(number); sb.append("%')"); hasCondition = true; } if (!hasCondition) { // If it is neither a phone number nor a name, the query should return // an empty cursor. Let's ensure that. sb.append("0"); } sb.append(")"); qb.appendWhere(sb); } groupBy = PhoneColumns.NORMALIZED_NUMBER + "," + RawContacts.CONTACT_ID; if (sortOrder == null) { final String accountPromotionSortOrder = getAccountPromotionSortOrder(uri); if (!TextUtils.isEmpty(accountPromotionSortOrder)) { sortOrder = accountPromotionSortOrder + ", " + PHONE_FILTER_SORT_ORDER; } else { sortOrder = PHONE_FILTER_SORT_ORDER; } } break; } case EMAILS: { setTablesAndProjectionMapForData(qb, uri, projection, false); qb.appendWhere(" AND " + Data.MIMETYPE + " = '" + Email.CONTENT_ITEM_TYPE + "'"); break; } case EMAILS_ID: { setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(" AND " + Data.MIMETYPE + " = '" + Email.CONTENT_ITEM_TYPE + "'" + " AND " + Data._ID + "=?"); break; } case EMAILS_LOOKUP: { setTablesAndProjectionMapForData(qb, uri, projection, false); qb.appendWhere(" AND " + Data.MIMETYPE + " = '" + Email.CONTENT_ITEM_TYPE + "'"); if (uri.getPathSegments().size() > 2) { String email = uri.getLastPathSegment(); String address = mDbHelper.extractAddressFromEmailAddress(email); selectionArgs = insertSelectionArg(selectionArgs, address); qb.appendWhere(" AND UPPER(" + Email.DATA + ")=UPPER(?)"); } break; } case EMAILS_FILTER: { String typeParam = uri.getQueryParameter(DataUsageFeedback.USAGE_TYPE); + profileRestrictionColumnName = RawContacts.RAW_CONTACT_IS_USER_PROFILE; Integer typeInt = sDataUsageTypeMap.get(typeParam); if (typeInt == null) { typeInt = DataUsageStatColumns.USAGE_TYPE_INT_LONG_TEXT; } setTablesAndProjectionMapForData(qb, uri, projection, true, typeInt); String filterParam = null; if (uri.getPathSegments().size() > 3) { filterParam = uri.getLastPathSegment(); if (TextUtils.isEmpty(filterParam)) { filterParam = null; } } if (filterParam == null) { // If the filter is unspecified, return nothing qb.appendWhere(" AND 0"); } else { StringBuilder sb = new StringBuilder(); sb.append(" AND " + Data._ID + " IN ("); sb.append( "SELECT " + Data._ID + " FROM " + Tables.DATA + " WHERE " + DataColumns.MIMETYPE_ID + "="); sb.append(mDbHelper.getMimeTypeIdForEmail()); sb.append(" AND " + Data.DATA1 + " LIKE "); DatabaseUtils.appendEscapedSQLString(sb, filterParam + '%'); if (!filterParam.contains("@")) { sb.append( " UNION SELECT " + Data._ID + " FROM " + Tables.DATA + " WHERE +" + DataColumns.MIMETYPE_ID + "="); sb.append(mDbHelper.getMimeTypeIdForEmail()); sb.append(" AND " + Data.RAW_CONTACT_ID + " IN " + "(SELECT " + RawContactsColumns.CONCRETE_ID + " FROM " + Tables.SEARCH_INDEX + " JOIN " + Tables.RAW_CONTACTS + " ON (" + Tables.SEARCH_INDEX + "." + SearchIndexColumns.CONTACT_ID + "=" + RawContactsColumns.CONCRETE_CONTACT_ID + ")" + " WHERE " + SearchIndexColumns.NAME + " MATCH "); DatabaseUtils.appendEscapedSQLString(sb, sanitizeMatch(filterParam) + "*"); sb.append(")"); } sb.append(")"); qb.appendWhere(sb); } groupBy = Email.DATA + "," + RawContacts.CONTACT_ID; if (sortOrder == null) { final String accountPromotionSortOrder = getAccountPromotionSortOrder(uri); if (!TextUtils.isEmpty(accountPromotionSortOrder)) { sortOrder = accountPromotionSortOrder + ", " + EMAIL_FILTER_SORT_ORDER; } else { sortOrder = EMAIL_FILTER_SORT_ORDER; } } break; } case POSTALS: { setTablesAndProjectionMapForData(qb, uri, projection, false); qb.appendWhere(" AND " + Data.MIMETYPE + " = '" + StructuredPostal.CONTENT_ITEM_TYPE + "'"); break; } case POSTALS_ID: { setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(" AND " + Data.MIMETYPE + " = '" + StructuredPostal.CONTENT_ITEM_TYPE + "'"); qb.appendWhere(" AND " + Data._ID + "=?"); break; } case RAW_CONTACTS: { setTablesAndProjectionMapForRawContacts(qb, uri); profileRestrictionColumnName = RawContacts.RAW_CONTACT_IS_USER_PROFILE; break; } case RAW_CONTACTS_ID: { long rawContactId = ContentUris.parseId(uri); enforceProfilePermissionForRawContact(db, rawContactId, false); setTablesAndProjectionMapForRawContacts(qb, uri); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId)); qb.appendWhere(" AND " + RawContacts._ID + "=?"); break; } case RAW_CONTACTS_DATA: { long rawContactId = Long.parseLong(uri.getPathSegments().get(1)); setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId)); qb.appendWhere(" AND " + Data.RAW_CONTACT_ID + "=?"); profileRestrictionColumnName = RawContacts.RAW_CONTACT_IS_USER_PROFILE; break; } case RAW_CONTACTS_ID_STREAM_ITEMS: { long rawContactId = Long.parseLong(uri.getPathSegments().get(1)); enforceProfilePermissionForRawContact(db, rawContactId, false); setTablesAndProjectionMapForStreamItems(qb); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId)); qb.appendWhere(StreamItems.RAW_CONTACT_ID + "=?"); break; } case PROFILE_RAW_CONTACTS: { enforceProfilePermission(false); setTablesAndProjectionMapForRawContacts(qb, uri); qb.appendWhere(" AND " + RawContacts.RAW_CONTACT_IS_USER_PROFILE + "=1"); break; } case PROFILE_RAW_CONTACTS_ID: { enforceProfilePermission(false); long rawContactId = ContentUris.parseId(uri); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId)); setTablesAndProjectionMapForRawContacts(qb, uri); qb.appendWhere(" AND " + RawContacts.RAW_CONTACT_IS_USER_PROFILE + "=1 AND " + RawContacts._ID + "=?"); break; } case PROFILE_RAW_CONTACTS_ID_DATA: { enforceProfilePermission(false); long rawContactId = Long.parseLong(uri.getPathSegments().get(2)); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId)); setTablesAndProjectionMapForData(qb, uri, projection, false); qb.appendWhere(" AND " + RawContacts.RAW_CONTACT_IS_USER_PROFILE + "=1 AND " + Data.RAW_CONTACT_ID + "=?"); break; } case PROFILE_RAW_CONTACTS_ID_ENTITIES: { enforceProfilePermission(false); long rawContactId = Long.parseLong(uri.getPathSegments().get(2)); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId)); setTablesAndProjectionMapForRawEntities(qb, uri); qb.appendWhere(" AND " + RawContacts.RAW_CONTACT_IS_USER_PROFILE + "=1 AND " + RawContacts._ID + "=?"); break; } case DATA: { setTablesAndProjectionMapForData(qb, uri, projection, false); profileRestrictionColumnName = RawContacts.RAW_CONTACT_IS_USER_PROFILE; break; } case DATA_ID: { long dataId = ContentUris.parseId(uri); enforceProfilePermissionForData(db, dataId, false); setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(" AND " + Data._ID + "=?"); break; } case PHONE_LOOKUP: { if (TextUtils.isEmpty(sortOrder)) { // Default the sort order to something reasonable so we get consistent // results when callers don't request an ordering sortOrder = " length(lookup.normalized_number) DESC"; } String number = uri.getPathSegments().size() > 1 ? uri.getLastPathSegment() : ""; String numberE164 = PhoneNumberUtils.formatNumberToE164(number, mDbHelper.getCurrentCountryIso()); String normalizedNumber = PhoneNumberUtils.normalizeNumber(number); mDbHelper.buildPhoneLookupAndContactQuery(qb, normalizedNumber, numberE164); qb.setProjectionMap(sPhoneLookupProjectionMap); // Phone lookup cannot be combined with a selection selection = null; selectionArgs = null; break; } case GROUPS: { qb.setTables(Views.GROUPS); qb.setProjectionMap(sGroupsProjectionMap); appendAccountFromParameter(qb, uri, true); break; } case GROUPS_ID: { qb.setTables(Views.GROUPS); qb.setProjectionMap(sGroupsProjectionMap); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(Groups._ID + "=?"); break; } case GROUPS_SUMMARY: { final boolean returnGroupCountPerAccount = readBooleanQueryParameter(uri, Groups.PARAM_RETURN_GROUP_COUNT_PER_ACCOUNT, false); qb.setTables(Views.GROUPS + " AS " + Tables.GROUPS); qb.setProjectionMap(returnGroupCountPerAccount ? sGroupsSummaryProjectionMapWithGroupCountPerAccount : sGroupsSummaryProjectionMap); appendAccountFromParameter(qb, uri, true); groupBy = GroupsColumns.CONCRETE_ID; break; } case AGGREGATION_EXCEPTIONS: { qb.setTables(Tables.AGGREGATION_EXCEPTIONS); qb.setProjectionMap(sAggregationExceptionsProjectionMap); break; } case AGGREGATION_SUGGESTIONS: { long contactId = Long.parseLong(uri.getPathSegments().get(1)); String filter = null; if (uri.getPathSegments().size() > 3) { filter = uri.getPathSegments().get(3); } final int maxSuggestions; if (limit != null) { maxSuggestions = Integer.parseInt(limit); } else { maxSuggestions = DEFAULT_MAX_SUGGESTIONS; } ArrayList<AggregationSuggestionParameter> parameters = null; List<String> query = uri.getQueryParameters("query"); if (query != null && !query.isEmpty()) { parameters = new ArrayList<AggregationSuggestionParameter>(query.size()); for (String parameter : query) { int offset = parameter.indexOf(':'); parameters.add(offset == -1 ? new AggregationSuggestionParameter( AggregationSuggestions.PARAMETER_MATCH_NAME, parameter) : new AggregationSuggestionParameter( parameter.substring(0, offset), parameter.substring(offset + 1))); } } setTablesAndProjectionMapForContacts(qb, uri, projection); return mContactAggregator.queryAggregationSuggestions(qb, projection, contactId, maxSuggestions, filter, parameters); } case SETTINGS: { qb.setTables(Tables.SETTINGS); qb.setProjectionMap(sSettingsProjectionMap); appendAccountFromParameter(qb, uri, false); // When requesting specific columns, this query requires // late-binding of the GroupMembership MIME-type. final String groupMembershipMimetypeId = Long.toString(mDbHelper .getMimeTypeId(GroupMembership.CONTENT_ITEM_TYPE)); if (projection != null && projection.length != 0 && mDbHelper.isInProjection(projection, Settings.UNGROUPED_COUNT)) { selectionArgs = insertSelectionArg(selectionArgs, groupMembershipMimetypeId); } if (projection != null && projection.length != 0 && mDbHelper.isInProjection(projection, Settings.UNGROUPED_WITH_PHONES)) { selectionArgs = insertSelectionArg(selectionArgs, groupMembershipMimetypeId); } break; } case STATUS_UPDATES: { setTableAndProjectionMapForStatusUpdates(qb, projection); break; } case STATUS_UPDATES_ID: { setTableAndProjectionMapForStatusUpdates(qb, projection); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(DataColumns.CONCRETE_ID + "=?"); break; } case SEARCH_SUGGESTIONS: { return mGlobalSearchSupport.handleSearchSuggestionsQuery( db, uri, projection, limit); } case SEARCH_SHORTCUT: { String lookupKey = uri.getLastPathSegment(); String filter = getQueryParameter( uri, SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA); return mGlobalSearchSupport.handleSearchShortcutRefresh( db, projection, lookupKey, filter); } case LIVE_FOLDERS_CONTACTS: qb.setTables(Views.CONTACTS); qb.setProjectionMap(sLiveFoldersProjectionMap); break; case LIVE_FOLDERS_CONTACTS_WITH_PHONES: qb.setTables(Views.CONTACTS); qb.setProjectionMap(sLiveFoldersProjectionMap); qb.appendWhere(Contacts.HAS_PHONE_NUMBER + "=1"); break; case LIVE_FOLDERS_CONTACTS_FAVORITES: qb.setTables(Views.CONTACTS); qb.setProjectionMap(sLiveFoldersProjectionMap); qb.appendWhere(Contacts.STARRED + "=1"); break; case LIVE_FOLDERS_CONTACTS_GROUP_NAME: qb.setTables(Views.CONTACTS); qb.setProjectionMap(sLiveFoldersProjectionMap); qb.appendWhere(CONTACTS_IN_GROUP_SELECT); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); break; case RAW_CONTACT_ENTITIES: { setTablesAndProjectionMapForRawEntities(qb, uri); break; } case RAW_CONTACT_ENTITY_ID: { long rawContactId = Long.parseLong(uri.getPathSegments().get(1)); setTablesAndProjectionMapForRawEntities(qb, uri); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId)); qb.appendWhere(" AND " + RawContacts._ID + "=?"); break; } case PROVIDER_STATUS: { return queryProviderStatus(uri, projection); } case DIRECTORIES : { qb.setTables(Tables.DIRECTORIES); qb.setProjectionMap(sDirectoryProjectionMap); break; } case DIRECTORIES_ID : { long id = ContentUris.parseId(uri); qb.setTables(Tables.DIRECTORIES); qb.setProjectionMap(sDirectoryProjectionMap); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(id)); qb.appendWhere(Directory._ID + "=?"); break; } case COMPLETE_NAME: { return completeName(uri, projection); } default: return mLegacyApiSupport.query(uri, projection, selection, selectionArgs, sortOrder, limit); } qb.setStrict(true); if (profileRestrictionColumnName != null) { // This check is very slow and most of the rows will pass though this check, so // it should be put after user's selection, so SQLite won't do this check first. selection = appendProfileRestriction(uri, profileRestrictionColumnName, suppressProfileCheck, selection); } Cursor cursor = query(db, qb, projection, selection, selectionArgs, sortOrder, groupBy, limit); if (readBooleanQueryParameter(uri, ContactCounts.ADDRESS_BOOK_INDEX_EXTRAS, false)) { cursor = bundleLetterCountExtras(cursor, db, qb, selection, selectionArgs, sortOrder); } return cursor; } private Cursor query(final SQLiteDatabase db, SQLiteQueryBuilder qb, String[] projection, String selection, String[] selectionArgs, String sortOrder, String groupBy, String limit) { if (projection != null && projection.length == 1 && BaseColumns._COUNT.equals(projection[0])) { qb.setProjectionMap(sCountProjectionMap); } final Cursor c = qb.query(db, projection, selection, selectionArgs, groupBy, null, sortOrder, limit); if (c != null) { c.setNotificationUri(getContext().getContentResolver(), ContactsContract.AUTHORITY_URI); } return c; } /** * Creates a single-row cursor containing the current status of the provider. */ private Cursor queryProviderStatus(Uri uri, String[] projection) { MatrixCursor cursor = new MatrixCursor(projection); RowBuilder row = cursor.newRow(); for (int i = 0; i < projection.length; i++) { if (ProviderStatus.STATUS.equals(projection[i])) { row.add(mProviderStatus); } else if (ProviderStatus.DATA1.equals(projection[i])) { row.add(mEstimatedStorageRequirement); } } return cursor; } /** * Runs the query with the supplied contact ID and lookup ID. If the query succeeds, * it returns the resulting cursor, otherwise it returns null and the calling * method needs to resolve the lookup key and rerun the query. */ private Cursor queryWithContactIdAndLookupKey(SQLiteQueryBuilder lookupQb, SQLiteDatabase db, Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder, String groupBy, String limit, String contactIdColumn, long contactId, String lookupKeyColumn, String lookupKey) { String[] args; if (selectionArgs == null) { args = new String[2]; } else { args = new String[selectionArgs.length + 2]; System.arraycopy(selectionArgs, 0, args, 2, selectionArgs.length); } args[0] = String.valueOf(contactId); args[1] = Uri.encode(lookupKey); lookupQb.appendWhere(contactIdColumn + "=? AND " + lookupKeyColumn + "=?"); Cursor c = query(db, lookupQb, projection, selection, args, sortOrder, groupBy, limit); if (c.getCount() != 0) { return c; } c.close(); return null; } private static final class AddressBookIndexQuery { public static final String LETTER = "letter"; public static final String TITLE = "title"; public static final String COUNT = "count"; public static final String[] COLUMNS = new String[] { LETTER, TITLE, COUNT }; public static final int COLUMN_LETTER = 0; public static final int COLUMN_TITLE = 1; public static final int COLUMN_COUNT = 2; // The first letter of the sort key column is what is used for the index headings, except // in the case of the user's profile, in which case it is empty. public static final String SECTION_HEADING_TEMPLATE = "(CASE WHEN %1$s=1 THEN '' ELSE SUBSTR(%2$s,1,1) END)"; public static final String ORDER_BY = LETTER + " COLLATE " + PHONEBOOK_COLLATOR_NAME; } /** * Computes counts by the address book index titles and adds the resulting tally * to the returned cursor as a bundle of extras. */ private Cursor bundleLetterCountExtras(Cursor cursor, final SQLiteDatabase db, SQLiteQueryBuilder qb, String selection, String[] selectionArgs, String sortOrder) { String sortKey; // The sort order suffix could be something like "DESC". // We want to preserve it in the query even though we will change // the sort column itself. String sortOrderSuffix = ""; if (sortOrder != null) { // If the sort order contains one of the "is_profile" columns, we need to strip it out // first. if (sortOrder.contains(Contacts.IS_USER_PROFILE) || sortOrder.contains(RawContacts.RAW_CONTACT_IS_USER_PROFILE)) { String[] splitOrderClauses = sortOrder.split(","); StringBuilder rejoinedClause = new StringBuilder(); for (String orderClause : splitOrderClauses) { if (!orderClause.contains(Contacts.IS_USER_PROFILE) && !orderClause.contains(RawContacts.RAW_CONTACT_IS_USER_PROFILE)) { if (rejoinedClause.length() > 0) { rejoinedClause.append(", "); } rejoinedClause.append(orderClause.trim()); } } sortOrder = rejoinedClause.toString(); } int spaceIndex = sortOrder.indexOf(' '); if (spaceIndex != -1) { sortKey = sortOrder.substring(0, spaceIndex); sortOrderSuffix = sortOrder.substring(spaceIndex); } else { sortKey = sortOrder; } } else { sortKey = Contacts.SORT_KEY_PRIMARY; } String locale = getLocale().toString(); HashMap<String, String> projectionMap = Maps.newHashMap(); // The user profile column varies depending on the view. String profileColumn = qb.getTables().contains(Views.CONTACTS) ? Contacts.IS_USER_PROFILE : RawContacts.RAW_CONTACT_IS_USER_PROFILE; String sectionHeading = String.format( AddressBookIndexQuery.SECTION_HEADING_TEMPLATE, profileColumn, sortKey); projectionMap.put(AddressBookIndexQuery.LETTER, sectionHeading + " AS " + AddressBookIndexQuery.LETTER); /** * Use the GET_PHONEBOOK_INDEX function, which is an android extension for SQLite3, * to map the first letter of the sort key to a character that is traditionally * used in phonebooks to represent that letter. For example, in Korean it will * be the first consonant in the letter; for Japanese it will be Hiragana rather * than Katakana. */ projectionMap.put(AddressBookIndexQuery.TITLE, "GET_PHONEBOOK_INDEX(" + sectionHeading + ",'" + locale + "')" + " AS " + AddressBookIndexQuery.TITLE); projectionMap.put(AddressBookIndexQuery.COUNT, "COUNT(" + Contacts._ID + ") AS " + AddressBookIndexQuery.COUNT); qb.setProjectionMap(projectionMap); Cursor indexCursor = qb.query(db, AddressBookIndexQuery.COLUMNS, selection, selectionArgs, AddressBookIndexQuery.ORDER_BY, null /* having */, AddressBookIndexQuery.ORDER_BY + sortOrderSuffix); try { int groupCount = indexCursor.getCount(); String titles[] = new String[groupCount]; int counts[] = new int[groupCount]; int indexCount = 0; String currentTitle = null; // Since GET_PHONEBOOK_INDEX is a many-to-1 function, we may end up // with multiple entries for the same title. The following code // collapses those duplicates. for (int i = 0; i < groupCount; i++) { indexCursor.moveToNext(); String title = indexCursor.getString(AddressBookIndexQuery.COLUMN_TITLE); int count = indexCursor.getInt(AddressBookIndexQuery.COLUMN_COUNT); if (indexCount == 0 || !TextUtils.equals(title, currentTitle)) { titles[indexCount] = currentTitle = title; counts[indexCount] = count; indexCount++; } else { counts[indexCount - 1] += count; } } if (indexCount < groupCount) { String[] newTitles = new String[indexCount]; System.arraycopy(titles, 0, newTitles, 0, indexCount); titles = newTitles; int[] newCounts = new int[indexCount]; System.arraycopy(counts, 0, newCounts, 0, indexCount); counts = newCounts; } return new AddressBookCursor((CrossProcessCursor) cursor, titles, counts); } finally { indexCursor.close(); } } /** * Returns the contact Id for the contact identified by the lookupKey. * Robust against changes in the lookup key: if the key has changed, will * look up the contact by the raw contact IDs or name encoded in the lookup * key. */ public long lookupContactIdByLookupKey(SQLiteDatabase db, String lookupKey) { ContactLookupKey key = new ContactLookupKey(); ArrayList<LookupKeySegment> segments = key.parse(lookupKey); long contactId = -1; if (lookupKeyContainsType(segments, ContactLookupKey.LOOKUP_TYPE_SOURCE_ID)) { contactId = lookupContactIdBySourceIds(db, segments); if (contactId != -1) { return contactId; } } boolean hasRawContactIds = lookupKeyContainsType(segments, ContactLookupKey.LOOKUP_TYPE_RAW_CONTACT_ID); if (hasRawContactIds) { contactId = lookupContactIdByRawContactIds(db, segments); if (contactId != -1) { return contactId; } } if (hasRawContactIds || lookupKeyContainsType(segments, ContactLookupKey.LOOKUP_TYPE_DISPLAY_NAME)) { contactId = lookupContactIdByDisplayNames(db, segments); } return contactId; } private interface LookupBySourceIdQuery { String TABLE = Views.RAW_CONTACTS; String COLUMNS[] = { RawContacts.CONTACT_ID, RawContacts.ACCOUNT_TYPE_AND_DATA_SET, RawContacts.ACCOUNT_NAME, RawContacts.SOURCE_ID }; int CONTACT_ID = 0; int ACCOUNT_TYPE_AND_DATA_SET = 1; int ACCOUNT_NAME = 2; int SOURCE_ID = 3; } private long lookupContactIdBySourceIds(SQLiteDatabase db, ArrayList<LookupKeySegment> segments) { StringBuilder sb = new StringBuilder(); sb.append(RawContacts.SOURCE_ID + " IN ("); for (int i = 0; i < segments.size(); i++) { LookupKeySegment segment = segments.get(i); if (segment.lookupType == ContactLookupKey.LOOKUP_TYPE_SOURCE_ID) { DatabaseUtils.appendEscapedSQLString(sb, segment.key); sb.append(","); } } sb.setLength(sb.length() - 1); // Last comma sb.append(") AND " + RawContacts.CONTACT_ID + " NOT NULL"); Cursor c = db.query(LookupBySourceIdQuery.TABLE, LookupBySourceIdQuery.COLUMNS, sb.toString(), null, null, null, null); try { while (c.moveToNext()) { String accountTypeAndDataSet = c.getString(LookupBySourceIdQuery.ACCOUNT_TYPE_AND_DATA_SET); String accountName = c.getString(LookupBySourceIdQuery.ACCOUNT_NAME); int accountHashCode = ContactLookupKey.getAccountHashCode(accountTypeAndDataSet, accountName); String sourceId = c.getString(LookupBySourceIdQuery.SOURCE_ID); for (int i = 0; i < segments.size(); i++) { LookupKeySegment segment = segments.get(i); if (segment.lookupType == ContactLookupKey.LOOKUP_TYPE_SOURCE_ID && accountHashCode == segment.accountHashCode && segment.key.equals(sourceId)) { segment.contactId = c.getLong(LookupBySourceIdQuery.CONTACT_ID); break; } } } } finally { c.close(); } return getMostReferencedContactId(segments); } private interface LookupByRawContactIdQuery { String TABLE = Views.RAW_CONTACTS; String COLUMNS[] = { RawContacts.CONTACT_ID, RawContacts.ACCOUNT_TYPE_AND_DATA_SET, RawContacts.ACCOUNT_NAME, RawContacts._ID, }; int CONTACT_ID = 0; int ACCOUNT_TYPE_AND_DATA_SET = 1; int ACCOUNT_NAME = 2; int ID = 3; } private long lookupContactIdByRawContactIds(SQLiteDatabase db, ArrayList<LookupKeySegment> segments) { StringBuilder sb = new StringBuilder(); sb.append(RawContacts._ID + " IN ("); for (int i = 0; i < segments.size(); i++) { LookupKeySegment segment = segments.get(i); if (segment.lookupType == ContactLookupKey.LOOKUP_TYPE_RAW_CONTACT_ID) { sb.append(segment.rawContactId); sb.append(","); } } sb.setLength(sb.length() - 1); // Last comma sb.append(") AND " + RawContacts.CONTACT_ID + " NOT NULL"); Cursor c = db.query(LookupByRawContactIdQuery.TABLE, LookupByRawContactIdQuery.COLUMNS, sb.toString(), null, null, null, null); try { while (c.moveToNext()) { String accountTypeAndDataSet = c.getString( LookupByRawContactIdQuery.ACCOUNT_TYPE_AND_DATA_SET); String accountName = c.getString(LookupByRawContactIdQuery.ACCOUNT_NAME); int accountHashCode = ContactLookupKey.getAccountHashCode(accountTypeAndDataSet, accountName); String rawContactId = c.getString(LookupByRawContactIdQuery.ID); for (int i = 0; i < segments.size(); i++) { LookupKeySegment segment = segments.get(i); if (segment.lookupType == ContactLookupKey.LOOKUP_TYPE_RAW_CONTACT_ID && accountHashCode == segment.accountHashCode && segment.rawContactId.equals(rawContactId)) { segment.contactId = c.getLong(LookupByRawContactIdQuery.CONTACT_ID); break; } } } } finally { c.close(); } return getMostReferencedContactId(segments); } private interface LookupByDisplayNameQuery { String TABLE = Tables.NAME_LOOKUP_JOIN_RAW_CONTACTS; String COLUMNS[] = { RawContacts.CONTACT_ID, RawContacts.ACCOUNT_TYPE_AND_DATA_SET, RawContacts.ACCOUNT_NAME, NameLookupColumns.NORMALIZED_NAME }; int CONTACT_ID = 0; int ACCOUNT_TYPE_AND_DATA_SET = 1; int ACCOUNT_NAME = 2; int NORMALIZED_NAME = 3; } private long lookupContactIdByDisplayNames(SQLiteDatabase db, ArrayList<LookupKeySegment> segments) { StringBuilder sb = new StringBuilder(); sb.append(NameLookupColumns.NORMALIZED_NAME + " IN ("); for (int i = 0; i < segments.size(); i++) { LookupKeySegment segment = segments.get(i); if (segment.lookupType == ContactLookupKey.LOOKUP_TYPE_DISPLAY_NAME || segment.lookupType == ContactLookupKey.LOOKUP_TYPE_RAW_CONTACT_ID) { DatabaseUtils.appendEscapedSQLString(sb, segment.key); sb.append(","); } } sb.setLength(sb.length() - 1); // Last comma sb.append(") AND " + NameLookupColumns.NAME_TYPE + "=" + NameLookupType.NAME_COLLATION_KEY + " AND " + RawContacts.CONTACT_ID + " NOT NULL"); Cursor c = db.query(LookupByDisplayNameQuery.TABLE, LookupByDisplayNameQuery.COLUMNS, sb.toString(), null, null, null, null); try { while (c.moveToNext()) { String accountTypeAndDataSet = c.getString(LookupByDisplayNameQuery.ACCOUNT_TYPE_AND_DATA_SET); String accountName = c.getString(LookupByDisplayNameQuery.ACCOUNT_NAME); int accountHashCode = ContactLookupKey.getAccountHashCode(accountTypeAndDataSet, accountName); String name = c.getString(LookupByDisplayNameQuery.NORMALIZED_NAME); for (int i = 0; i < segments.size(); i++) { LookupKeySegment segment = segments.get(i); if ((segment.lookupType == ContactLookupKey.LOOKUP_TYPE_DISPLAY_NAME || segment.lookupType == ContactLookupKey.LOOKUP_TYPE_RAW_CONTACT_ID) && accountHashCode == segment.accountHashCode && segment.key.equals(name)) { segment.contactId = c.getLong(LookupByDisplayNameQuery.CONTACT_ID); break; } } } } finally { c.close(); } return getMostReferencedContactId(segments); } private boolean lookupKeyContainsType(ArrayList<LookupKeySegment> segments, int lookupType) { for (int i = 0; i < segments.size(); i++) { LookupKeySegment segment = segments.get(i); if (segment.lookupType == lookupType) { return true; } } return false; } public void updateLookupKeyForRawContact(SQLiteDatabase db, long rawContactId) { mContactAggregator.updateLookupKeyForRawContact(db, rawContactId); } /** * Returns the contact ID that is mentioned the highest number of times. */ private long getMostReferencedContactId(ArrayList<LookupKeySegment> segments) { Collections.sort(segments); long bestContactId = -1; int bestRefCount = 0; long contactId = -1; int count = 0; int segmentCount = segments.size(); for (int i = 0; i < segmentCount; i++) { LookupKeySegment segment = segments.get(i); if (segment.contactId != -1) { if (segment.contactId == contactId) { count++; } else { if (count > bestRefCount) { bestContactId = contactId; bestRefCount = count; } contactId = segment.contactId; count = 1; } } } if (count > bestRefCount) { return contactId; } else { return bestContactId; } } private void setTablesAndProjectionMapForContacts(SQLiteQueryBuilder qb, Uri uri, String[] projection) { setTablesAndProjectionMapForContacts(qb, uri, projection, false); } /** * @param includeDataUsageStat true when the table should include DataUsageStat table. * Note that this uses INNER JOIN instead of LEFT OUTER JOIN, so some of data in Contacts * may be dropped. */ private void setTablesAndProjectionMapForContacts(SQLiteQueryBuilder qb, Uri uri, String[] projection, boolean includeDataUsageStat) { StringBuilder sb = new StringBuilder(); sb.append(Views.CONTACTS); // Just for frequently contacted contacts in Strequent Uri handling. if (includeDataUsageStat) { sb.append(" INNER JOIN " + Views.DATA_USAGE_STAT + " AS " + Tables.DATA_USAGE_STAT + " ON (" + DbQueryUtils.concatenateClauses( DataUsageStatColumns.CONCRETE_TIMES_USED + " > 0", RawContacts.CONTACT_ID + "=" + Views.CONTACTS + "." + Contacts._ID) + ")"); } appendContactPresenceJoin(sb, projection, Contacts._ID); appendContactStatusUpdateJoin(sb, projection, ContactsColumns.LAST_STATUS_UPDATE_ID); qb.setTables(sb.toString()); qb.setProjectionMap(sContactsProjectionMap); } /** * Finds name lookup records matching the supplied filter, picks one arbitrary match per * contact and joins that with other contacts tables. */ private void setTablesAndProjectionMapForContactsWithSnippet(SQLiteQueryBuilder qb, Uri uri, String[] projection, String filter, long directoryId) { StringBuilder sb = new StringBuilder(); sb.append(Views.CONTACTS); if (filter != null) { filter = filter.trim(); } if (TextUtils.isEmpty(filter) || (directoryId != -1 && directoryId != Directory.DEFAULT)) { sb.append(" JOIN (SELECT NULL AS " + SearchSnippetColumns.SNIPPET + " WHERE 0)"); } else { appendSearchIndexJoin(sb, uri, projection, filter); } appendContactPresenceJoin(sb, projection, Contacts._ID); appendContactStatusUpdateJoin(sb, projection, ContactsColumns.LAST_STATUS_UPDATE_ID); qb.setTables(sb.toString()); qb.setProjectionMap(sContactsProjectionWithSnippetMap); } private void appendSearchIndexJoin( StringBuilder sb, Uri uri, String[] projection, String filter) { if (mDbHelper.isInProjection(projection, SearchSnippetColumns.SNIPPET)) { String[] args = null; String snippetArgs = getQueryParameter(uri, SearchSnippetColumns.SNIPPET_ARGS_PARAM_KEY); if (snippetArgs != null) { args = snippetArgs.split(","); } String startMatch = args != null && args.length > 0 ? args[0] : DEFAULT_SNIPPET_ARG_START_MATCH; String endMatch = args != null && args.length > 1 ? args[1] : DEFAULT_SNIPPET_ARG_END_MATCH; String ellipsis = args != null && args.length > 2 ? args[2] : DEFAULT_SNIPPET_ARG_ELLIPSIS; int maxTokens = args != null && args.length > 3 ? Integer.parseInt(args[3]) : DEFAULT_SNIPPET_ARG_MAX_TOKENS; appendSearchIndexJoin( sb, filter, true, startMatch, endMatch, ellipsis, maxTokens); } else { appendSearchIndexJoin(sb, filter, false, null, null, null, 0); } } public void appendSearchIndexJoin(StringBuilder sb, String filter, boolean snippetNeeded, String startMatch, String endMatch, String ellipsis, int maxTokens) { boolean isEmailAddress = false; String emailAddress = null; boolean isPhoneNumber = false; String phoneNumber = null; String numberE164 = null; // If the query consists of a single word, we can do snippetizing after-the-fact for a // performance boost. boolean singleTokenSearch = filter.split(QUERY_TOKENIZER_REGEX).length == 1; if (filter.indexOf('@') != -1) { emailAddress = mDbHelper.extractAddressFromEmailAddress(filter); isEmailAddress = !TextUtils.isEmpty(emailAddress); } else { isPhoneNumber = isPhoneNumber(filter); if (isPhoneNumber) { phoneNumber = PhoneNumberUtils.normalizeNumber(filter); numberE164 = PhoneNumberUtils.formatNumberToE164(phoneNumber, mDbHelper.getCountryIso()); } } sb.append(" JOIN (SELECT " + SearchIndexColumns.CONTACT_ID + " AS snippet_contact_id"); if (snippetNeeded) { sb.append(", "); if (isEmailAddress) { sb.append("ifnull("); DatabaseUtils.appendEscapedSQLString(sb, startMatch); sb.append("||(SELECT MIN(" + Email.ADDRESS + ")"); sb.append(" FROM " + Tables.DATA_JOIN_RAW_CONTACTS); sb.append(" WHERE " + Tables.SEARCH_INDEX + "." + SearchIndexColumns.CONTACT_ID); sb.append("=" + RawContacts.CONTACT_ID + " AND " + Email.ADDRESS + " LIKE "); DatabaseUtils.appendEscapedSQLString(sb, filter + "%"); sb.append(")||"); DatabaseUtils.appendEscapedSQLString(sb, endMatch); sb.append(","); // Optimization for single-token search. if (singleTokenSearch) { sb.append(SearchIndexColumns.CONTENT); } else { appendSnippetFunction(sb, startMatch, endMatch, ellipsis, maxTokens); } sb.append(")"); } else if (isPhoneNumber) { sb.append("ifnull("); DatabaseUtils.appendEscapedSQLString(sb, startMatch); sb.append("||(SELECT MIN(" + Phone.NUMBER + ")"); sb.append(" FROM " + Tables.DATA_JOIN_RAW_CONTACTS + " JOIN " + Tables.PHONE_LOOKUP); sb.append(" ON " + DataColumns.CONCRETE_ID); sb.append("=" + Tables.PHONE_LOOKUP + "." + PhoneLookupColumns.DATA_ID); sb.append(" WHERE " + Tables.SEARCH_INDEX + "." + SearchIndexColumns.CONTACT_ID); sb.append("=" + RawContacts.CONTACT_ID); sb.append(" AND " + PhoneLookupColumns.NORMALIZED_NUMBER + " LIKE '"); sb.append(phoneNumber); sb.append("%'"); if (!TextUtils.isEmpty(numberE164)) { sb.append(" OR " + PhoneLookupColumns.NORMALIZED_NUMBER + " LIKE '"); sb.append(numberE164); sb.append("%'"); } sb.append(")||"); DatabaseUtils.appendEscapedSQLString(sb, endMatch); sb.append(","); // Optimization for single-token search. if (singleTokenSearch) { sb.append(SearchIndexColumns.CONTENT); } else { appendSnippetFunction(sb, startMatch, endMatch, ellipsis, maxTokens); } sb.append(")"); } else { final String normalizedFilter = NameNormalizer.normalize(filter); if (!TextUtils.isEmpty(normalizedFilter)) { // Optimization for single-token search. if (singleTokenSearch) { sb.append(SearchIndexColumns.CONTENT); } else { sb.append("(CASE WHEN EXISTS (SELECT 1 FROM "); sb.append(Tables.RAW_CONTACTS + " AS rc INNER JOIN "); sb.append(Tables.NAME_LOOKUP + " AS nl ON (rc." + RawContacts._ID); sb.append("=nl." + NameLookupColumns.RAW_CONTACT_ID); sb.append(") WHERE nl." + NameLookupColumns.NORMALIZED_NAME); sb.append(" GLOB '" + normalizedFilter + "*' AND "); sb.append("nl." + NameLookupColumns.NAME_TYPE + "="); sb.append(NameLookupType.NAME_COLLATION_KEY + " AND "); sb.append(Tables.SEARCH_INDEX + "." + SearchIndexColumns.CONTACT_ID); sb.append("=rc." + RawContacts.CONTACT_ID); sb.append(") THEN NULL ELSE "); appendSnippetFunction(sb, startMatch, endMatch, ellipsis, maxTokens); sb.append(" END)"); } } else { sb.append("NULL"); } } sb.append(" AS " + SearchSnippetColumns.SNIPPET); } sb.append(" FROM " + Tables.SEARCH_INDEX); sb.append(" WHERE "); sb.append(Tables.SEARCH_INDEX + " MATCH "); if (isEmailAddress) { DatabaseUtils.appendEscapedSQLString(sb, "\"" + sanitizeMatch(filter) + "*\""); } else if (isPhoneNumber) { DatabaseUtils.appendEscapedSQLString(sb, "\"" + sanitizeMatch(filter) + "*\" OR \"" + phoneNumber + "*\"" + (numberE164 != null ? " OR \"" + numberE164 + "\"" : "")); } else { DatabaseUtils.appendEscapedSQLString(sb, sanitizeMatch(filter) + "*"); } sb.append(") ON (" + Contacts._ID + "=snippet_contact_id)"); } private String sanitizeMatch(String filter) { // TODO more robust preprocessing of match expressions return filter.replace('-', ' ').replace('\"', ' '); } private void appendSnippetFunction( StringBuilder sb, String startMatch, String endMatch, String ellipsis, int maxTokens) { sb.append("snippet(" + Tables.SEARCH_INDEX + ","); DatabaseUtils.appendEscapedSQLString(sb, startMatch); sb.append(","); DatabaseUtils.appendEscapedSQLString(sb, endMatch); sb.append(","); DatabaseUtils.appendEscapedSQLString(sb, ellipsis); // The index of the column used for the snippet, "content" sb.append(",1,"); sb.append(maxTokens); sb.append(")"); } private void setTablesAndProjectionMapForRawContacts(SQLiteQueryBuilder qb, Uri uri) { StringBuilder sb = new StringBuilder(); sb.append(Views.RAW_CONTACTS); qb.setTables(sb.toString()); qb.setProjectionMap(sRawContactsProjectionMap); appendAccountFromParameter(qb, uri, true); } private void setTablesAndProjectionMapForRawEntities(SQLiteQueryBuilder qb, Uri uri) { qb.setTables(Views.RAW_ENTITIES); qb.setProjectionMap(sRawEntityProjectionMap); appendAccountFromParameter(qb, uri, true); } private void setTablesAndProjectionMapForData(SQLiteQueryBuilder qb, Uri uri, String[] projection, boolean distinct) { setTablesAndProjectionMapForData(qb, uri, projection, distinct, null); } /** * @param usageType when non-null {@link Tables#DATA_USAGE_STAT} is joined with the specified * type. */ private void setTablesAndProjectionMapForData(SQLiteQueryBuilder qb, Uri uri, String[] projection, boolean distinct, Integer usageType) { StringBuilder sb = new StringBuilder(); sb.append(Views.DATA); sb.append(" data"); appendContactPresenceJoin(sb, projection, RawContacts.CONTACT_ID); appendContactStatusUpdateJoin(sb, projection, ContactsColumns.LAST_STATUS_UPDATE_ID); appendDataPresenceJoin(sb, projection, DataColumns.CONCRETE_ID); appendDataStatusUpdateJoin(sb, projection, DataColumns.CONCRETE_ID); if (usageType != null) { appendDataUsageStatJoin(sb, usageType, DataColumns.CONCRETE_ID); } qb.setTables(sb.toString()); boolean useDistinct = distinct || !mDbHelper.isInProjection(projection, DISTINCT_DATA_PROHIBITING_COLUMNS); qb.setDistinct(useDistinct); qb.setProjectionMap(useDistinct ? sDistinctDataProjectionMap : sDataProjectionMap); appendAccountFromParameter(qb, uri, true); } private void setTableAndProjectionMapForStatusUpdates(SQLiteQueryBuilder qb, String[] projection) { StringBuilder sb = new StringBuilder(); sb.append(Views.DATA); sb.append(" data"); appendDataPresenceJoin(sb, projection, DataColumns.CONCRETE_ID); appendDataStatusUpdateJoin(sb, projection, DataColumns.CONCRETE_ID); qb.setTables(sb.toString()); qb.setProjectionMap(sStatusUpdatesProjectionMap); } private void setTablesAndProjectionMapForStreamItems(SQLiteQueryBuilder qb) { qb.setTables(Tables.STREAM_ITEMS + " JOIN " + Tables.RAW_CONTACTS + " ON (" + StreamItemsColumns.CONCRETE_RAW_CONTACT_ID + "=" + RawContactsColumns.CONCRETE_ID + ") JOIN " + Tables.CONTACTS + " ON (" + RawContactsColumns.CONCRETE_CONTACT_ID + "=" + ContactsColumns.CONCRETE_ID + ")"); qb.setProjectionMap(sStreamItemsProjectionMap); } private void setTablesAndProjectionMapForStreamItemPhotos(SQLiteQueryBuilder qb) { qb.setTables(Tables.PHOTO_FILES + " JOIN " + Tables.STREAM_ITEM_PHOTOS + " ON (" + StreamItemPhotosColumns.CONCRETE_PHOTO_FILE_ID + "=" + PhotoFilesColumns.CONCRETE_ID + ") JOIN " + Tables.STREAM_ITEMS + " ON (" + StreamItemPhotosColumns.CONCRETE_STREAM_ITEM_ID + "=" + StreamItemsColumns.CONCRETE_ID + ")"); qb.setProjectionMap(sStreamItemPhotosProjectionMap); } private void setTablesAndProjectionMapForEntities(SQLiteQueryBuilder qb, Uri uri, String[] projection) { StringBuilder sb = new StringBuilder(); sb.append(Views.ENTITIES); sb.append(" data"); appendContactPresenceJoin(sb, projection, Contacts.Entity.CONTACT_ID); appendContactStatusUpdateJoin(sb, projection, ContactsColumns.LAST_STATUS_UPDATE_ID); appendDataPresenceJoin(sb, projection, Contacts.Entity.DATA_ID); appendDataStatusUpdateJoin(sb, projection, Contacts.Entity.DATA_ID); qb.setTables(sb.toString()); qb.setProjectionMap(sEntityProjectionMap); appendAccountFromParameter(qb, uri, true); } private void appendContactStatusUpdateJoin(StringBuilder sb, String[] projection, String lastStatusUpdateIdColumn) { if (mDbHelper.isInProjection(projection, Contacts.CONTACT_STATUS, Contacts.CONTACT_STATUS_RES_PACKAGE, Contacts.CONTACT_STATUS_ICON, Contacts.CONTACT_STATUS_LABEL, Contacts.CONTACT_STATUS_TIMESTAMP)) { sb.append(" LEFT OUTER JOIN " + Tables.STATUS_UPDATES + " " + ContactsStatusUpdatesColumns.ALIAS + " ON (" + lastStatusUpdateIdColumn + "=" + ContactsStatusUpdatesColumns.CONCRETE_DATA_ID + ")"); } } private void appendDataStatusUpdateJoin(StringBuilder sb, String[] projection, String dataIdColumn) { if (mDbHelper.isInProjection(projection, StatusUpdates.STATUS, StatusUpdates.STATUS_RES_PACKAGE, StatusUpdates.STATUS_ICON, StatusUpdates.STATUS_LABEL, StatusUpdates.STATUS_TIMESTAMP)) { sb.append(" LEFT OUTER JOIN " + Tables.STATUS_UPDATES + " ON (" + StatusUpdatesColumns.CONCRETE_DATA_ID + "=" + dataIdColumn + ")"); } } private void appendDataUsageStatJoin(StringBuilder sb, int usageType, String dataIdColumn) { sb.append(" LEFT OUTER JOIN " + Tables.DATA_USAGE_STAT + " ON (" + DataUsageStatColumns.CONCRETE_DATA_ID + "=" + dataIdColumn + " AND " + DataUsageStatColumns.CONCRETE_USAGE_TYPE + "=" + usageType + ")"); } private void appendContactPresenceJoin(StringBuilder sb, String[] projection, String contactIdColumn) { if (mDbHelper.isInProjection(projection, Contacts.CONTACT_PRESENCE, Contacts.CONTACT_CHAT_CAPABILITY)) { sb.append(" LEFT OUTER JOIN " + Tables.AGGREGATED_PRESENCE + " ON (" + contactIdColumn + " = " + AggregatedPresenceColumns.CONCRETE_CONTACT_ID + ")"); } } private void appendDataPresenceJoin(StringBuilder sb, String[] projection, String dataIdColumn) { if (mDbHelper.isInProjection(projection, Data.PRESENCE, Data.CHAT_CAPABILITY)) { sb.append(" LEFT OUTER JOIN " + Tables.PRESENCE + " ON (" + StatusUpdates.DATA_ID + "=" + dataIdColumn + ")"); } } private boolean appendLocalDirectorySelectionIfNeeded(SQLiteQueryBuilder qb, long directoryId) { if (directoryId == Directory.DEFAULT) { qb.appendWhere(Contacts._ID + " IN " + Tables.DEFAULT_DIRECTORY); return true; } else if (directoryId == Directory.LOCAL_INVISIBLE){ qb.appendWhere(Contacts._ID + " NOT IN " + Tables.DEFAULT_DIRECTORY); return true; } return false; } private String appendProfileRestriction(Uri uri, String profileColumn, boolean suppressProfileCheck, String originalSelection) { if (shouldIncludeProfile(uri, suppressProfileCheck)) { return originalSelection; } else { final String SELECTION = "(" + profileColumn + " IS NULL OR " + profileColumn + "=0)"; if (TextUtils.isEmpty(originalSelection)) { return SELECTION; } else { StringBuilder sb = new StringBuilder(); sb.append("("); sb.append(originalSelection); sb.append(") AND "); sb.append(SELECTION); return sb.toString(); } } } private String prependProfileSortIfNeeded(Uri uri, String sortOrder, boolean suppressProfileCheck) { if (shouldIncludeProfile(uri, suppressProfileCheck)) { if (TextUtils.isEmpty(sortOrder)) { return Contacts.IS_USER_PROFILE + " DESC"; } else { return Contacts.IS_USER_PROFILE + " DESC, " + sortOrder; } } return sortOrder; } private boolean shouldIncludeProfile(Uri uri, boolean suppressProfileCheck) { // The user's profile may be returned alongside other contacts if it was requested and // the calling application has permission to read profile data. boolean profileRequested = readBooleanQueryParameter(uri, ContactsContract.ALLOW_PROFILE, false); if (profileRequested && !suppressProfileCheck) { enforceProfilePermission(false); } return profileRequested; } private void appendAccountFromParameter(SQLiteQueryBuilder qb, Uri uri, boolean includeDataSet) { final String accountName = getQueryParameter(uri, RawContacts.ACCOUNT_NAME); final String accountType = getQueryParameter(uri, RawContacts.ACCOUNT_TYPE); final String dataSet = getQueryParameter(uri, RawContacts.DATA_SET); final boolean partialUri = TextUtils.isEmpty(accountName) ^ TextUtils.isEmpty(accountType); if (partialUri) { // Throw when either account is incomplete throw new IllegalArgumentException(mDbHelper.exceptionMessage( "Must specify both or neither of ACCOUNT_NAME and ACCOUNT_TYPE", uri)); } // Accounts are valid by only checking one parameter, since we've // already ruled out partial accounts. final boolean validAccount = !TextUtils.isEmpty(accountName); if (validAccount) { String toAppend = RawContacts.ACCOUNT_NAME + "=" + DatabaseUtils.sqlEscapeString(accountName) + " AND " + RawContacts.ACCOUNT_TYPE + "=" + DatabaseUtils.sqlEscapeString(accountType); if (includeDataSet) { if (dataSet == null) { toAppend += " AND " + RawContacts.DATA_SET + " IS NULL"; } else { toAppend += " AND " + RawContacts.DATA_SET + "=" + DatabaseUtils.sqlEscapeString(dataSet); } } qb.appendWhere(toAppend); } else { qb.appendWhere("1"); } } private String appendAccountToSelection(Uri uri, String selection) { final String accountName = getQueryParameter(uri, RawContacts.ACCOUNT_NAME); final String accountType = getQueryParameter(uri, RawContacts.ACCOUNT_TYPE); final String dataSet = getQueryParameter(uri, RawContacts.DATA_SET); final boolean partialUri = TextUtils.isEmpty(accountName) ^ TextUtils.isEmpty(accountType); if (partialUri) { // Throw when either account is incomplete throw new IllegalArgumentException(mDbHelper.exceptionMessage( "Must specify both or neither of ACCOUNT_NAME and ACCOUNT_TYPE", uri)); } // Accounts are valid by only checking one parameter, since we've // already ruled out partial accounts. final boolean validAccount = !TextUtils.isEmpty(accountName); if (validAccount) { StringBuilder selectionSb = new StringBuilder(RawContacts.ACCOUNT_NAME + "=" + DatabaseUtils.sqlEscapeString(accountName) + " AND " + RawContacts.ACCOUNT_TYPE + "=" + DatabaseUtils.sqlEscapeString(accountType)); if (!TextUtils.isEmpty(dataSet)) { selectionSb.append(" AND " + RawContacts.DATA_SET + "=") .append(DatabaseUtils.sqlEscapeString(dataSet)); } if (!TextUtils.isEmpty(selection)) { selectionSb.append(" AND ("); selectionSb.append(selection); selectionSb.append(')'); } return selectionSb.toString(); } else { return selection; } } /** * Gets the value of the "limit" URI query parameter. * * @return A string containing a non-negative integer, or <code>null</code> if * the parameter is not set, or is set to an invalid value. */ private String getLimit(Uri uri) { String limitParam = getQueryParameter(uri, ContactsContract.LIMIT_PARAM_KEY); if (limitParam == null) { return null; } // make sure that the limit is a non-negative integer try { int l = Integer.parseInt(limitParam); if (l < 0) { Log.w(TAG, "Invalid limit parameter: " + limitParam); return null; } return String.valueOf(l); } catch (NumberFormatException ex) { Log.w(TAG, "Invalid limit parameter: " + limitParam); return null; } } @Override public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException { if (mode.equals("r")) { waitForAccess(mReadAccessLatch); } else { waitForAccess(mWriteAccessLatch); } int match = sUriMatcher.match(uri); switch (match) { case CONTACTS_ID_PHOTO: { SQLiteDatabase db = mDbHelper.getReadableDatabase(); long rawContactId = Long.parseLong(uri.getPathSegments().get(1)); enforceProfilePermissionForRawContact(db, rawContactId, false); return openPhotoAssetFile(db, uri, mode, Data._ID + "=" + Contacts.PHOTO_ID + " AND " + RawContacts.CONTACT_ID + "=?", new String[]{String.valueOf(rawContactId)}); } case CONTACTS_ID_DISPLAY_PHOTO: { if (!mode.equals("r")) { throw new IllegalArgumentException( "Display photos retrieved by contact ID can only be read."); } SQLiteDatabase db = mDbHelper.getReadableDatabase(); long contactId = Long.parseLong(uri.getPathSegments().get(1)); enforceProfilePermissionForContact(db, contactId, false); Cursor c = db.query(Tables.CONTACTS, new String[]{Contacts.PHOTO_FILE_ID}, Contacts._ID + "=?", new String[]{String.valueOf(contactId)}, null, null, null); try { c.moveToFirst(); long photoFileId = c.getLong(0); return openDisplayPhotoForRead(photoFileId); } finally { c.close(); } } case CONTACTS_LOOKUP_DISPLAY_PHOTO: case CONTACTS_LOOKUP_ID_DISPLAY_PHOTO: { if (!mode.equals("r")) { throw new IllegalArgumentException( "Display photos retrieved by contact lookup key can only be read."); } List<String> pathSegments = uri.getPathSegments(); int segmentCount = pathSegments.size(); if (segmentCount < 4) { throw new IllegalArgumentException(mDbHelper.exceptionMessage( "Missing a lookup key", uri)); } SQLiteDatabase db = mDbHelper.getReadableDatabase(); String lookupKey = pathSegments.get(2); String[] projection = new String[]{Contacts.PHOTO_FILE_ID}; if (segmentCount == 5) { long contactId = Long.parseLong(pathSegments.get(3)); enforceProfilePermissionForContact(db, contactId, false); SQLiteQueryBuilder lookupQb = new SQLiteQueryBuilder(); setTablesAndProjectionMapForContacts(lookupQb, uri, projection); Cursor c = queryWithContactIdAndLookupKey(lookupQb, db, uri, projection, null, null, null, null, null, Contacts._ID, contactId, Contacts.LOOKUP_KEY, lookupKey); if (c != null) { try { c.moveToFirst(); long photoFileId = c.getLong(c.getColumnIndex(Contacts.PHOTO_FILE_ID)); return openDisplayPhotoForRead(photoFileId); } finally { c.close(); } } } SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); setTablesAndProjectionMapForContacts(qb, uri, projection); long contactId = lookupContactIdByLookupKey(db, lookupKey); enforceProfilePermissionForContact(db, contactId, false); Cursor c = qb.query(db, projection, Contacts._ID + "=?", new String[]{String.valueOf(contactId)}, null, null, null); try { c.moveToFirst(); long photoFileId = c.getLong(c.getColumnIndex(Contacts.PHOTO_FILE_ID)); return openDisplayPhotoForRead(photoFileId); } finally { c.close(); } } case RAW_CONTACTS_ID_DISPLAY_PHOTO: { long rawContactId = Long.parseLong(uri.getPathSegments().get(1)); boolean writeable = !mode.equals("r"); SQLiteDatabase db = mDbHelper.getReadableDatabase(); enforceProfilePermissionForRawContact(db, rawContactId, writeable); // Find the primary photo data record for this raw contact. SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); String[] projection = new String[]{Data._ID, Photo.PHOTO_FILE_ID}; setTablesAndProjectionMapForData(qb, uri, projection, false); Cursor c = qb.query(db, projection, Data.RAW_CONTACT_ID + "=? AND " + Data.MIMETYPE + "=?", new String[]{String.valueOf(rawContactId), Photo.CONTENT_ITEM_TYPE}, null, null, Data.IS_PRIMARY + " DESC"); long dataId = 0; long photoFileId = 0; try { if (c.getCount() >= 1) { c.moveToFirst(); dataId = c.getLong(0); photoFileId = c.getLong(1); } } finally { c.close(); } // If writeable, open a writeable file descriptor that we can monitor. // When the caller finishes writing content, we'll process the photo and // update the data record. if (writeable) { return openDisplayPhotoForWrite(rawContactId, dataId, uri, mode); } else { return openDisplayPhotoForRead(photoFileId); } } case DISPLAY_PHOTO: { long photoFileId = ContentUris.parseId(uri); if (!mode.equals("r")) { throw new IllegalArgumentException( "Display photos retrieved by key can only be read."); } return openDisplayPhotoForRead(photoFileId); } case DATA_ID: { SQLiteDatabase db = mDbHelper.getReadableDatabase(); long dataId = Long.parseLong(uri.getPathSegments().get(1)); enforceProfilePermissionForData(db, dataId, false); return openPhotoAssetFile(db, uri, mode, Data._ID + "=? AND " + Data.MIMETYPE + "='" + Photo.CONTENT_ITEM_TYPE + "'", new String[]{String.valueOf(dataId)}); } case PROFILE_AS_VCARD: { // When opening a contact as file, we pass back contents as a // vCard-encoded stream. We build into a local buffer first, // then pipe into MemoryFile once the exact size is known. final ByteArrayOutputStream localStream = new ByteArrayOutputStream(); outputRawContactsAsVCard(uri, localStream, null, null); return buildAssetFileDescriptor(localStream); } case CONTACTS_AS_VCARD: { // When opening a contact as file, we pass back contents as a // vCard-encoded stream. We build into a local buffer first, // then pipe into MemoryFile once the exact size is known. final ByteArrayOutputStream localStream = new ByteArrayOutputStream(); outputRawContactsAsVCard(uri, localStream, null, null); return buildAssetFileDescriptor(localStream); } case CONTACTS_AS_MULTI_VCARD: { SQLiteDatabase db = mDbHelper.getReadableDatabase(); final String lookupKeys = uri.getPathSegments().get(2); final String[] loopupKeyList = lookupKeys.split(":"); final StringBuilder inBuilder = new StringBuilder(); Uri queryUri = Contacts.CONTENT_URI; int index = 0; // SQLite has limits on how many parameters can be used // so the IDs are concatenated to a query string here instead for (String lookupKey : loopupKeyList) { if (index == 0) { inBuilder.append("("); } else { inBuilder.append(","); } long contactId = lookupContactIdByLookupKey(db, lookupKey); enforceProfilePermissionForContact(db, contactId, false); inBuilder.append(contactId); if (mProfileIdCache.profileContactId == contactId) { queryUri = queryUri.buildUpon().appendQueryParameter( ContactsContract.ALLOW_PROFILE, "true").build(); } index++; } inBuilder.append(')'); final String selection = Contacts._ID + " IN " + inBuilder.toString(); // When opening a contact as file, we pass back contents as a // vCard-encoded stream. We build into a local buffer first, // then pipe into MemoryFile once the exact size is known. final ByteArrayOutputStream localStream = new ByteArrayOutputStream(); outputRawContactsAsVCard(queryUri, localStream, selection, null); return buildAssetFileDescriptor(localStream); } default: throw new FileNotFoundException(mDbHelper.exceptionMessage("File does not exist", uri)); } } private AssetFileDescriptor openPhotoAssetFile(SQLiteDatabase db, Uri uri, String mode, String selection, String[] selectionArgs) throws FileNotFoundException { if (!"r".equals(mode)) { throw new FileNotFoundException(mDbHelper.exceptionMessage("Mode " + mode + " not supported.", uri)); } String sql = "SELECT " + Photo.PHOTO + " FROM " + Views.DATA + " WHERE " + selection; try { return makeAssetFileDescriptor( DatabaseUtils.blobFileDescriptorForQuery(db, sql, selectionArgs)); } catch (SQLiteDoneException e) { // this will happen if the DB query returns no rows (i.e. contact does not exist) throw new FileNotFoundException(uri.toString()); } } /** * Opens a display photo from the photo store for reading. * @param photoFileId The display photo file ID * @return An asset file descriptor that allows the file to be read. * @throws FileNotFoundException If no photo file for the given ID exists. */ private AssetFileDescriptor openDisplayPhotoForRead(long photoFileId) throws FileNotFoundException { PhotoStore.Entry entry = mPhotoStore.get(photoFileId); if (entry != null) { return makeAssetFileDescriptor( ParcelFileDescriptor.open(new File(entry.path), ParcelFileDescriptor.MODE_READ_ONLY), entry.size); } else { scheduleBackgroundTask(BACKGROUND_TASK_CLEANUP_PHOTOS); throw new FileNotFoundException("No photo file found for ID " + photoFileId); } } /** * Opens a file descriptor for a photo to be written. When the caller completes writing * to the file (closing the output stream), the image will be parsed out and processed. * If processing succeeds, the given raw contact ID's primary photo record will be * populated with the inserted image (if no primary photo record exists, the data ID can * be left as 0, and a new data record will be inserted). * @param rawContactId Raw contact ID this photo entry should be associated with. * @param dataId Data ID for a photo mimetype that will be updated with the inserted * image. May be set to 0, in which case the inserted image will trigger creation * of a new primary photo image data row for the raw contact. * @param uri The URI being used to access this file. * @param mode Read/write mode string. * @return An asset file descriptor the caller can use to write an image file for the * raw contact. */ private AssetFileDescriptor openDisplayPhotoForWrite(long rawContactId, long dataId, Uri uri, String mode) { try { return new AssetFileDescriptor(new MonitoredParcelFileDescriptor(rawContactId, dataId, ParcelFileDescriptor.open(File.createTempFile("img", null), ContentResolver.modeToMode(uri, mode))), 0, AssetFileDescriptor.UNKNOWN_LENGTH); } catch (IOException ioe) { Log.e(TAG, "Could not create temp image file in mode " + mode); return null; } } /** * Parcel file descriptor wrapper that monitors when the file is closed. * If the file contains a valid image, the image is either inserted into the given * raw contact or updated in the given data row. */ private class MonitoredParcelFileDescriptor extends ParcelFileDescriptor { private final long mRawContactId; private final long mDataId; private MonitoredParcelFileDescriptor(long rawContactId, long dataId, ParcelFileDescriptor descriptor) { super(descriptor); mRawContactId = rawContactId; mDataId = dataId; } @Override public void close() throws IOException { try { // Check to see whether a valid image was written out. Bitmap b = BitmapFactory.decodeFileDescriptor(getFileDescriptor()); if (b != null) { PhotoProcessor processor = new PhotoProcessor(b, mMaxDisplayPhotoDim, mMaxThumbnailPhotoDim); // Store the compressed photo in the photo store. long photoFileId = mPhotoStore.insert(processor); // Depending on whether we already had a data row to attach the photo to, // do an update or insert. if (mDataId != 0) { // Update the data record with the new photo. ContentValues updateValues = new ContentValues(); // Signal that photo processing has already been handled. updateValues.put(DataRowHandlerForPhoto.SKIP_PROCESSING_KEY, true); if (photoFileId != 0) { updateValues.put(Photo.PHOTO_FILE_ID, photoFileId); } updateValues.put(Photo.PHOTO, processor.getThumbnailPhotoBytes()); update(ContentUris.withAppendedId(Data.CONTENT_URI, mDataId), updateValues, null, null); } else { // Insert a new primary data record with the photo. ContentValues insertValues = new ContentValues(); // Signal that photo processing has already been handled. insertValues.put(DataRowHandlerForPhoto.SKIP_PROCESSING_KEY, true); insertValues.put(Data.MIMETYPE, Photo.CONTENT_ITEM_TYPE); insertValues.put(Data.IS_PRIMARY, 1); if (photoFileId != 0) { insertValues.put(Photo.PHOTO_FILE_ID, photoFileId); } insertValues.put(Photo.PHOTO, processor.getThumbnailPhotoBytes()); insert(RawContacts.CONTENT_URI.buildUpon() .appendPath(String.valueOf(mRawContactId)) .appendPath(RawContacts.Data.CONTENT_DIRECTORY).build(), insertValues); } } } finally { super.close(); } } } private static final String CONTACT_MEMORY_FILE_NAME = "contactAssetFile"; /** * Returns an {@link AssetFileDescriptor} backed by the * contents of the given {@link ByteArrayOutputStream}. */ private AssetFileDescriptor buildAssetFileDescriptor(ByteArrayOutputStream stream) { try { stream.flush(); final byte[] byteData = stream.toByteArray(); return makeAssetFileDescriptor( ParcelFileDescriptor.fromData(byteData, CONTACT_MEMORY_FILE_NAME), byteData.length); } catch (IOException e) { Log.w(TAG, "Problem writing stream into an ParcelFileDescriptor: " + e.toString()); return null; } } private AssetFileDescriptor makeAssetFileDescriptor(ParcelFileDescriptor fd) { return makeAssetFileDescriptor(fd, AssetFileDescriptor.UNKNOWN_LENGTH); } private AssetFileDescriptor makeAssetFileDescriptor(ParcelFileDescriptor fd, long length) { return fd != null ? new AssetFileDescriptor(fd, 0, length) : null; } /** * Output {@link RawContacts} matching the requested selection in the vCard * format to the given {@link OutputStream}. This method returns silently if * any errors encountered. */ private void outputRawContactsAsVCard(Uri uri, OutputStream stream, String selection, String[] selectionArgs) { final Context context = this.getContext(); int vcardconfig = VCardConfig.VCARD_TYPE_DEFAULT; if(uri.getBooleanQueryParameter( Contacts.QUERY_PARAMETER_VCARD_NO_PHOTO, false)) { vcardconfig |= VCardConfig.FLAG_REFRAIN_IMAGE_EXPORT; } final VCardComposer composer = new VCardComposer(context, vcardconfig, false); Writer writer = null; try { writer = new BufferedWriter(new OutputStreamWriter(stream)); if (!composer.init(uri, selection, selectionArgs, null)) { Log.w(TAG, "Failed to init VCardComposer"); return; } while (!composer.isAfterLast()) { writer.write(composer.createOneEntry()); } } catch (IOException e) { Log.e(TAG, "IOException: " + e); } finally { composer.terminate(); if (writer != null) { try { writer.close(); } catch (IOException e) { Log.w(TAG, "IOException during closing output stream: " + e); } } } } @Override public String getType(Uri uri) { waitForAccess(mReadAccessLatch); final int match = sUriMatcher.match(uri); switch (match) { case CONTACTS: return Contacts.CONTENT_TYPE; case CONTACTS_LOOKUP: case CONTACTS_ID: case CONTACTS_LOOKUP_ID: case PROFILE: return Contacts.CONTENT_ITEM_TYPE; case CONTACTS_AS_VCARD: case CONTACTS_AS_MULTI_VCARD: case PROFILE_AS_VCARD: return Contacts.CONTENT_VCARD_TYPE; case CONTACTS_ID_PHOTO: case CONTACTS_ID_DISPLAY_PHOTO: case CONTACTS_LOOKUP_DISPLAY_PHOTO: case CONTACTS_LOOKUP_ID_DISPLAY_PHOTO: case RAW_CONTACTS_ID_DISPLAY_PHOTO: case DISPLAY_PHOTO: return "image/jpeg"; case RAW_CONTACTS: case PROFILE_RAW_CONTACTS: return RawContacts.CONTENT_TYPE; case RAW_CONTACTS_ID: case PROFILE_RAW_CONTACTS_ID: return RawContacts.CONTENT_ITEM_TYPE; case DATA: case PROFILE_DATA: return Data.CONTENT_TYPE; case DATA_ID: return mDbHelper.getDataMimeType(ContentUris.parseId(uri)); case PHONES: return Phone.CONTENT_TYPE; case PHONES_ID: return Phone.CONTENT_ITEM_TYPE; case PHONE_LOOKUP: return PhoneLookup.CONTENT_TYPE; case EMAILS: return Email.CONTENT_TYPE; case EMAILS_ID: return Email.CONTENT_ITEM_TYPE; case POSTALS: return StructuredPostal.CONTENT_TYPE; case POSTALS_ID: return StructuredPostal.CONTENT_ITEM_TYPE; case AGGREGATION_EXCEPTIONS: return AggregationExceptions.CONTENT_TYPE; case AGGREGATION_EXCEPTION_ID: return AggregationExceptions.CONTENT_ITEM_TYPE; case SETTINGS: return Settings.CONTENT_TYPE; case AGGREGATION_SUGGESTIONS: return Contacts.CONTENT_TYPE; case SEARCH_SUGGESTIONS: return SearchManager.SUGGEST_MIME_TYPE; case SEARCH_SHORTCUT: return SearchManager.SHORTCUT_MIME_TYPE; case DIRECTORIES: return Directory.CONTENT_TYPE; case DIRECTORIES_ID: return Directory.CONTENT_ITEM_TYPE; default: return mLegacyApiSupport.getType(uri); } } public String[] getDefaultProjection(Uri uri) { final int match = sUriMatcher.match(uri); switch (match) { case CONTACTS: case CONTACTS_LOOKUP: case CONTACTS_ID: case CONTACTS_LOOKUP_ID: case AGGREGATION_SUGGESTIONS: case PROFILE: return sContactsProjectionMap.getColumnNames(); case CONTACTS_ID_ENTITIES: case PROFILE_ENTITIES: return sEntityProjectionMap.getColumnNames(); case CONTACTS_AS_VCARD: case CONTACTS_AS_MULTI_VCARD: case PROFILE_AS_VCARD: return sContactsVCardProjectionMap.getColumnNames(); case RAW_CONTACTS: case RAW_CONTACTS_ID: case PROFILE_RAW_CONTACTS: case PROFILE_RAW_CONTACTS_ID: return sRawContactsProjectionMap.getColumnNames(); case DATA_ID: case PHONES: case PHONES_ID: case EMAILS: case EMAILS_ID: case POSTALS: case POSTALS_ID: case PROFILE_DATA: return sDataProjectionMap.getColumnNames(); case PHONE_LOOKUP: return sPhoneLookupProjectionMap.getColumnNames(); case AGGREGATION_EXCEPTIONS: case AGGREGATION_EXCEPTION_ID: return sAggregationExceptionsProjectionMap.getColumnNames(); case SETTINGS: return sSettingsProjectionMap.getColumnNames(); case DIRECTORIES: case DIRECTORIES_ID: return sDirectoryProjectionMap.getColumnNames(); default: return null; } } private class StructuredNameLookupBuilder extends NameLookupBuilder { public StructuredNameLookupBuilder(NameSplitter splitter) { super(splitter); } @Override protected void insertNameLookup(long rawContactId, long dataId, int lookupType, String name) { mDbHelper.insertNameLookup(rawContactId, dataId, lookupType, name); } @Override protected String[] getCommonNicknameClusters(String normalizedName) { return mCommonNicknameCache.getCommonNicknameClusters(normalizedName); } } public void appendContactFilterAsNestedQuery(StringBuilder sb, String filterParam) { sb.append("(" + "SELECT DISTINCT " + RawContacts.CONTACT_ID + " FROM " + Tables.RAW_CONTACTS + " JOIN " + Tables.NAME_LOOKUP + " ON(" + RawContactsColumns.CONCRETE_ID + "=" + NameLookupColumns.RAW_CONTACT_ID + ")" + " WHERE normalized_name GLOB '"); sb.append(NameNormalizer.normalize(filterParam)); sb.append("*' AND " + NameLookupColumns.NAME_TYPE + " IN(" + CONTACT_LOOKUP_NAME_TYPES + "))"); } public boolean isPhoneNumber(String filter) { boolean atLeastOneDigit = false; int len = filter.length(); for (int i = 0; i < len; i++) { char c = filter.charAt(i); if (c >= '0' && c <= '9') { atLeastOneDigit = true; } else if (c != '*' && c != '#' && c != '+' && c != 'N' && c != '.' && c != ';' && c != '-' && c != '(' && c != ')' && c != ' ') { return false; } } return atLeastOneDigit; } /** * Takes components of a name from the query parameters and returns a cursor with those * components as well as all missing components. There is no database activity involved * in this so the call can be made on the UI thread. */ private Cursor completeName(Uri uri, String[] projection) { if (projection == null) { projection = sDataProjectionMap.getColumnNames(); } ContentValues values = new ContentValues(); DataRowHandlerForStructuredName handler = (DataRowHandlerForStructuredName) getDataRowHandler(StructuredName.CONTENT_ITEM_TYPE); copyQueryParamsToContentValues(values, uri, StructuredName.DISPLAY_NAME, StructuredName.PREFIX, StructuredName.GIVEN_NAME, StructuredName.MIDDLE_NAME, StructuredName.FAMILY_NAME, StructuredName.SUFFIX, StructuredName.PHONETIC_NAME, StructuredName.PHONETIC_FAMILY_NAME, StructuredName.PHONETIC_MIDDLE_NAME, StructuredName.PHONETIC_GIVEN_NAME ); handler.fixStructuredNameComponents(values, values); MatrixCursor cursor = new MatrixCursor(projection); Object[] row = new Object[projection.length]; for (int i = 0; i < projection.length; i++) { row[i] = values.get(projection[i]); } cursor.addRow(row); return cursor; } private void copyQueryParamsToContentValues(ContentValues values, Uri uri, String... columns) { for (String column : columns) { String param = uri.getQueryParameter(column); if (param != null) { values.put(column, param); } } } /** * Inserts an argument at the beginning of the selection arg list. */ private String[] insertSelectionArg(String[] selectionArgs, String arg) { if (selectionArgs == null) { return new String[] {arg}; } else { int newLength = selectionArgs.length + 1; String[] newSelectionArgs = new String[newLength]; newSelectionArgs[0] = arg; System.arraycopy(selectionArgs, 0, newSelectionArgs, 1, selectionArgs.length); return newSelectionArgs; } } private String[] appendProjectionArg(String[] projection, String arg) { if (projection == null) { return null; } final int length = projection.length; String[] newProjection = new String[length + 1]; System.arraycopy(projection, 0, newProjection, 0, length); newProjection[length] = arg; return newProjection; } protected Account getDefaultAccount() { AccountManager accountManager = AccountManager.get(getContext()); try { Account[] accounts = accountManager.getAccountsByType(DEFAULT_ACCOUNT_TYPE); if (accounts != null && accounts.length > 0) { return accounts[0]; } } catch (Throwable e) { Log.e(TAG, "Cannot determine the default account for contacts compatibility", e); } return null; } /** * Returns true if the specified account type and data set is writable. */ protected boolean isWritableAccountWithDataSet(String accountTypeAndDataSet) { if (accountTypeAndDataSet == null) { return true; } Boolean writable = mAccountWritability.get(accountTypeAndDataSet); if (writable != null) { return writable; } IContentService contentService = ContentResolver.getContentService(); try { // TODO(dsantoro): Need to update this logic to allow for sub-accounts. for (SyncAdapterType sync : contentService.getSyncAdapterTypes()) { if (ContactsContract.AUTHORITY.equals(sync.authority) && accountTypeAndDataSet.equals(sync.accountType)) { writable = sync.supportsUploading(); break; } } } catch (RemoteException e) { Log.e(TAG, "Could not acquire sync adapter types"); } if (writable == null) { writable = false; } mAccountWritability.put(accountTypeAndDataSet, writable); return writable; } /* package */ static boolean readBooleanQueryParameter(Uri uri, String parameter, boolean defaultValue) { // Manually parse the query, which is much faster than calling uri.getQueryParameter String query = uri.getEncodedQuery(); if (query == null) { return defaultValue; } int index = query.indexOf(parameter); if (index == -1) { return defaultValue; } index += parameter.length(); return !matchQueryParameter(query, index, "=0", false) && !matchQueryParameter(query, index, "=false", true); } private static boolean matchQueryParameter(String query, int index, String value, boolean ignoreCase) { int length = value.length(); return query.regionMatches(ignoreCase, index, value, 0, length) && (query.length() == index + length || query.charAt(index + length) == '&'); } /** * A fast re-implementation of {@link Uri#getQueryParameter} */ /* package */ static String getQueryParameter(Uri uri, String parameter) { String query = uri.getEncodedQuery(); if (query == null) { return null; } int queryLength = query.length(); int parameterLength = parameter.length(); String value; int index = 0; while (true) { index = query.indexOf(parameter, index); if (index == -1) { return null; } // Should match against the whole parameter instead of its suffix. // e.g. The parameter "param" must not be found in "some_param=val". if (index > 0) { char prevChar = query.charAt(index - 1); if (prevChar != '?' && prevChar != '&') { // With "some_param=val1&param=val2", we should find second "param" occurrence. index += parameterLength; continue; } } index += parameterLength; if (queryLength == index) { return null; } if (query.charAt(index) == '=') { index++; break; } } int ampIndex = query.indexOf('&', index); if (ampIndex == -1) { value = query.substring(index); } else { value = query.substring(index, ampIndex); } return Uri.decode(value); } protected boolean isAggregationUpgradeNeeded() { if (!mContactAggregator.isEnabled()) { return false; } int version = Integer.parseInt(mDbHelper.getProperty(PROPERTY_AGGREGATION_ALGORITHM, "1")); return version < PROPERTY_AGGREGATION_ALGORITHM_VERSION; } protected void upgradeAggregationAlgorithmInBackground() { // This upgrade will affect very few contacts, so it can be performed on the // main thread during the initial boot after an OTA Log.i(TAG, "Upgrading aggregation algorithm"); int count = 0; long start = SystemClock.currentThreadTimeMillis(); try { mDb = mDbHelper.getWritableDatabase(); mDb.beginTransaction(); Cursor cursor = mDb.query(true, Tables.RAW_CONTACTS + " r1 JOIN " + Tables.RAW_CONTACTS + " r2", new String[]{"r1." + RawContacts._ID}, "r1." + RawContacts._ID + "!=r2." + RawContacts._ID + " AND r1." + RawContacts.CONTACT_ID + "=r2." + RawContacts.CONTACT_ID + " AND r1." + RawContacts.ACCOUNT_NAME + "=r2." + RawContacts.ACCOUNT_NAME + " AND r1." + RawContacts.ACCOUNT_TYPE + "=r2." + RawContacts.ACCOUNT_TYPE + " AND r1." + RawContacts.DATA_SET + "=r2." + RawContacts.DATA_SET, null, null, null, null, null); try { while (cursor.moveToNext()) { long rawContactId = cursor.getLong(0); mContactAggregator.markForAggregation(rawContactId, RawContacts.AGGREGATION_MODE_DEFAULT, true); count++; } } finally { cursor.close(); } mContactAggregator.aggregateInTransaction(mTransactionContext, mDb); updateSearchIndexInTransaction(); mDb.setTransactionSuccessful(); mDbHelper.setProperty(PROPERTY_AGGREGATION_ALGORITHM, String.valueOf(PROPERTY_AGGREGATION_ALGORITHM_VERSION)); } finally { mDb.endTransaction(); long end = SystemClock.currentThreadTimeMillis(); Log.i(TAG, "Aggregation algorithm upgraded for " + count + " contacts, in " + (end - start) + "ms"); } } /* Visible for testing */ boolean isPhone() { if (!sIsPhoneInitialized) { sIsPhone = new TelephonyManager(getContext()).isVoiceCapable(); sIsPhoneInitialized = true; } return sIsPhone; } private boolean handleDataUsageFeedback(Uri uri) { final long currentTimeMillis = System.currentTimeMillis(); final String usageType = uri.getQueryParameter(DataUsageFeedback.USAGE_TYPE); final String[] ids = uri.getLastPathSegment().trim().split(","); final ArrayList<Long> dataIds = new ArrayList<Long>(); for (String id : ids) { dataIds.add(Long.valueOf(id)); } final boolean successful; if (TextUtils.isEmpty(usageType)) { Log.w(TAG, "Method for data usage feedback isn't specified. Ignoring."); successful = false; } else { successful = updateDataUsageStat(dataIds, usageType, currentTimeMillis) > 0; } // Handle old API. This doesn't affect the result of this entire method. final String[] questionMarks = new String[ids.length]; Arrays.fill(questionMarks, "?"); final String where = Data._ID + " IN (" + TextUtils.join(",", questionMarks) + ")"; final Cursor cursor = mDb.query( Views.DATA, new String[] { Data.CONTACT_ID }, where, ids, null, null, null); try { while (cursor.moveToNext()) { mSelectionArgs1[0] = cursor.getString(0); ContentValues values2 = new ContentValues(); values2.put(Contacts.LAST_TIME_CONTACTED, currentTimeMillis); mDb.update(Tables.CONTACTS, values2, Contacts._ID + "=?", mSelectionArgs1); mDb.execSQL(UPDATE_TIMES_CONTACTED_CONTACTS_TABLE, mSelectionArgs1); mDb.execSQL(UPDATE_TIMES_CONTACTED_RAWCONTACTS_TABLE, mSelectionArgs1); } } finally { cursor.close(); } return successful; } /** * Update {@link Tables#DATA_USAGE_STAT}. * * @return the number of rows affected. */ @VisibleForTesting /* package */ int updateDataUsageStat( List<Long> dataIds, String type, long currentTimeMillis) { final int typeInt = sDataUsageTypeMap.get(type); final String where = DataUsageStatColumns.DATA_ID + " =? AND " + DataUsageStatColumns.USAGE_TYPE_INT + " =?"; final String[] columns = new String[] { DataUsageStatColumns._ID, DataUsageStatColumns.TIMES_USED }; final ContentValues values = new ContentValues(); for (Long dataId : dataIds) { final String[] args = new String[] { dataId.toString(), String.valueOf(typeInt) }; mDb.beginTransaction(); try { final Cursor cursor = mDb.query(Tables.DATA_USAGE_STAT, columns, where, args, null, null, null); try { if (cursor.getCount() > 0) { if (!cursor.moveToFirst()) { Log.e(TAG, "moveToFirst() failed while getAccount() returned non-zero."); } else { values.clear(); values.put(DataUsageStatColumns.TIMES_USED, cursor.getInt(1) + 1); values.put(DataUsageStatColumns.LAST_TIME_USED, currentTimeMillis); mDb.update(Tables.DATA_USAGE_STAT, values, DataUsageStatColumns._ID + " =?", new String[] { cursor.getString(0) }); } } else { values.clear(); values.put(DataUsageStatColumns.DATA_ID, dataId); values.put(DataUsageStatColumns.USAGE_TYPE_INT, typeInt); values.put(DataUsageStatColumns.TIMES_USED, 1); values.put(DataUsageStatColumns.LAST_TIME_USED, currentTimeMillis); mDb.insert(Tables.DATA_USAGE_STAT, null, values); } mDb.setTransactionSuccessful(); } finally { cursor.close(); } } finally { mDb.endTransaction(); } } return dataIds.size(); } /** * Returns a sort order String for promoting data rows (email addresses, phone numbers, etc.) * associated with a primary account. The primary account should be supplied from applications * with {@link ContactsContract#PRIMARY_ACCOUNT_NAME} and * {@link ContactsContract#PRIMARY_ACCOUNT_TYPE}. Null will be returned when the primary * account isn't available. */ private String getAccountPromotionSortOrder(Uri uri) { final String primaryAccountName = uri.getQueryParameter(ContactsContract.PRIMARY_ACCOUNT_NAME); final String primaryAccountType = uri.getQueryParameter(ContactsContract.PRIMARY_ACCOUNT_TYPE); // Data rows associated with primary account should be promoted. if (!TextUtils.isEmpty(primaryAccountName)) { StringBuilder sb = new StringBuilder(); sb.append("(CASE WHEN " + RawContacts.ACCOUNT_NAME + "="); DatabaseUtils.appendEscapedSQLString(sb, primaryAccountName); if (!TextUtils.isEmpty(primaryAccountType)) { sb.append(" AND " + RawContacts.ACCOUNT_TYPE + "="); DatabaseUtils.appendEscapedSQLString(sb, primaryAccountType); } sb.append(" THEN 0 ELSE 1 END)"); return sb.toString(); } else { return null; } } }
false
true
private Cursor queryLocal(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder, long directoryId, final boolean suppressProfileCheck) { if (VERBOSE_LOGGING) { Log.v(TAG, "query: " + uri); } final SQLiteDatabase db = mDbHelper.getReadableDatabase(); SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); String groupBy = null; String limit = getLimit(uri); // Column name for appendProfileRestriction(). We append the profile check to the original // selection if it's not null. String profileRestrictionColumnName = null; final int match = sUriMatcher.match(uri); switch (match) { case SYNCSTATE: return mDbHelper.getSyncState().query(db, projection, selection, selectionArgs, sortOrder); case CONTACTS: { setTablesAndProjectionMapForContacts(qb, uri, projection); appendLocalDirectorySelectionIfNeeded(qb, directoryId); profileRestrictionColumnName = Contacts.IS_USER_PROFILE; sortOrder = prependProfileSortIfNeeded(uri, sortOrder, suppressProfileCheck); break; } case CONTACTS_ID: { long contactId = ContentUris.parseId(uri); enforceProfilePermissionForContact(db, contactId, false); setTablesAndProjectionMapForContacts(qb, uri, projection); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(Contacts._ID + "=?"); break; } case CONTACTS_LOOKUP: case CONTACTS_LOOKUP_ID: { List<String> pathSegments = uri.getPathSegments(); int segmentCount = pathSegments.size(); if (segmentCount < 3) { throw new IllegalArgumentException(mDbHelper.exceptionMessage( "Missing a lookup key", uri)); } String lookupKey = pathSegments.get(2); if (segmentCount == 4) { long contactId = Long.parseLong(pathSegments.get(3)); enforceProfilePermissionForContact(db, contactId, false); SQLiteQueryBuilder lookupQb = new SQLiteQueryBuilder(); setTablesAndProjectionMapForContacts(lookupQb, uri, projection); Cursor c = queryWithContactIdAndLookupKey(lookupQb, db, uri, projection, selection, selectionArgs, sortOrder, groupBy, limit, Contacts._ID, contactId, Contacts.LOOKUP_KEY, lookupKey); if (c != null) { return c; } } setTablesAndProjectionMapForContacts(qb, uri, projection); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(lookupContactIdByLookupKey(db, lookupKey))); qb.appendWhere(Contacts._ID + "=?"); break; } case CONTACTS_LOOKUP_DATA: case CONTACTS_LOOKUP_ID_DATA: { List<String> pathSegments = uri.getPathSegments(); int segmentCount = pathSegments.size(); if (segmentCount < 4) { throw new IllegalArgumentException(mDbHelper.exceptionMessage( "Missing a lookup key", uri)); } String lookupKey = pathSegments.get(2); if (segmentCount == 5) { long contactId = Long.parseLong(pathSegments.get(3)); enforceProfilePermissionForContact(db, contactId, false); SQLiteQueryBuilder lookupQb = new SQLiteQueryBuilder(); setTablesAndProjectionMapForData(lookupQb, uri, projection, false); lookupQb.appendWhere(" AND "); Cursor c = queryWithContactIdAndLookupKey(lookupQb, db, uri, projection, selection, selectionArgs, sortOrder, groupBy, limit, Data.CONTACT_ID, contactId, Data.LOOKUP_KEY, lookupKey); if (c != null) { return c; } // TODO see if the contact exists but has no data rows (rare) } setTablesAndProjectionMapForData(qb, uri, projection, false); long contactId = lookupContactIdByLookupKey(db, lookupKey); enforceProfilePermissionForContact(db, contactId, false); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(" AND " + Data.CONTACT_ID + "=?"); break; } case CONTACTS_ID_STREAM_ITEMS: { long contactId = Long.parseLong(uri.getPathSegments().get(1)); enforceProfilePermissionForContact(db, contactId, false); setTablesAndProjectionMapForStreamItems(qb); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(RawContactsColumns.CONCRETE_CONTACT_ID + "=?"); break; } case CONTACTS_LOOKUP_STREAM_ITEMS: case CONTACTS_LOOKUP_ID_STREAM_ITEMS: { List<String> pathSegments = uri.getPathSegments(); int segmentCount = pathSegments.size(); if (segmentCount < 4) { throw new IllegalArgumentException(mDbHelper.exceptionMessage( "Missing a lookup key", uri)); } String lookupKey = pathSegments.get(2); if (segmentCount == 5) { long contactId = Long.parseLong(pathSegments.get(3)); enforceProfilePermissionForContact(db, contactId, false); SQLiteQueryBuilder lookupQb = new SQLiteQueryBuilder(); setTablesAndProjectionMapForStreamItems(lookupQb); Cursor c = queryWithContactIdAndLookupKey(lookupQb, db, uri, projection, selection, selectionArgs, sortOrder, groupBy, limit, RawContacts.CONTACT_ID, contactId, Contacts.LOOKUP_KEY, lookupKey); if (c != null) { return c; } } setTablesAndProjectionMapForStreamItems(qb); long contactId = lookupContactIdByLookupKey(db, lookupKey); enforceProfilePermissionForContact(db, contactId, false); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(RawContacts.CONTACT_ID + "=?"); break; } case CONTACTS_AS_VCARD: { final String lookupKey = Uri.encode(uri.getPathSegments().get(2)); long contactId = lookupContactIdByLookupKey(db, lookupKey); enforceProfilePermissionForContact(db, contactId, false); qb.setTables(Views.CONTACTS); qb.setProjectionMap(sContactsVCardProjectionMap); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(Contacts._ID + "=?"); break; } case CONTACTS_AS_MULTI_VCARD: { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss"); String currentDateString = dateFormat.format(new Date()).toString(); return db.rawQuery( "SELECT" + " 'vcards_' || ? || '.vcf' AS " + OpenableColumns.DISPLAY_NAME + "," + " NULL AS " + OpenableColumns.SIZE, new String[] { currentDateString }); } case CONTACTS_FILTER: { String filterParam = ""; if (uri.getPathSegments().size() > 2) { filterParam = uri.getLastPathSegment(); } setTablesAndProjectionMapForContactsWithSnippet( qb, uri, projection, filterParam, directoryId); profileRestrictionColumnName = Contacts.IS_USER_PROFILE; sortOrder = prependProfileSortIfNeeded(uri, sortOrder, suppressProfileCheck); break; } case CONTACTS_STREQUENT_FILTER: case CONTACTS_STREQUENT: { // Basically the resultant SQL should look like this: // (SQL for listing starred items) // UNION ALL // (SQL for listing frequently contacted items) // ORDER BY ... final boolean phoneOnly = readBooleanQueryParameter( uri, ContactsContract.STREQUENT_PHONE_ONLY, false); if (match == CONTACTS_STREQUENT_FILTER && uri.getPathSegments().size() > 3) { String filterParam = uri.getLastPathSegment(); StringBuilder sb = new StringBuilder(); sb.append(Contacts._ID + " IN "); appendContactFilterAsNestedQuery(sb, filterParam); selection = DbQueryUtils.concatenateClauses(selection, sb.toString()); } String[] subProjection = null; if (projection != null) { subProjection = appendProjectionArg(projection, TIMES_USED_SORT_COLUMN); } // Build the first query for starred setTablesAndProjectionMapForContacts(qb, uri, projection, false); qb.setProjectionMap(phoneOnly ? sStrequentPhoneOnlyStarredProjectionMap : sStrequentStarredProjectionMap); qb.appendWhere(DbQueryUtils.concatenateClauses( selection, Contacts.IS_USER_PROFILE + "=0")); if (phoneOnly) { qb.appendWhere(" AND " + Contacts.HAS_PHONE_NUMBER + "=1"); } qb.setStrict(true); final String starredQuery = qb.buildQuery(subProjection, Contacts.STARRED + "=1", Contacts._ID, null, null, null); // Reset the builder. qb = new SQLiteQueryBuilder(); qb.setStrict(true); // Build the second query for frequent part. final String frequentQuery; if (phoneOnly) { final StringBuilder tableBuilder = new StringBuilder(); // In phone only mode, we need to look at view_data instead of // contacts/raw_contacts to obtain actual phone numbers. One problem is that // view_data is much larger than view_contacts, so our query might become much // slower. // // To avoid the possible slow down, we start from data usage table and join // view_data to the table, assuming data usage table is quite smaller than // data rows (almost always it should be), and we don't want any phone // numbers not used by the user. This way sqlite is able to drop a number of // rows in view_data in the early stage of data lookup. tableBuilder.append(Tables.DATA_USAGE_STAT + " INNER JOIN " + Views.DATA + " " + Tables.DATA + " ON (" + DataUsageStatColumns.CONCRETE_DATA_ID + "=" + DataColumns.CONCRETE_ID + " AND " + DataUsageStatColumns.CONCRETE_USAGE_TYPE + "=" + DataUsageStatColumns.USAGE_TYPE_INT_CALL + ")"); appendContactPresenceJoin(tableBuilder, projection, RawContacts.CONTACT_ID); appendContactStatusUpdateJoin(tableBuilder, projection, ContactsColumns.LAST_STATUS_UPDATE_ID); qb.setTables(tableBuilder.toString()); qb.setProjectionMap(sStrequentPhoneOnlyFrequentProjectionMap); qb.appendWhere(DbQueryUtils.concatenateClauses( selection, Contacts.STARRED + "=0 OR " + Contacts.STARRED + " IS NULL", MimetypesColumns.MIMETYPE + " IN (" + "'" + Phone.CONTENT_ITEM_TYPE + "', " + "'" + SipAddress.CONTENT_ITEM_TYPE + "')")); frequentQuery = qb.buildQuery(subProjection, null, null, null, null, null); } else { setTablesAndProjectionMapForContacts(qb, uri, projection, true); qb.setProjectionMap(sStrequentFrequentProjectionMap); qb.appendWhere(DbQueryUtils.concatenateClauses( selection, "(" + Contacts.STARRED + " =0 OR " + Contacts.STARRED + " IS NULL)", Contacts.IS_USER_PROFILE + "=0")); frequentQuery = qb.buildQuery(subProjection, null, Contacts._ID, null, null, null); } // Put them together final String unionQuery = qb.buildUnionQuery(new String[] {starredQuery, frequentQuery}, STREQUENT_ORDER_BY, STREQUENT_LIMIT); // Here, we need to use selection / selectionArgs (supplied from users) "twice", // as we want them both for starred items and for frequently contacted items. // // e.g. if the user specify selection = "starred =?" and selectionArgs = "0", // the resultant SQL should be like: // SELECT ... WHERE starred =? AND ... // UNION ALL // SELECT ... WHERE starred =? AND ... String[] doubledSelectionArgs = null; if (selectionArgs != null) { final int length = selectionArgs.length; doubledSelectionArgs = new String[length * 2]; System.arraycopy(selectionArgs, 0, doubledSelectionArgs, 0, length); System.arraycopy(selectionArgs, 0, doubledSelectionArgs, length, length); } Cursor cursor = db.rawQuery(unionQuery, doubledSelectionArgs); if (cursor != null) { cursor.setNotificationUri(getContext().getContentResolver(), ContactsContract.AUTHORITY_URI); } return cursor; } case CONTACTS_FREQUENT: { setTablesAndProjectionMapForContacts(qb, uri, projection, true); qb.setProjectionMap(sStrequentFrequentProjectionMap); qb.appendWhere(Contacts.IS_USER_PROFILE + "=0"); groupBy = Contacts._ID; if (!TextUtils.isEmpty(sortOrder)) { sortOrder = FREQUENT_ORDER_BY + ", " + sortOrder; } else { sortOrder = FREQUENT_ORDER_BY; } break; } case CONTACTS_GROUP: { setTablesAndProjectionMapForContacts(qb, uri, projection); if (uri.getPathSegments().size() > 2) { qb.appendWhere(CONTACTS_IN_GROUP_SELECT); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); } break; } case PROFILE: { enforceProfilePermission(false); setTablesAndProjectionMapForContacts(qb, uri, projection); qb.appendWhere(Contacts.IS_USER_PROFILE + "=1"); break; } case PROFILE_ENTITIES: { enforceProfilePermission(false); setTablesAndProjectionMapForEntities(qb, uri, projection); qb.appendWhere(" AND " + Contacts.IS_USER_PROFILE + "=1"); break; } case PROFILE_DATA: { enforceProfilePermission(false); setTablesAndProjectionMapForData(qb, uri, projection, false); qb.appendWhere(" AND " + RawContacts.RAW_CONTACT_IS_USER_PROFILE + "=1"); break; } case PROFILE_DATA_ID: { enforceProfilePermission(false); setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(" AND " + Data._ID + "=? AND " + RawContacts.RAW_CONTACT_IS_USER_PROFILE + "=1"); break; } case PROFILE_AS_VCARD: { enforceProfilePermission(false); qb.setTables(Views.CONTACTS); qb.setProjectionMap(sContactsVCardProjectionMap); qb.appendWhere(Contacts.IS_USER_PROFILE + "=1"); break; } case CONTACTS_ID_DATA: { long contactId = Long.parseLong(uri.getPathSegments().get(1)); setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(" AND " + RawContacts.CONTACT_ID + "=?"); break; } case CONTACTS_ID_PHOTO: { long contactId = Long.parseLong(uri.getPathSegments().get(1)); enforceProfilePermissionForContact(db, contactId, false); setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(" AND " + RawContacts.CONTACT_ID + "=?"); qb.appendWhere(" AND " + Data._ID + "=" + Contacts.PHOTO_ID); break; } case CONTACTS_ID_ENTITIES: { long contactId = Long.parseLong(uri.getPathSegments().get(1)); setTablesAndProjectionMapForEntities(qb, uri, projection); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(" AND " + RawContacts.CONTACT_ID + "=?"); break; } case CONTACTS_LOOKUP_ENTITIES: case CONTACTS_LOOKUP_ID_ENTITIES: { List<String> pathSegments = uri.getPathSegments(); int segmentCount = pathSegments.size(); if (segmentCount < 4) { throw new IllegalArgumentException(mDbHelper.exceptionMessage( "Missing a lookup key", uri)); } String lookupKey = pathSegments.get(2); if (segmentCount == 5) { long contactId = Long.parseLong(pathSegments.get(3)); SQLiteQueryBuilder lookupQb = new SQLiteQueryBuilder(); setTablesAndProjectionMapForEntities(lookupQb, uri, projection); lookupQb.appendWhere(" AND "); Cursor c = queryWithContactIdAndLookupKey(lookupQb, db, uri, projection, selection, selectionArgs, sortOrder, groupBy, limit, Contacts.Entity.CONTACT_ID, contactId, Contacts.Entity.LOOKUP_KEY, lookupKey); if (c != null) { return c; } } setTablesAndProjectionMapForEntities(qb, uri, projection); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(lookupContactIdByLookupKey(db, lookupKey))); qb.appendWhere(" AND " + Contacts.Entity.CONTACT_ID + "=?"); break; } case STREAM_ITEMS: { setTablesAndProjectionMapForStreamItems(qb); break; } case STREAM_ITEMS_ID: { setTablesAndProjectionMapForStreamItems(qb); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(StreamItemsColumns.CONCRETE_ID + "=?"); break; } case STREAM_ITEMS_LIMIT: { MatrixCursor cursor = new MatrixCursor(new String[]{StreamItems.MAX_ITEMS}, 1); cursor.addRow(new Object[]{MAX_STREAM_ITEMS_PER_RAW_CONTACT}); return cursor; } case STREAM_ITEMS_PHOTOS: { setTablesAndProjectionMapForStreamItemPhotos(qb); break; } case STREAM_ITEMS_ID_PHOTOS: { setTablesAndProjectionMapForStreamItemPhotos(qb); String streamItemId = uri.getPathSegments().get(1); selectionArgs = insertSelectionArg(selectionArgs, streamItemId); qb.appendWhere(StreamItemPhotosColumns.CONCRETE_STREAM_ITEM_ID + "=?"); break; } case STREAM_ITEMS_ID_PHOTOS_ID: { setTablesAndProjectionMapForStreamItemPhotos(qb); String streamItemId = uri.getPathSegments().get(1); String streamItemPhotoId = uri.getPathSegments().get(3); selectionArgs = insertSelectionArg(selectionArgs, streamItemPhotoId); selectionArgs = insertSelectionArg(selectionArgs, streamItemId); qb.appendWhere(StreamItemPhotosColumns.CONCRETE_STREAM_ITEM_ID + "=? AND " + StreamItemPhotosColumns.CONCRETE_ID + "=?"); break; } case PHOTO_DIMENSIONS: { MatrixCursor cursor = new MatrixCursor( new String[]{DisplayPhoto.DISPLAY_MAX_DIM, DisplayPhoto.THUMBNAIL_MAX_DIM}, 1); cursor.addRow(new Object[]{mMaxDisplayPhotoDim, mMaxThumbnailPhotoDim}); return cursor; } case PHONES: { setTablesAndProjectionMapForData(qb, uri, projection, false); qb.appendWhere(" AND " + Data.MIMETYPE + " = '" + Phone.CONTENT_ITEM_TYPE + "'"); break; } case PHONES_ID: { setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(" AND " + Data.MIMETYPE + " = '" + Phone.CONTENT_ITEM_TYPE + "'"); qb.appendWhere(" AND " + Data._ID + "=?"); break; } case PHONES_FILTER: { String typeParam = uri.getQueryParameter(DataUsageFeedback.USAGE_TYPE); Integer typeInt = sDataUsageTypeMap.get(typeParam); if (typeInt == null) { typeInt = DataUsageStatColumns.USAGE_TYPE_INT_CALL; } setTablesAndProjectionMapForData(qb, uri, projection, true, typeInt); qb.appendWhere(" AND " + Data.MIMETYPE + " = '" + Phone.CONTENT_ITEM_TYPE + "'"); if (uri.getPathSegments().size() > 2) { String filterParam = uri.getLastPathSegment(); StringBuilder sb = new StringBuilder(); sb.append(" AND ("); boolean hasCondition = false; boolean orNeeded = false; String normalizedName = NameNormalizer.normalize(filterParam); if (normalizedName.length() > 0) { sb.append(Data.RAW_CONTACT_ID + " IN " + "(SELECT " + RawContactsColumns.CONCRETE_ID + " FROM " + Tables.SEARCH_INDEX + " JOIN " + Tables.RAW_CONTACTS + " ON (" + Tables.SEARCH_INDEX + "." + SearchIndexColumns.CONTACT_ID + "=" + RawContactsColumns.CONCRETE_CONTACT_ID + ")" + " WHERE " + SearchIndexColumns.NAME + " MATCH "); DatabaseUtils.appendEscapedSQLString(sb, sanitizeMatch(filterParam) + "*"); sb.append(")"); orNeeded = true; hasCondition = true; } String number = PhoneNumberUtils.normalizeNumber(filterParam); if (!TextUtils.isEmpty(number)) { if (orNeeded) { sb.append(" OR "); } sb.append(Data._ID + " IN (SELECT DISTINCT " + PhoneLookupColumns.DATA_ID + " FROM " + Tables.PHONE_LOOKUP + " WHERE " + PhoneLookupColumns.NORMALIZED_NUMBER + " LIKE '"); sb.append(number); sb.append("%')"); hasCondition = true; } if (!hasCondition) { // If it is neither a phone number nor a name, the query should return // an empty cursor. Let's ensure that. sb.append("0"); } sb.append(")"); qb.appendWhere(sb); } groupBy = PhoneColumns.NORMALIZED_NUMBER + "," + RawContacts.CONTACT_ID; if (sortOrder == null) { final String accountPromotionSortOrder = getAccountPromotionSortOrder(uri); if (!TextUtils.isEmpty(accountPromotionSortOrder)) { sortOrder = accountPromotionSortOrder + ", " + PHONE_FILTER_SORT_ORDER; } else { sortOrder = PHONE_FILTER_SORT_ORDER; } } break; } case EMAILS: { setTablesAndProjectionMapForData(qb, uri, projection, false); qb.appendWhere(" AND " + Data.MIMETYPE + " = '" + Email.CONTENT_ITEM_TYPE + "'"); break; } case EMAILS_ID: { setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(" AND " + Data.MIMETYPE + " = '" + Email.CONTENT_ITEM_TYPE + "'" + " AND " + Data._ID + "=?"); break; } case EMAILS_LOOKUP: { setTablesAndProjectionMapForData(qb, uri, projection, false); qb.appendWhere(" AND " + Data.MIMETYPE + " = '" + Email.CONTENT_ITEM_TYPE + "'"); if (uri.getPathSegments().size() > 2) { String email = uri.getLastPathSegment(); String address = mDbHelper.extractAddressFromEmailAddress(email); selectionArgs = insertSelectionArg(selectionArgs, address); qb.appendWhere(" AND UPPER(" + Email.DATA + ")=UPPER(?)"); } break; } case EMAILS_FILTER: { String typeParam = uri.getQueryParameter(DataUsageFeedback.USAGE_TYPE); Integer typeInt = sDataUsageTypeMap.get(typeParam); if (typeInt == null) { typeInt = DataUsageStatColumns.USAGE_TYPE_INT_LONG_TEXT; } setTablesAndProjectionMapForData(qb, uri, projection, true, typeInt); String filterParam = null; if (uri.getPathSegments().size() > 3) { filterParam = uri.getLastPathSegment(); if (TextUtils.isEmpty(filterParam)) { filterParam = null; } } if (filterParam == null) { // If the filter is unspecified, return nothing qb.appendWhere(" AND 0"); } else { StringBuilder sb = new StringBuilder(); sb.append(" AND " + Data._ID + " IN ("); sb.append( "SELECT " + Data._ID + " FROM " + Tables.DATA + " WHERE " + DataColumns.MIMETYPE_ID + "="); sb.append(mDbHelper.getMimeTypeIdForEmail()); sb.append(" AND " + Data.DATA1 + " LIKE "); DatabaseUtils.appendEscapedSQLString(sb, filterParam + '%'); if (!filterParam.contains("@")) { sb.append( " UNION SELECT " + Data._ID + " FROM " + Tables.DATA + " WHERE +" + DataColumns.MIMETYPE_ID + "="); sb.append(mDbHelper.getMimeTypeIdForEmail()); sb.append(" AND " + Data.RAW_CONTACT_ID + " IN " + "(SELECT " + RawContactsColumns.CONCRETE_ID + " FROM " + Tables.SEARCH_INDEX + " JOIN " + Tables.RAW_CONTACTS + " ON (" + Tables.SEARCH_INDEX + "." + SearchIndexColumns.CONTACT_ID + "=" + RawContactsColumns.CONCRETE_CONTACT_ID + ")" + " WHERE " + SearchIndexColumns.NAME + " MATCH "); DatabaseUtils.appendEscapedSQLString(sb, sanitizeMatch(filterParam) + "*"); sb.append(")"); } sb.append(")"); qb.appendWhere(sb); } groupBy = Email.DATA + "," + RawContacts.CONTACT_ID; if (sortOrder == null) { final String accountPromotionSortOrder = getAccountPromotionSortOrder(uri); if (!TextUtils.isEmpty(accountPromotionSortOrder)) { sortOrder = accountPromotionSortOrder + ", " + EMAIL_FILTER_SORT_ORDER; } else { sortOrder = EMAIL_FILTER_SORT_ORDER; } } break; } case POSTALS: { setTablesAndProjectionMapForData(qb, uri, projection, false); qb.appendWhere(" AND " + Data.MIMETYPE + " = '" + StructuredPostal.CONTENT_ITEM_TYPE + "'"); break; } case POSTALS_ID: { setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(" AND " + Data.MIMETYPE + " = '" + StructuredPostal.CONTENT_ITEM_TYPE + "'"); qb.appendWhere(" AND " + Data._ID + "=?"); break; } case RAW_CONTACTS: { setTablesAndProjectionMapForRawContacts(qb, uri); profileRestrictionColumnName = RawContacts.RAW_CONTACT_IS_USER_PROFILE; break; } case RAW_CONTACTS_ID: { long rawContactId = ContentUris.parseId(uri); enforceProfilePermissionForRawContact(db, rawContactId, false); setTablesAndProjectionMapForRawContacts(qb, uri); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId)); qb.appendWhere(" AND " + RawContacts._ID + "=?"); break; } case RAW_CONTACTS_DATA: { long rawContactId = Long.parseLong(uri.getPathSegments().get(1)); setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId)); qb.appendWhere(" AND " + Data.RAW_CONTACT_ID + "=?"); profileRestrictionColumnName = RawContacts.RAW_CONTACT_IS_USER_PROFILE; break; } case RAW_CONTACTS_ID_STREAM_ITEMS: { long rawContactId = Long.parseLong(uri.getPathSegments().get(1)); enforceProfilePermissionForRawContact(db, rawContactId, false); setTablesAndProjectionMapForStreamItems(qb); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId)); qb.appendWhere(StreamItems.RAW_CONTACT_ID + "=?"); break; } case PROFILE_RAW_CONTACTS: { enforceProfilePermission(false); setTablesAndProjectionMapForRawContacts(qb, uri); qb.appendWhere(" AND " + RawContacts.RAW_CONTACT_IS_USER_PROFILE + "=1"); break; } case PROFILE_RAW_CONTACTS_ID: { enforceProfilePermission(false); long rawContactId = ContentUris.parseId(uri); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId)); setTablesAndProjectionMapForRawContacts(qb, uri); qb.appendWhere(" AND " + RawContacts.RAW_CONTACT_IS_USER_PROFILE + "=1 AND " + RawContacts._ID + "=?"); break; } case PROFILE_RAW_CONTACTS_ID_DATA: { enforceProfilePermission(false); long rawContactId = Long.parseLong(uri.getPathSegments().get(2)); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId)); setTablesAndProjectionMapForData(qb, uri, projection, false); qb.appendWhere(" AND " + RawContacts.RAW_CONTACT_IS_USER_PROFILE + "=1 AND " + Data.RAW_CONTACT_ID + "=?"); break; } case PROFILE_RAW_CONTACTS_ID_ENTITIES: { enforceProfilePermission(false); long rawContactId = Long.parseLong(uri.getPathSegments().get(2)); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId)); setTablesAndProjectionMapForRawEntities(qb, uri); qb.appendWhere(" AND " + RawContacts.RAW_CONTACT_IS_USER_PROFILE + "=1 AND " + RawContacts._ID + "=?"); break; } case DATA: { setTablesAndProjectionMapForData(qb, uri, projection, false); profileRestrictionColumnName = RawContacts.RAW_CONTACT_IS_USER_PROFILE; break; } case DATA_ID: { long dataId = ContentUris.parseId(uri); enforceProfilePermissionForData(db, dataId, false); setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(" AND " + Data._ID + "=?"); break; } case PHONE_LOOKUP: { if (TextUtils.isEmpty(sortOrder)) { // Default the sort order to something reasonable so we get consistent // results when callers don't request an ordering sortOrder = " length(lookup.normalized_number) DESC"; } String number = uri.getPathSegments().size() > 1 ? uri.getLastPathSegment() : ""; String numberE164 = PhoneNumberUtils.formatNumberToE164(number, mDbHelper.getCurrentCountryIso()); String normalizedNumber = PhoneNumberUtils.normalizeNumber(number); mDbHelper.buildPhoneLookupAndContactQuery(qb, normalizedNumber, numberE164); qb.setProjectionMap(sPhoneLookupProjectionMap); // Phone lookup cannot be combined with a selection selection = null; selectionArgs = null; break; } case GROUPS: { qb.setTables(Views.GROUPS); qb.setProjectionMap(sGroupsProjectionMap); appendAccountFromParameter(qb, uri, true); break; } case GROUPS_ID: { qb.setTables(Views.GROUPS); qb.setProjectionMap(sGroupsProjectionMap); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(Groups._ID + "=?"); break; } case GROUPS_SUMMARY: { final boolean returnGroupCountPerAccount = readBooleanQueryParameter(uri, Groups.PARAM_RETURN_GROUP_COUNT_PER_ACCOUNT, false); qb.setTables(Views.GROUPS + " AS " + Tables.GROUPS); qb.setProjectionMap(returnGroupCountPerAccount ? sGroupsSummaryProjectionMapWithGroupCountPerAccount : sGroupsSummaryProjectionMap); appendAccountFromParameter(qb, uri, true); groupBy = GroupsColumns.CONCRETE_ID; break; } case AGGREGATION_EXCEPTIONS: { qb.setTables(Tables.AGGREGATION_EXCEPTIONS); qb.setProjectionMap(sAggregationExceptionsProjectionMap); break; } case AGGREGATION_SUGGESTIONS: { long contactId = Long.parseLong(uri.getPathSegments().get(1)); String filter = null; if (uri.getPathSegments().size() > 3) { filter = uri.getPathSegments().get(3); } final int maxSuggestions; if (limit != null) { maxSuggestions = Integer.parseInt(limit); } else { maxSuggestions = DEFAULT_MAX_SUGGESTIONS; } ArrayList<AggregationSuggestionParameter> parameters = null; List<String> query = uri.getQueryParameters("query"); if (query != null && !query.isEmpty()) { parameters = new ArrayList<AggregationSuggestionParameter>(query.size()); for (String parameter : query) { int offset = parameter.indexOf(':'); parameters.add(offset == -1 ? new AggregationSuggestionParameter( AggregationSuggestions.PARAMETER_MATCH_NAME, parameter) : new AggregationSuggestionParameter( parameter.substring(0, offset), parameter.substring(offset + 1))); } } setTablesAndProjectionMapForContacts(qb, uri, projection); return mContactAggregator.queryAggregationSuggestions(qb, projection, contactId, maxSuggestions, filter, parameters); } case SETTINGS: { qb.setTables(Tables.SETTINGS); qb.setProjectionMap(sSettingsProjectionMap); appendAccountFromParameter(qb, uri, false); // When requesting specific columns, this query requires // late-binding of the GroupMembership MIME-type. final String groupMembershipMimetypeId = Long.toString(mDbHelper .getMimeTypeId(GroupMembership.CONTENT_ITEM_TYPE)); if (projection != null && projection.length != 0 && mDbHelper.isInProjection(projection, Settings.UNGROUPED_COUNT)) { selectionArgs = insertSelectionArg(selectionArgs, groupMembershipMimetypeId); } if (projection != null && projection.length != 0 && mDbHelper.isInProjection(projection, Settings.UNGROUPED_WITH_PHONES)) { selectionArgs = insertSelectionArg(selectionArgs, groupMembershipMimetypeId); } break; } case STATUS_UPDATES: { setTableAndProjectionMapForStatusUpdates(qb, projection); break; } case STATUS_UPDATES_ID: { setTableAndProjectionMapForStatusUpdates(qb, projection); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(DataColumns.CONCRETE_ID + "=?"); break; } case SEARCH_SUGGESTIONS: { return mGlobalSearchSupport.handleSearchSuggestionsQuery( db, uri, projection, limit); } case SEARCH_SHORTCUT: { String lookupKey = uri.getLastPathSegment(); String filter = getQueryParameter( uri, SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA); return mGlobalSearchSupport.handleSearchShortcutRefresh( db, projection, lookupKey, filter); } case LIVE_FOLDERS_CONTACTS: qb.setTables(Views.CONTACTS); qb.setProjectionMap(sLiveFoldersProjectionMap); break; case LIVE_FOLDERS_CONTACTS_WITH_PHONES: qb.setTables(Views.CONTACTS); qb.setProjectionMap(sLiveFoldersProjectionMap); qb.appendWhere(Contacts.HAS_PHONE_NUMBER + "=1"); break; case LIVE_FOLDERS_CONTACTS_FAVORITES: qb.setTables(Views.CONTACTS); qb.setProjectionMap(sLiveFoldersProjectionMap); qb.appendWhere(Contacts.STARRED + "=1"); break; case LIVE_FOLDERS_CONTACTS_GROUP_NAME: qb.setTables(Views.CONTACTS); qb.setProjectionMap(sLiveFoldersProjectionMap); qb.appendWhere(CONTACTS_IN_GROUP_SELECT); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); break; case RAW_CONTACT_ENTITIES: { setTablesAndProjectionMapForRawEntities(qb, uri); break; } case RAW_CONTACT_ENTITY_ID: { long rawContactId = Long.parseLong(uri.getPathSegments().get(1)); setTablesAndProjectionMapForRawEntities(qb, uri); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId)); qb.appendWhere(" AND " + RawContacts._ID + "=?"); break; } case PROVIDER_STATUS: { return queryProviderStatus(uri, projection); } case DIRECTORIES : { qb.setTables(Tables.DIRECTORIES); qb.setProjectionMap(sDirectoryProjectionMap); break; } case DIRECTORIES_ID : { long id = ContentUris.parseId(uri); qb.setTables(Tables.DIRECTORIES); qb.setProjectionMap(sDirectoryProjectionMap); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(id)); qb.appendWhere(Directory._ID + "=?"); break; } case COMPLETE_NAME: { return completeName(uri, projection); } default: return mLegacyApiSupport.query(uri, projection, selection, selectionArgs, sortOrder, limit); } qb.setStrict(true); if (profileRestrictionColumnName != null) { // This check is very slow and most of the rows will pass though this check, so // it should be put after user's selection, so SQLite won't do this check first. selection = appendProfileRestriction(uri, profileRestrictionColumnName, suppressProfileCheck, selection); } Cursor cursor = query(db, qb, projection, selection, selectionArgs, sortOrder, groupBy, limit); if (readBooleanQueryParameter(uri, ContactCounts.ADDRESS_BOOK_INDEX_EXTRAS, false)) { cursor = bundleLetterCountExtras(cursor, db, qb, selection, selectionArgs, sortOrder); } return cursor; }
private Cursor queryLocal(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder, long directoryId, final boolean suppressProfileCheck) { if (VERBOSE_LOGGING) { Log.v(TAG, "query: " + uri); } final SQLiteDatabase db = mDbHelper.getReadableDatabase(); SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); String groupBy = null; String limit = getLimit(uri); // Column name for appendProfileRestriction(). We append the profile check to the original // selection if it's not null. String profileRestrictionColumnName = null; final int match = sUriMatcher.match(uri); switch (match) { case SYNCSTATE: return mDbHelper.getSyncState().query(db, projection, selection, selectionArgs, sortOrder); case CONTACTS: { setTablesAndProjectionMapForContacts(qb, uri, projection); appendLocalDirectorySelectionIfNeeded(qb, directoryId); profileRestrictionColumnName = Contacts.IS_USER_PROFILE; sortOrder = prependProfileSortIfNeeded(uri, sortOrder, suppressProfileCheck); break; } case CONTACTS_ID: { long contactId = ContentUris.parseId(uri); enforceProfilePermissionForContact(db, contactId, false); setTablesAndProjectionMapForContacts(qb, uri, projection); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(Contacts._ID + "=?"); break; } case CONTACTS_LOOKUP: case CONTACTS_LOOKUP_ID: { List<String> pathSegments = uri.getPathSegments(); int segmentCount = pathSegments.size(); if (segmentCount < 3) { throw new IllegalArgumentException(mDbHelper.exceptionMessage( "Missing a lookup key", uri)); } String lookupKey = pathSegments.get(2); if (segmentCount == 4) { long contactId = Long.parseLong(pathSegments.get(3)); enforceProfilePermissionForContact(db, contactId, false); SQLiteQueryBuilder lookupQb = new SQLiteQueryBuilder(); setTablesAndProjectionMapForContacts(lookupQb, uri, projection); Cursor c = queryWithContactIdAndLookupKey(lookupQb, db, uri, projection, selection, selectionArgs, sortOrder, groupBy, limit, Contacts._ID, contactId, Contacts.LOOKUP_KEY, lookupKey); if (c != null) { return c; } } setTablesAndProjectionMapForContacts(qb, uri, projection); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(lookupContactIdByLookupKey(db, lookupKey))); qb.appendWhere(Contacts._ID + "=?"); break; } case CONTACTS_LOOKUP_DATA: case CONTACTS_LOOKUP_ID_DATA: { List<String> pathSegments = uri.getPathSegments(); int segmentCount = pathSegments.size(); if (segmentCount < 4) { throw new IllegalArgumentException(mDbHelper.exceptionMessage( "Missing a lookup key", uri)); } String lookupKey = pathSegments.get(2); if (segmentCount == 5) { long contactId = Long.parseLong(pathSegments.get(3)); enforceProfilePermissionForContact(db, contactId, false); SQLiteQueryBuilder lookupQb = new SQLiteQueryBuilder(); setTablesAndProjectionMapForData(lookupQb, uri, projection, false); lookupQb.appendWhere(" AND "); Cursor c = queryWithContactIdAndLookupKey(lookupQb, db, uri, projection, selection, selectionArgs, sortOrder, groupBy, limit, Data.CONTACT_ID, contactId, Data.LOOKUP_KEY, lookupKey); if (c != null) { return c; } // TODO see if the contact exists but has no data rows (rare) } setTablesAndProjectionMapForData(qb, uri, projection, false); long contactId = lookupContactIdByLookupKey(db, lookupKey); enforceProfilePermissionForContact(db, contactId, false); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(" AND " + Data.CONTACT_ID + "=?"); break; } case CONTACTS_ID_STREAM_ITEMS: { long contactId = Long.parseLong(uri.getPathSegments().get(1)); enforceProfilePermissionForContact(db, contactId, false); setTablesAndProjectionMapForStreamItems(qb); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(RawContactsColumns.CONCRETE_CONTACT_ID + "=?"); break; } case CONTACTS_LOOKUP_STREAM_ITEMS: case CONTACTS_LOOKUP_ID_STREAM_ITEMS: { List<String> pathSegments = uri.getPathSegments(); int segmentCount = pathSegments.size(); if (segmentCount < 4) { throw new IllegalArgumentException(mDbHelper.exceptionMessage( "Missing a lookup key", uri)); } String lookupKey = pathSegments.get(2); if (segmentCount == 5) { long contactId = Long.parseLong(pathSegments.get(3)); enforceProfilePermissionForContact(db, contactId, false); SQLiteQueryBuilder lookupQb = new SQLiteQueryBuilder(); setTablesAndProjectionMapForStreamItems(lookupQb); Cursor c = queryWithContactIdAndLookupKey(lookupQb, db, uri, projection, selection, selectionArgs, sortOrder, groupBy, limit, RawContacts.CONTACT_ID, contactId, Contacts.LOOKUP_KEY, lookupKey); if (c != null) { return c; } } setTablesAndProjectionMapForStreamItems(qb); long contactId = lookupContactIdByLookupKey(db, lookupKey); enforceProfilePermissionForContact(db, contactId, false); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(RawContacts.CONTACT_ID + "=?"); break; } case CONTACTS_AS_VCARD: { final String lookupKey = Uri.encode(uri.getPathSegments().get(2)); long contactId = lookupContactIdByLookupKey(db, lookupKey); enforceProfilePermissionForContact(db, contactId, false); qb.setTables(Views.CONTACTS); qb.setProjectionMap(sContactsVCardProjectionMap); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(Contacts._ID + "=?"); break; } case CONTACTS_AS_MULTI_VCARD: { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss"); String currentDateString = dateFormat.format(new Date()).toString(); return db.rawQuery( "SELECT" + " 'vcards_' || ? || '.vcf' AS " + OpenableColumns.DISPLAY_NAME + "," + " NULL AS " + OpenableColumns.SIZE, new String[] { currentDateString }); } case CONTACTS_FILTER: { String filterParam = ""; if (uri.getPathSegments().size() > 2) { filterParam = uri.getLastPathSegment(); } setTablesAndProjectionMapForContactsWithSnippet( qb, uri, projection, filterParam, directoryId); profileRestrictionColumnName = Contacts.IS_USER_PROFILE; sortOrder = prependProfileSortIfNeeded(uri, sortOrder, suppressProfileCheck); break; } case CONTACTS_STREQUENT_FILTER: case CONTACTS_STREQUENT: { // Basically the resultant SQL should look like this: // (SQL for listing starred items) // UNION ALL // (SQL for listing frequently contacted items) // ORDER BY ... final boolean phoneOnly = readBooleanQueryParameter( uri, ContactsContract.STREQUENT_PHONE_ONLY, false); if (match == CONTACTS_STREQUENT_FILTER && uri.getPathSegments().size() > 3) { String filterParam = uri.getLastPathSegment(); StringBuilder sb = new StringBuilder(); sb.append(Contacts._ID + " IN "); appendContactFilterAsNestedQuery(sb, filterParam); selection = DbQueryUtils.concatenateClauses(selection, sb.toString()); } String[] subProjection = null; if (projection != null) { subProjection = appendProjectionArg(projection, TIMES_USED_SORT_COLUMN); } // Build the first query for starred setTablesAndProjectionMapForContacts(qb, uri, projection, false); qb.setProjectionMap(phoneOnly ? sStrequentPhoneOnlyStarredProjectionMap : sStrequentStarredProjectionMap); qb.appendWhere(DbQueryUtils.concatenateClauses( selection, Contacts.IS_USER_PROFILE + "=0")); if (phoneOnly) { qb.appendWhere(" AND " + Contacts.HAS_PHONE_NUMBER + "=1"); } qb.setStrict(true); final String starredQuery = qb.buildQuery(subProjection, Contacts.STARRED + "=1", Contacts._ID, null, null, null); // Reset the builder. qb = new SQLiteQueryBuilder(); qb.setStrict(true); // Build the second query for frequent part. final String frequentQuery; if (phoneOnly) { final StringBuilder tableBuilder = new StringBuilder(); // In phone only mode, we need to look at view_data instead of // contacts/raw_contacts to obtain actual phone numbers. One problem is that // view_data is much larger than view_contacts, so our query might become much // slower. // // To avoid the possible slow down, we start from data usage table and join // view_data to the table, assuming data usage table is quite smaller than // data rows (almost always it should be), and we don't want any phone // numbers not used by the user. This way sqlite is able to drop a number of // rows in view_data in the early stage of data lookup. tableBuilder.append(Tables.DATA_USAGE_STAT + " INNER JOIN " + Views.DATA + " " + Tables.DATA + " ON (" + DataUsageStatColumns.CONCRETE_DATA_ID + "=" + DataColumns.CONCRETE_ID + " AND " + DataUsageStatColumns.CONCRETE_USAGE_TYPE + "=" + DataUsageStatColumns.USAGE_TYPE_INT_CALL + ")"); appendContactPresenceJoin(tableBuilder, projection, RawContacts.CONTACT_ID); appendContactStatusUpdateJoin(tableBuilder, projection, ContactsColumns.LAST_STATUS_UPDATE_ID); qb.setTables(tableBuilder.toString()); qb.setProjectionMap(sStrequentPhoneOnlyFrequentProjectionMap); qb.appendWhere(DbQueryUtils.concatenateClauses( selection, Contacts.STARRED + "=0 OR " + Contacts.STARRED + " IS NULL", MimetypesColumns.MIMETYPE + " IN (" + "'" + Phone.CONTENT_ITEM_TYPE + "', " + "'" + SipAddress.CONTENT_ITEM_TYPE + "')")); frequentQuery = qb.buildQuery(subProjection, null, null, null, null, null); } else { setTablesAndProjectionMapForContacts(qb, uri, projection, true); qb.setProjectionMap(sStrequentFrequentProjectionMap); qb.appendWhere(DbQueryUtils.concatenateClauses( selection, "(" + Contacts.STARRED + " =0 OR " + Contacts.STARRED + " IS NULL)", Contacts.IS_USER_PROFILE + "=0")); frequentQuery = qb.buildQuery(subProjection, null, Contacts._ID, null, null, null); } // Put them together final String unionQuery = qb.buildUnionQuery(new String[] {starredQuery, frequentQuery}, STREQUENT_ORDER_BY, STREQUENT_LIMIT); // Here, we need to use selection / selectionArgs (supplied from users) "twice", // as we want them both for starred items and for frequently contacted items. // // e.g. if the user specify selection = "starred =?" and selectionArgs = "0", // the resultant SQL should be like: // SELECT ... WHERE starred =? AND ... // UNION ALL // SELECT ... WHERE starred =? AND ... String[] doubledSelectionArgs = null; if (selectionArgs != null) { final int length = selectionArgs.length; doubledSelectionArgs = new String[length * 2]; System.arraycopy(selectionArgs, 0, doubledSelectionArgs, 0, length); System.arraycopy(selectionArgs, 0, doubledSelectionArgs, length, length); } Cursor cursor = db.rawQuery(unionQuery, doubledSelectionArgs); if (cursor != null) { cursor.setNotificationUri(getContext().getContentResolver(), ContactsContract.AUTHORITY_URI); } return cursor; } case CONTACTS_FREQUENT: { setTablesAndProjectionMapForContacts(qb, uri, projection, true); qb.setProjectionMap(sStrequentFrequentProjectionMap); qb.appendWhere(Contacts.IS_USER_PROFILE + "=0"); groupBy = Contacts._ID; if (!TextUtils.isEmpty(sortOrder)) { sortOrder = FREQUENT_ORDER_BY + ", " + sortOrder; } else { sortOrder = FREQUENT_ORDER_BY; } break; } case CONTACTS_GROUP: { setTablesAndProjectionMapForContacts(qb, uri, projection); if (uri.getPathSegments().size() > 2) { qb.appendWhere(CONTACTS_IN_GROUP_SELECT); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); } break; } case PROFILE: { enforceProfilePermission(false); setTablesAndProjectionMapForContacts(qb, uri, projection); qb.appendWhere(Contacts.IS_USER_PROFILE + "=1"); break; } case PROFILE_ENTITIES: { enforceProfilePermission(false); setTablesAndProjectionMapForEntities(qb, uri, projection); qb.appendWhere(" AND " + Contacts.IS_USER_PROFILE + "=1"); break; } case PROFILE_DATA: { enforceProfilePermission(false); setTablesAndProjectionMapForData(qb, uri, projection, false); qb.appendWhere(" AND " + RawContacts.RAW_CONTACT_IS_USER_PROFILE + "=1"); break; } case PROFILE_DATA_ID: { enforceProfilePermission(false); setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(" AND " + Data._ID + "=? AND " + RawContacts.RAW_CONTACT_IS_USER_PROFILE + "=1"); break; } case PROFILE_AS_VCARD: { enforceProfilePermission(false); qb.setTables(Views.CONTACTS); qb.setProjectionMap(sContactsVCardProjectionMap); qb.appendWhere(Contacts.IS_USER_PROFILE + "=1"); break; } case CONTACTS_ID_DATA: { long contactId = Long.parseLong(uri.getPathSegments().get(1)); setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(" AND " + RawContacts.CONTACT_ID + "=?"); break; } case CONTACTS_ID_PHOTO: { long contactId = Long.parseLong(uri.getPathSegments().get(1)); enforceProfilePermissionForContact(db, contactId, false); setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(" AND " + RawContacts.CONTACT_ID + "=?"); qb.appendWhere(" AND " + Data._ID + "=" + Contacts.PHOTO_ID); break; } case CONTACTS_ID_ENTITIES: { long contactId = Long.parseLong(uri.getPathSegments().get(1)); setTablesAndProjectionMapForEntities(qb, uri, projection); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(contactId)); qb.appendWhere(" AND " + RawContacts.CONTACT_ID + "=?"); break; } case CONTACTS_LOOKUP_ENTITIES: case CONTACTS_LOOKUP_ID_ENTITIES: { List<String> pathSegments = uri.getPathSegments(); int segmentCount = pathSegments.size(); if (segmentCount < 4) { throw new IllegalArgumentException(mDbHelper.exceptionMessage( "Missing a lookup key", uri)); } String lookupKey = pathSegments.get(2); if (segmentCount == 5) { long contactId = Long.parseLong(pathSegments.get(3)); SQLiteQueryBuilder lookupQb = new SQLiteQueryBuilder(); setTablesAndProjectionMapForEntities(lookupQb, uri, projection); lookupQb.appendWhere(" AND "); Cursor c = queryWithContactIdAndLookupKey(lookupQb, db, uri, projection, selection, selectionArgs, sortOrder, groupBy, limit, Contacts.Entity.CONTACT_ID, contactId, Contacts.Entity.LOOKUP_KEY, lookupKey); if (c != null) { return c; } } setTablesAndProjectionMapForEntities(qb, uri, projection); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(lookupContactIdByLookupKey(db, lookupKey))); qb.appendWhere(" AND " + Contacts.Entity.CONTACT_ID + "=?"); break; } case STREAM_ITEMS: { setTablesAndProjectionMapForStreamItems(qb); break; } case STREAM_ITEMS_ID: { setTablesAndProjectionMapForStreamItems(qb); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(StreamItemsColumns.CONCRETE_ID + "=?"); break; } case STREAM_ITEMS_LIMIT: { MatrixCursor cursor = new MatrixCursor(new String[]{StreamItems.MAX_ITEMS}, 1); cursor.addRow(new Object[]{MAX_STREAM_ITEMS_PER_RAW_CONTACT}); return cursor; } case STREAM_ITEMS_PHOTOS: { setTablesAndProjectionMapForStreamItemPhotos(qb); break; } case STREAM_ITEMS_ID_PHOTOS: { setTablesAndProjectionMapForStreamItemPhotos(qb); String streamItemId = uri.getPathSegments().get(1); selectionArgs = insertSelectionArg(selectionArgs, streamItemId); qb.appendWhere(StreamItemPhotosColumns.CONCRETE_STREAM_ITEM_ID + "=?"); break; } case STREAM_ITEMS_ID_PHOTOS_ID: { setTablesAndProjectionMapForStreamItemPhotos(qb); String streamItemId = uri.getPathSegments().get(1); String streamItemPhotoId = uri.getPathSegments().get(3); selectionArgs = insertSelectionArg(selectionArgs, streamItemPhotoId); selectionArgs = insertSelectionArg(selectionArgs, streamItemId); qb.appendWhere(StreamItemPhotosColumns.CONCRETE_STREAM_ITEM_ID + "=? AND " + StreamItemPhotosColumns.CONCRETE_ID + "=?"); break; } case PHOTO_DIMENSIONS: { MatrixCursor cursor = new MatrixCursor( new String[]{DisplayPhoto.DISPLAY_MAX_DIM, DisplayPhoto.THUMBNAIL_MAX_DIM}, 1); cursor.addRow(new Object[]{mMaxDisplayPhotoDim, mMaxThumbnailPhotoDim}); return cursor; } case PHONES: { setTablesAndProjectionMapForData(qb, uri, projection, false); qb.appendWhere(" AND " + Data.MIMETYPE + " = '" + Phone.CONTENT_ITEM_TYPE + "'"); break; } case PHONES_ID: { setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(" AND " + Data.MIMETYPE + " = '" + Phone.CONTENT_ITEM_TYPE + "'"); qb.appendWhere(" AND " + Data._ID + "=?"); break; } case PHONES_FILTER: { String typeParam = uri.getQueryParameter(DataUsageFeedback.USAGE_TYPE); profileRestrictionColumnName = RawContacts.RAW_CONTACT_IS_USER_PROFILE; Integer typeInt = sDataUsageTypeMap.get(typeParam); if (typeInt == null) { typeInt = DataUsageStatColumns.USAGE_TYPE_INT_CALL; } setTablesAndProjectionMapForData(qb, uri, projection, true, typeInt); qb.appendWhere(" AND " + Data.MIMETYPE + " = '" + Phone.CONTENT_ITEM_TYPE + "'"); if (uri.getPathSegments().size() > 2) { String filterParam = uri.getLastPathSegment(); StringBuilder sb = new StringBuilder(); sb.append(" AND ("); boolean hasCondition = false; boolean orNeeded = false; String normalizedName = NameNormalizer.normalize(filterParam); if (normalizedName.length() > 0) { sb.append(Data.RAW_CONTACT_ID + " IN " + "(SELECT " + RawContactsColumns.CONCRETE_ID + " FROM " + Tables.SEARCH_INDEX + " JOIN " + Tables.RAW_CONTACTS + " ON (" + Tables.SEARCH_INDEX + "." + SearchIndexColumns.CONTACT_ID + "=" + RawContactsColumns.CONCRETE_CONTACT_ID + ")" + " WHERE " + SearchIndexColumns.NAME + " MATCH "); DatabaseUtils.appendEscapedSQLString(sb, sanitizeMatch(filterParam) + "*"); sb.append(")"); orNeeded = true; hasCondition = true; } String number = PhoneNumberUtils.normalizeNumber(filterParam); if (!TextUtils.isEmpty(number)) { if (orNeeded) { sb.append(" OR "); } sb.append(Data._ID + " IN (SELECT DISTINCT " + PhoneLookupColumns.DATA_ID + " FROM " + Tables.PHONE_LOOKUP + " WHERE " + PhoneLookupColumns.NORMALIZED_NUMBER + " LIKE '"); sb.append(number); sb.append("%')"); hasCondition = true; } if (!hasCondition) { // If it is neither a phone number nor a name, the query should return // an empty cursor. Let's ensure that. sb.append("0"); } sb.append(")"); qb.appendWhere(sb); } groupBy = PhoneColumns.NORMALIZED_NUMBER + "," + RawContacts.CONTACT_ID; if (sortOrder == null) { final String accountPromotionSortOrder = getAccountPromotionSortOrder(uri); if (!TextUtils.isEmpty(accountPromotionSortOrder)) { sortOrder = accountPromotionSortOrder + ", " + PHONE_FILTER_SORT_ORDER; } else { sortOrder = PHONE_FILTER_SORT_ORDER; } } break; } case EMAILS: { setTablesAndProjectionMapForData(qb, uri, projection, false); qb.appendWhere(" AND " + Data.MIMETYPE + " = '" + Email.CONTENT_ITEM_TYPE + "'"); break; } case EMAILS_ID: { setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(" AND " + Data.MIMETYPE + " = '" + Email.CONTENT_ITEM_TYPE + "'" + " AND " + Data._ID + "=?"); break; } case EMAILS_LOOKUP: { setTablesAndProjectionMapForData(qb, uri, projection, false); qb.appendWhere(" AND " + Data.MIMETYPE + " = '" + Email.CONTENT_ITEM_TYPE + "'"); if (uri.getPathSegments().size() > 2) { String email = uri.getLastPathSegment(); String address = mDbHelper.extractAddressFromEmailAddress(email); selectionArgs = insertSelectionArg(selectionArgs, address); qb.appendWhere(" AND UPPER(" + Email.DATA + ")=UPPER(?)"); } break; } case EMAILS_FILTER: { String typeParam = uri.getQueryParameter(DataUsageFeedback.USAGE_TYPE); profileRestrictionColumnName = RawContacts.RAW_CONTACT_IS_USER_PROFILE; Integer typeInt = sDataUsageTypeMap.get(typeParam); if (typeInt == null) { typeInt = DataUsageStatColumns.USAGE_TYPE_INT_LONG_TEXT; } setTablesAndProjectionMapForData(qb, uri, projection, true, typeInt); String filterParam = null; if (uri.getPathSegments().size() > 3) { filterParam = uri.getLastPathSegment(); if (TextUtils.isEmpty(filterParam)) { filterParam = null; } } if (filterParam == null) { // If the filter is unspecified, return nothing qb.appendWhere(" AND 0"); } else { StringBuilder sb = new StringBuilder(); sb.append(" AND " + Data._ID + " IN ("); sb.append( "SELECT " + Data._ID + " FROM " + Tables.DATA + " WHERE " + DataColumns.MIMETYPE_ID + "="); sb.append(mDbHelper.getMimeTypeIdForEmail()); sb.append(" AND " + Data.DATA1 + " LIKE "); DatabaseUtils.appendEscapedSQLString(sb, filterParam + '%'); if (!filterParam.contains("@")) { sb.append( " UNION SELECT " + Data._ID + " FROM " + Tables.DATA + " WHERE +" + DataColumns.MIMETYPE_ID + "="); sb.append(mDbHelper.getMimeTypeIdForEmail()); sb.append(" AND " + Data.RAW_CONTACT_ID + " IN " + "(SELECT " + RawContactsColumns.CONCRETE_ID + " FROM " + Tables.SEARCH_INDEX + " JOIN " + Tables.RAW_CONTACTS + " ON (" + Tables.SEARCH_INDEX + "." + SearchIndexColumns.CONTACT_ID + "=" + RawContactsColumns.CONCRETE_CONTACT_ID + ")" + " WHERE " + SearchIndexColumns.NAME + " MATCH "); DatabaseUtils.appendEscapedSQLString(sb, sanitizeMatch(filterParam) + "*"); sb.append(")"); } sb.append(")"); qb.appendWhere(sb); } groupBy = Email.DATA + "," + RawContacts.CONTACT_ID; if (sortOrder == null) { final String accountPromotionSortOrder = getAccountPromotionSortOrder(uri); if (!TextUtils.isEmpty(accountPromotionSortOrder)) { sortOrder = accountPromotionSortOrder + ", " + EMAIL_FILTER_SORT_ORDER; } else { sortOrder = EMAIL_FILTER_SORT_ORDER; } } break; } case POSTALS: { setTablesAndProjectionMapForData(qb, uri, projection, false); qb.appendWhere(" AND " + Data.MIMETYPE + " = '" + StructuredPostal.CONTENT_ITEM_TYPE + "'"); break; } case POSTALS_ID: { setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(" AND " + Data.MIMETYPE + " = '" + StructuredPostal.CONTENT_ITEM_TYPE + "'"); qb.appendWhere(" AND " + Data._ID + "=?"); break; } case RAW_CONTACTS: { setTablesAndProjectionMapForRawContacts(qb, uri); profileRestrictionColumnName = RawContacts.RAW_CONTACT_IS_USER_PROFILE; break; } case RAW_CONTACTS_ID: { long rawContactId = ContentUris.parseId(uri); enforceProfilePermissionForRawContact(db, rawContactId, false); setTablesAndProjectionMapForRawContacts(qb, uri); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId)); qb.appendWhere(" AND " + RawContacts._ID + "=?"); break; } case RAW_CONTACTS_DATA: { long rawContactId = Long.parseLong(uri.getPathSegments().get(1)); setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId)); qb.appendWhere(" AND " + Data.RAW_CONTACT_ID + "=?"); profileRestrictionColumnName = RawContacts.RAW_CONTACT_IS_USER_PROFILE; break; } case RAW_CONTACTS_ID_STREAM_ITEMS: { long rawContactId = Long.parseLong(uri.getPathSegments().get(1)); enforceProfilePermissionForRawContact(db, rawContactId, false); setTablesAndProjectionMapForStreamItems(qb); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId)); qb.appendWhere(StreamItems.RAW_CONTACT_ID + "=?"); break; } case PROFILE_RAW_CONTACTS: { enforceProfilePermission(false); setTablesAndProjectionMapForRawContacts(qb, uri); qb.appendWhere(" AND " + RawContacts.RAW_CONTACT_IS_USER_PROFILE + "=1"); break; } case PROFILE_RAW_CONTACTS_ID: { enforceProfilePermission(false); long rawContactId = ContentUris.parseId(uri); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId)); setTablesAndProjectionMapForRawContacts(qb, uri); qb.appendWhere(" AND " + RawContacts.RAW_CONTACT_IS_USER_PROFILE + "=1 AND " + RawContacts._ID + "=?"); break; } case PROFILE_RAW_CONTACTS_ID_DATA: { enforceProfilePermission(false); long rawContactId = Long.parseLong(uri.getPathSegments().get(2)); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId)); setTablesAndProjectionMapForData(qb, uri, projection, false); qb.appendWhere(" AND " + RawContacts.RAW_CONTACT_IS_USER_PROFILE + "=1 AND " + Data.RAW_CONTACT_ID + "=?"); break; } case PROFILE_RAW_CONTACTS_ID_ENTITIES: { enforceProfilePermission(false); long rawContactId = Long.parseLong(uri.getPathSegments().get(2)); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId)); setTablesAndProjectionMapForRawEntities(qb, uri); qb.appendWhere(" AND " + RawContacts.RAW_CONTACT_IS_USER_PROFILE + "=1 AND " + RawContacts._ID + "=?"); break; } case DATA: { setTablesAndProjectionMapForData(qb, uri, projection, false); profileRestrictionColumnName = RawContacts.RAW_CONTACT_IS_USER_PROFILE; break; } case DATA_ID: { long dataId = ContentUris.parseId(uri); enforceProfilePermissionForData(db, dataId, false); setTablesAndProjectionMapForData(qb, uri, projection, false); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(" AND " + Data._ID + "=?"); break; } case PHONE_LOOKUP: { if (TextUtils.isEmpty(sortOrder)) { // Default the sort order to something reasonable so we get consistent // results when callers don't request an ordering sortOrder = " length(lookup.normalized_number) DESC"; } String number = uri.getPathSegments().size() > 1 ? uri.getLastPathSegment() : ""; String numberE164 = PhoneNumberUtils.formatNumberToE164(number, mDbHelper.getCurrentCountryIso()); String normalizedNumber = PhoneNumberUtils.normalizeNumber(number); mDbHelper.buildPhoneLookupAndContactQuery(qb, normalizedNumber, numberE164); qb.setProjectionMap(sPhoneLookupProjectionMap); // Phone lookup cannot be combined with a selection selection = null; selectionArgs = null; break; } case GROUPS: { qb.setTables(Views.GROUPS); qb.setProjectionMap(sGroupsProjectionMap); appendAccountFromParameter(qb, uri, true); break; } case GROUPS_ID: { qb.setTables(Views.GROUPS); qb.setProjectionMap(sGroupsProjectionMap); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(Groups._ID + "=?"); break; } case GROUPS_SUMMARY: { final boolean returnGroupCountPerAccount = readBooleanQueryParameter(uri, Groups.PARAM_RETURN_GROUP_COUNT_PER_ACCOUNT, false); qb.setTables(Views.GROUPS + " AS " + Tables.GROUPS); qb.setProjectionMap(returnGroupCountPerAccount ? sGroupsSummaryProjectionMapWithGroupCountPerAccount : sGroupsSummaryProjectionMap); appendAccountFromParameter(qb, uri, true); groupBy = GroupsColumns.CONCRETE_ID; break; } case AGGREGATION_EXCEPTIONS: { qb.setTables(Tables.AGGREGATION_EXCEPTIONS); qb.setProjectionMap(sAggregationExceptionsProjectionMap); break; } case AGGREGATION_SUGGESTIONS: { long contactId = Long.parseLong(uri.getPathSegments().get(1)); String filter = null; if (uri.getPathSegments().size() > 3) { filter = uri.getPathSegments().get(3); } final int maxSuggestions; if (limit != null) { maxSuggestions = Integer.parseInt(limit); } else { maxSuggestions = DEFAULT_MAX_SUGGESTIONS; } ArrayList<AggregationSuggestionParameter> parameters = null; List<String> query = uri.getQueryParameters("query"); if (query != null && !query.isEmpty()) { parameters = new ArrayList<AggregationSuggestionParameter>(query.size()); for (String parameter : query) { int offset = parameter.indexOf(':'); parameters.add(offset == -1 ? new AggregationSuggestionParameter( AggregationSuggestions.PARAMETER_MATCH_NAME, parameter) : new AggregationSuggestionParameter( parameter.substring(0, offset), parameter.substring(offset + 1))); } } setTablesAndProjectionMapForContacts(qb, uri, projection); return mContactAggregator.queryAggregationSuggestions(qb, projection, contactId, maxSuggestions, filter, parameters); } case SETTINGS: { qb.setTables(Tables.SETTINGS); qb.setProjectionMap(sSettingsProjectionMap); appendAccountFromParameter(qb, uri, false); // When requesting specific columns, this query requires // late-binding of the GroupMembership MIME-type. final String groupMembershipMimetypeId = Long.toString(mDbHelper .getMimeTypeId(GroupMembership.CONTENT_ITEM_TYPE)); if (projection != null && projection.length != 0 && mDbHelper.isInProjection(projection, Settings.UNGROUPED_COUNT)) { selectionArgs = insertSelectionArg(selectionArgs, groupMembershipMimetypeId); } if (projection != null && projection.length != 0 && mDbHelper.isInProjection(projection, Settings.UNGROUPED_WITH_PHONES)) { selectionArgs = insertSelectionArg(selectionArgs, groupMembershipMimetypeId); } break; } case STATUS_UPDATES: { setTableAndProjectionMapForStatusUpdates(qb, projection); break; } case STATUS_UPDATES_ID: { setTableAndProjectionMapForStatusUpdates(qb, projection); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); qb.appendWhere(DataColumns.CONCRETE_ID + "=?"); break; } case SEARCH_SUGGESTIONS: { return mGlobalSearchSupport.handleSearchSuggestionsQuery( db, uri, projection, limit); } case SEARCH_SHORTCUT: { String lookupKey = uri.getLastPathSegment(); String filter = getQueryParameter( uri, SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA); return mGlobalSearchSupport.handleSearchShortcutRefresh( db, projection, lookupKey, filter); } case LIVE_FOLDERS_CONTACTS: qb.setTables(Views.CONTACTS); qb.setProjectionMap(sLiveFoldersProjectionMap); break; case LIVE_FOLDERS_CONTACTS_WITH_PHONES: qb.setTables(Views.CONTACTS); qb.setProjectionMap(sLiveFoldersProjectionMap); qb.appendWhere(Contacts.HAS_PHONE_NUMBER + "=1"); break; case LIVE_FOLDERS_CONTACTS_FAVORITES: qb.setTables(Views.CONTACTS); qb.setProjectionMap(sLiveFoldersProjectionMap); qb.appendWhere(Contacts.STARRED + "=1"); break; case LIVE_FOLDERS_CONTACTS_GROUP_NAME: qb.setTables(Views.CONTACTS); qb.setProjectionMap(sLiveFoldersProjectionMap); qb.appendWhere(CONTACTS_IN_GROUP_SELECT); selectionArgs = insertSelectionArg(selectionArgs, uri.getLastPathSegment()); break; case RAW_CONTACT_ENTITIES: { setTablesAndProjectionMapForRawEntities(qb, uri); break; } case RAW_CONTACT_ENTITY_ID: { long rawContactId = Long.parseLong(uri.getPathSegments().get(1)); setTablesAndProjectionMapForRawEntities(qb, uri); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(rawContactId)); qb.appendWhere(" AND " + RawContacts._ID + "=?"); break; } case PROVIDER_STATUS: { return queryProviderStatus(uri, projection); } case DIRECTORIES : { qb.setTables(Tables.DIRECTORIES); qb.setProjectionMap(sDirectoryProjectionMap); break; } case DIRECTORIES_ID : { long id = ContentUris.parseId(uri); qb.setTables(Tables.DIRECTORIES); qb.setProjectionMap(sDirectoryProjectionMap); selectionArgs = insertSelectionArg(selectionArgs, String.valueOf(id)); qb.appendWhere(Directory._ID + "=?"); break; } case COMPLETE_NAME: { return completeName(uri, projection); } default: return mLegacyApiSupport.query(uri, projection, selection, selectionArgs, sortOrder, limit); } qb.setStrict(true); if (profileRestrictionColumnName != null) { // This check is very slow and most of the rows will pass though this check, so // it should be put after user's selection, so SQLite won't do this check first. selection = appendProfileRestriction(uri, profileRestrictionColumnName, suppressProfileCheck, selection); } Cursor cursor = query(db, qb, projection, selection, selectionArgs, sortOrder, groupBy, limit); if (readBooleanQueryParameter(uri, ContactCounts.ADDRESS_BOOK_INDEX_EXTRAS, false)) { cursor = bundleLetterCountExtras(cursor, db, qb, selection, selectionArgs, sortOrder); } return cursor; }
diff --git a/src/btlshp/turns/Turn.java b/src/btlshp/turns/Turn.java index 2c47e45..e708f24 100644 --- a/src/btlshp/turns/Turn.java +++ b/src/btlshp/turns/Turn.java @@ -1,468 +1,468 @@ package btlshp.turns; import java.io.FileNotFoundException; import java.io.IOException; import java.io.Serializable; import btlshp.entities.Base; import btlshp.entities.ConstructBlock; import btlshp.entities.Location; import btlshp.enums.Direction; import btlshp.entities.Ship; import btlshp.entities.Map; import java.io.*; public interface Turn { /** * @returns true if the move object represents a successful move, false otherwise. */ boolean wasSuccessful(); /** * Executes a given move object representing a move from the other player. * @throws IllegalStateException If the turn was not successful. */ void executeTurn(); } class Pass implements Turn, Serializable{ /** * */ private static final long serialVersionUID = 3359745261868508357L; @Override public void executeTurn() {//Does no work } @Override public boolean wasSuccessful() { //Always returns true because a pass turn cannot fail return true; } @Override public String toString(){ return "pass"; } } class RequestPostponeGame implements Turn, Serializable{ /** * */ private static final long serialVersionUID = -2537600636201002718L; @Override /** * Opponent would like to PostPone Game */ public void executeTurn() { // TODO Implementation UI dependent //Generate a dialog box with player and allow player to accept or reject } @Override public boolean wasSuccessful() { // TODO Implementation UI dependent return true; } @Override public String toString(){ return "requestPostponeGame"; } } class ConfirmPostponeGame implements Turn, Serializable{ /** * */ private static final long serialVersionUID = -7601913526703183133L; @Override /** * Opponent accepted postponing game */ public void executeTurn() { // TODO Implementation UI dependent } @Override public boolean wasSuccessful() { // TODO Implementation UI dependent return true; } @Override public String toString(){ return "confirmPostponeGame"; } } class LoadGameState implements Turn, Serializable{ /** * */ private static final long serialVersionUID = 4870988534077315987L; private String filePath; /** * * @param f location of saved game file */ public LoadGameState(String f){ filePath = f; } @Override public void executeTurn() { FileInputStream fileIn = null; ObjectInputStream objIn = null; try{ fileIn = new FileInputStream(filePath); objIn = new ObjectInputStream(fileIn); fileIn.close(); }catch(IOException e){ System.err.println(e.getMessage()); } } @Override public boolean wasSuccessful() { // TODO Implementation IO dependent return true; } @Override public String toString(){ return "loadGameState"; } } class SaveGameState implements Turn, Serializable{ /** * */ private static final long serialVersionUID = 2354631655310067958L; private Map saveGame; public SaveGameState(Map map) { saveGame = map; } @Override public void executeTurn() { // TODO Auto-generated method stub ObjectOutputStream objOut = null; FileOutputStream fileOut = null; try { - fileOut = new FileOutputStream("game.dat"); + fileOut = new FileOutputStream("..Dropbox/Btlshp/game.dat"); objOut = new ObjectOutputStream(fileOut); // uncertain what object is needed to save objOut.writeObject(saveGame); objOut.close(); } catch (IOException e) { e.printStackTrace(); } } @Override public boolean wasSuccessful() { // TODO Auto-generated method stub return true; } @Override public String toString(){ return "saveGameState"; } } class RequestSurrender implements Turn, Serializable{ /** * */ private static final long serialVersionUID = -4395558489216020334L; @Override /** * Opponent requests to quit(surrender) game */ public void executeTurn() { // TODO Implementation UI dependent //Generate dialog for the player to accept or reject surrender } @Override public boolean wasSuccessful() { // TODO Implementation UI dependent return true; } @Override public String toString(){ return "requestSurrender"; } } class AcceptSurrender implements Turn, Serializable{ /** * */ private static final long serialVersionUID = -8163598235191879797L; @Override /** * Opponent has accepted request to surrender */ public void executeTurn() { // TODO Implementation UI dependent //Generate dialog informing player opponent has accepted surrender } @Override public boolean wasSuccessful() { // TODO Implementation UI dependent return true; } @Override public String toString(){ return "acceptSurrender"; } } class MoveShip implements Turn, Serializable{ /** * */ private static final long serialVersionUID = 4599021282070269467L; private Ship s; private Direction dir; private int distance; private Map m; private boolean success = false; public MoveShip(Map m, Ship s, Direction dir, int distance) { this.m = m; this.s = s; this.dir = dir; this.distance = distance; } @Override public void executeTurn() { try{ m.move(s, dir, distance); success = true; }catch(IllegalStateException e){ success = false; } } @Override public boolean wasSuccessful() { return true; } @Override public String toString(){ return "moveShip"; } } class PlaceMine implements Turn, Serializable{ /** * */ private static final long serialVersionUID = -4336837927576289067L; private Map m; private Location loc; private Ship s; private boolean success = false; public PlaceMine(Map m, Ship s, Location loc) { this.m = m; this.loc = loc; this.s = s; } @Override public void executeTurn() { try{ m.placeMine(s, loc); success = true; }catch(IllegalStateException e){ success = false; } } @Override public boolean wasSuccessful() { return success; } @Override public String toString(){ return "placeMine"; } } class TakeMine implements Turn, Serializable{ /** * */ private static final long serialVersionUID = -1991458862311470623L; private Location loc; private Ship s; private Map m; private boolean success = false; public TakeMine(Map m, Ship s, Location loc) { this.s = s; this.loc = loc; this.m = m; } @Override public void executeTurn() { try{ m.pickupMine(s, loc); success = true; }catch(IllegalStateException e){ success = false; } } @Override public boolean wasSuccessful() { return success; } @Override public String toString(){ return "takeMine"; } } class LaunchTorpedo implements Turn, Serializable{ /** * */ private static final long serialVersionUID = 1790493199271040630L; private Map m; private Ship s; private boolean success = false; LaunchTorpedo(Map m2, Ship s2) { this.m = m2; this.s = s2; } @Override public void executeTurn() { try{ m.fireTorpedo(s); success = true; }catch(IllegalStateException e){ success = false; } } @Override public boolean wasSuccessful() { return success; } @Override public String toString(){ return "launchTorpedo"; } } class Shoot implements Turn, Serializable{ /** * */ private static final long serialVersionUID = -605750640559980738L; private Map m; private Ship s; private Location loc; private boolean success = false; public Shoot(Map m, Ship s, Location loc) { this.m = m; this.s = s; this.loc = loc; } @Override public void executeTurn() { try{ m.fireGuns(s, loc); success = true; }catch(IllegalStateException e){ success = false; } } @Override public boolean wasSuccessful() { return success; } @Override public String toString(){ return "shoot"; } } class RepairBase implements Turn, Serializable{ /** * */ private static final long serialVersionUID = 3486672126675014858L; private ConstructBlock repairBlock; private Base b; private boolean success = false; RepairBase(Base b, ConstructBlock repairBlock) { this.b = b; this.repairBlock = repairBlock; } @Override public void executeTurn() { b.AssesRepair(repairBlock); success = true; } @Override public boolean wasSuccessful() { return success; } @Override public String toString(){ return "repairBase"; } } class RepairShip implements Turn, Serializable{ /** * */ private static final long serialVersionUID = 89817140305258661L; private Ship s; private ConstructBlock repairBlock; private boolean success = false; RepairShip(Ship s, ConstructBlock repairBlock) { this.s = s; this.repairBlock = repairBlock; } @Override public void executeTurn() { s.AssesRepair(repairBlock); success = true; } @Override public boolean wasSuccessful() { return success; } @Override public String toString(){ return "repairShip"; } }
true
true
public void executeTurn() { // TODO Auto-generated method stub ObjectOutputStream objOut = null; FileOutputStream fileOut = null; try { fileOut = new FileOutputStream("game.dat"); objOut = new ObjectOutputStream(fileOut); // uncertain what object is needed to save objOut.writeObject(saveGame); objOut.close(); } catch (IOException e) { e.printStackTrace(); } }
public void executeTurn() { // TODO Auto-generated method stub ObjectOutputStream objOut = null; FileOutputStream fileOut = null; try { fileOut = new FileOutputStream("..Dropbox/Btlshp/game.dat"); objOut = new ObjectOutputStream(fileOut); // uncertain what object is needed to save objOut.writeObject(saveGame); objOut.close(); } catch (IOException e) { e.printStackTrace(); } }
diff --git a/src/plugins/WebOfTrust/WebOfTrust.java b/src/plugins/WebOfTrust/WebOfTrust.java index b39c0d42..56a2faf9 100644 --- a/src/plugins/WebOfTrust/WebOfTrust.java +++ b/src/plugins/WebOfTrust/WebOfTrust.java @@ -1,3241 +1,3241 @@ /* This code is part of WoT, a plugin for Freenet. It is distributed * under the GNU General Public License, version 2 (or at your option * any later version). See http://www.gnu.org/ for details of the GPL. */ package plugins.WebOfTrust; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.net.MalformedURLException; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Random; import plugins.WebOfTrust.Identity.FetchState; import plugins.WebOfTrust.Identity.IdentityID; import plugins.WebOfTrust.Score.ScoreID; import plugins.WebOfTrust.Trust.TrustID; import plugins.WebOfTrust.exceptions.DuplicateIdentityException; import plugins.WebOfTrust.exceptions.DuplicateScoreException; import plugins.WebOfTrust.exceptions.DuplicateTrustException; import plugins.WebOfTrust.exceptions.InvalidParameterException; import plugins.WebOfTrust.exceptions.NotInTrustTreeException; import plugins.WebOfTrust.exceptions.NotTrustedException; import plugins.WebOfTrust.exceptions.UnknownIdentityException; import plugins.WebOfTrust.introduction.IntroductionClient; import plugins.WebOfTrust.introduction.IntroductionPuzzle; import plugins.WebOfTrust.introduction.IntroductionPuzzleStore; import plugins.WebOfTrust.introduction.IntroductionServer; import plugins.WebOfTrust.introduction.OwnIntroductionPuzzle; import plugins.WebOfTrust.ui.fcp.FCPInterface; import plugins.WebOfTrust.ui.web.WebInterface; import com.db4o.Db4o; import com.db4o.ObjectContainer; import com.db4o.ObjectSet; import com.db4o.defragment.Defragment; import com.db4o.defragment.DefragmentConfig; import com.db4o.ext.ExtObjectContainer; import com.db4o.query.Query; import com.db4o.reflect.jdk.JdkReflector; import freenet.keys.FreenetURI; import freenet.keys.USK; import freenet.l10n.BaseL10n; import freenet.l10n.BaseL10n.LANGUAGE; import freenet.l10n.PluginL10n; import freenet.node.RequestClient; import freenet.pluginmanager.FredPlugin; import freenet.pluginmanager.FredPluginBaseL10n; import freenet.pluginmanager.FredPluginFCP; import freenet.pluginmanager.FredPluginL10n; import freenet.pluginmanager.FredPluginRealVersioned; import freenet.pluginmanager.FredPluginThreadless; import freenet.pluginmanager.FredPluginVersioned; import freenet.pluginmanager.PluginReplySender; import freenet.pluginmanager.PluginRespirator; import freenet.support.CurrentTimeUTC; import freenet.support.Logger; import freenet.support.Logger.LogLevel; import freenet.support.SimpleFieldSet; import freenet.support.SizeUtil; import freenet.support.api.Bucket; import freenet.support.io.FileUtil; /** * A web of trust plugin based on Freenet. * * @author xor ([email protected]), Julien Cornuwel ([email protected]) */ public class WebOfTrust implements FredPlugin, FredPluginThreadless, FredPluginFCP, FredPluginVersioned, FredPluginRealVersioned, FredPluginL10n, FredPluginBaseL10n { /* Constants */ public static final boolean FAST_DEBUG_MODE = false; /** The relative path of the plugin on Freenet's web interface */ public static final String SELF_URI = "/WebOfTrust"; /** Package-private method to allow unit tests to bypass some assert()s */ /** * The "name" of this web of trust. It is included in the document name of identity URIs. For an example, see the SEED_IDENTITIES * constant below. The purpose of this constant is to allow anyone to create his own custom web of trust which is completely disconnected * from the "official" web of trust of the Freenet project. It is also used as the session cookie namespace. */ public static final String WOT_NAME = "WebOfTrust"; public static final String DATABASE_FILENAME = WOT_NAME + ".db4o"; public static final int DATABASE_FORMAT_VERSION = 2; /** * The official seed identities of the WoT plugin: If a newbie wants to download the whole offficial web of trust, he needs at least one * trust list from an identity which is well-connected to the web of trust. To prevent newbies from having to add this identity manually, * the Freenet development team provides a list of seed identities - each of them is one of the developers. */ private static final String[] SEED_IDENTITIES = new String[] { "USK@QeTBVWTwBldfI-lrF~xf0nqFVDdQoSUghT~PvhyJ1NE,OjEywGD063La2H-IihD7iYtZm3rC0BP6UTvvwyF5Zh4,AQACAAE/WebOfTrust/1344", // xor "USK@z9dv7wqsxIBCiFLW7VijMGXD9Gl-EXAqBAwzQ4aq26s,4Uvc~Fjw3i9toGeQuBkDARUV5mF7OTKoAhqOA9LpNdo,AQACAAE/WebOfTrust/1270", // Toad "USK@o2~q8EMoBkCNEgzLUL97hLPdddco9ix1oAnEa~VzZtg,X~vTpL2LSyKvwQoYBx~eleI2RF6QzYJpzuenfcKDKBM,AQACAAE/WebOfTrust/9379", // Bombe // "USK@cI~w2hrvvyUa1E6PhJ9j5cCoG1xmxSooi7Nez4V2Gd4,A3ArC3rrJBHgAJV~LlwY9kgxM8kUR2pVYXbhGFtid78,AQACAAE/WebOfTrust/19", // TheSeeker. Disabled because he is using LCWoT and it does not support identity introduction ATM. "USK@D3MrAR-AVMqKJRjXnpKW2guW9z1mw5GZ9BB15mYVkVc,xgddjFHx2S~5U6PeFkwqO5V~1gZngFLoM-xaoMKSBI8,AQACAAE/WebOfTrust/4959", // zidel }; /* References from the node */ /** The node's interface to connect the plugin with the node, needed for retrieval of all other interfaces */ private PluginRespirator mPR; private static PluginL10n l10n; /* References from the plugin itself */ /* Database & configuration of the plugin */ private ExtObjectContainer mDB; private Configuration mConfig; private IntroductionPuzzleStore mPuzzleStore; /** Used for exporting identities, identity introductions and introduction puzzles to XML and importing them from XML. */ private XMLTransformer mXMLTransformer; private RequestClient mRequestClient; /* Worker objects which actually run the plugin */ /** * Periodically wakes up and inserts any OwnIdentity which needs to be inserted. */ private IdentityInserter mInserter; /** * Fetches identities when it is told to do so by the plugin: * - At startup, all known identities are fetched * - When a new identity is received from a trust list it is fetched * - When a new identity is received by the IntrouductionServer it is fetched * - When an identity is manually added it is also fetched. * - ... */ private IdentityFetcher mFetcher; /** * Uploads captchas belonging to our own identities which others can solve to get on the trust list of them. Checks whether someone * uploaded solutions for them periodically and adds the new identities if a solution is received. */ private IntroductionServer mIntroductionServer; /** * Downloads captchas which the user can solve to announce his identities on other people's trust lists, provides the interface for * the UI to obtain the captchas and enter solutions. Uploads the solutions if the UI enters them. */ private IntroductionClient mIntroductionClient; /* Actual data of the WoT */ private boolean mFullScoreComputationNeeded = false; private boolean mTrustListImportInProgress = false; /* User interfaces */ private WebInterface mWebInterface; private FCPInterface mFCPInterface; /* Statistics */ private int mFullScoreRecomputationCount = 0; private long mFullScoreRecomputationMilliseconds = 0; private int mIncrementalScoreRecomputationCount = 0; private long mIncrementalScoreRecomputationMilliseconds = 0; /* These booleans are used for preventing the construction of log-strings if logging is disabled (for saving some cpu cycles) */ private static transient volatile boolean logDEBUG = false; private static transient volatile boolean logMINOR = false; static { Logger.registerClass(WebOfTrust.class); } public void runPlugin(PluginRespirator myPR) { try { Logger.normal(this, "Web Of Trust plugin version " + Version.getMarketingVersion() + " starting up..."); /* Catpcha generation needs headless mode on linux */ System.setProperty("java.awt.headless", "true"); mPR = myPR; /* TODO: This can be used for clean copies of the database to get rid of corrupted internal db4o structures. /* We should provide an option on the web interface to run this once during next startup and switch to the cloned database */ // cloneDatabase(new File(getUserDataDirectory(), DATABASE_FILENAME), new File(getUserDataDirectory(), DATABASE_FILENAME + ".clone")); mDB = openDatabase(new File(getUserDataDirectory(), DATABASE_FILENAME)); mConfig = getOrCreateConfig(); if(mConfig.getDatabaseFormatVersion() > WebOfTrust.DATABASE_FORMAT_VERSION) throw new RuntimeException("The WoT plugin's database format is newer than the WoT plugin which is being used."); mPuzzleStore = new IntroductionPuzzleStore(this); upgradeDB(); // Please ensure that no threads are using the IntroductionPuzzleStore / IdentityFetcher while this is executing. mXMLTransformer = new XMLTransformer(this); mRequestClient = new RequestClient() { public boolean persistent() { return false; } public void removeFrom(ObjectContainer container) { throw new UnsupportedOperationException(); } public boolean realTimeFlag() { return false; } }; mInserter = new IdentityInserter(this); mFetcher = new IdentityFetcher(this, getPluginRespirator()); // We only do this if debug logging is enabled since the integrity verification cannot repair anything anyway, // if the user does not read his logs there is no need to check the integrity. // TODO: Do this once every few startups and notify the user in the web ui if errors are found. if(logDEBUG) verifyDatabaseIntegrity(); // TODO: Only do this once every few startups once we are certain that score computation does not have any serious bugs. verifyAndCorrectStoredScores(); // Database is up now, integrity is checked. We can start to actually do stuff // TODO: This can be used for doing backups. Implement auto backup, maybe once a week or month //backupDatabase(new File(getUserDataDirectory(), DATABASE_FILENAME + ".backup")); createSeedIdentities(); Logger.normal(this, "Starting fetches of all identities..."); synchronized(this) { synchronized(mFetcher) { for(Identity identity : getAllIdentities()) { if(shouldFetchIdentity(identity)) { try { mFetcher.fetch(identity.getID()); } catch(Exception e) { Logger.error(this, "Fetching identity failed!", e); } } } } } mInserter.start(); mIntroductionServer = new IntroductionServer(this, mFetcher); mIntroductionServer.start(); mIntroductionClient = new IntroductionClient(this); mIntroductionClient.start(); mWebInterface = new WebInterface(this, SELF_URI); mFCPInterface = new FCPInterface(this); Logger.normal(this, "Web Of Trust plugin starting up completed."); } catch(RuntimeException e){ Logger.error(this, "Error during startup", e); /* We call it so the database is properly closed */ terminate(); throw e; } } /** * Constructor for being used by the node and unit tests. Does not do anything. */ public WebOfTrust() { } /** * Constructor which does not generate an IdentityFetcher, IdentityInster, IntroductionPuzzleStore, user interface, etc. * For use by the unit tests to be able to run WoT without a node. * @param databaseFilename The filename of the database. */ public WebOfTrust(String databaseFilename) { mDB = openDatabase(new File(databaseFilename)); mConfig = getOrCreateConfig(); if(mConfig.getDatabaseFormatVersion() != WebOfTrust.DATABASE_FORMAT_VERSION) throw new RuntimeException("Database format version mismatch. Found: " + mConfig.getDatabaseFormatVersion() + "; expected: " + WebOfTrust.DATABASE_FORMAT_VERSION); mPuzzleStore = new IntroductionPuzzleStore(this); mFetcher = new IdentityFetcher(this, null); } private File getUserDataDirectory() { final File wotDirectory = new File(mPR.getNode().getUserDir(), WOT_NAME); if(!wotDirectory.exists() && !wotDirectory.mkdir()) throw new RuntimeException("Unable to create directory " + wotDirectory); return wotDirectory; } private com.db4o.config.Configuration getNewDatabaseConfiguration() { com.db4o.config.Configuration cfg = Db4o.newConfiguration(); // Required config options: cfg.reflectWith(new JdkReflector(getPluginClassLoader())); // TODO: Optimization: We do explicit activation everywhere. We could change this to 0 and test whether everything still works. // Ideally, we would benchmark both 0 and 1 and make it configurable. cfg.activationDepth(1); cfg.updateDepth(1); // This must not be changed: We only activate(this, 1) before store(this). Logger.normal(this, "Default activation depth: " + cfg.activationDepth()); cfg.exceptionsOnNotStorable(true); // The shutdown hook does auto-commit. We do NOT want auto-commit: if a transaction hasn't commit()ed, it's not safe to commit it. cfg.automaticShutDown(false); // Performance config options: cfg.callbacks(false); // We don't use callbacks yet. TODO: Investigate whether we might want to use them cfg.classActivationDepthConfigurable(false); // Registration of indices (also performance) // ATTENTION: Also update cloneDatabase() when adding new classes! @SuppressWarnings("unchecked") final Class<? extends Persistent>[] persistentClasses = new Class[] { Configuration.class, Identity.class, OwnIdentity.class, Trust.class, Score.class, IdentityFetcher.IdentityFetcherCommand.class, IdentityFetcher.AbortFetchCommand.class, IdentityFetcher.StartFetchCommand.class, IdentityFetcher.UpdateEditionHintCommand.class, IntroductionPuzzle.class, OwnIntroductionPuzzle.class }; for(Class<? extends Persistent> clazz : persistentClasses) { boolean classHasIndex = clazz.getAnnotation(Persistent.IndexedClass.class) != null; // TODO: We enable class indexes for all classes to make sure nothing breaks because it is the db4o default, check whether enabling // them only for the classes where we need them does not cause any harm. classHasIndex = true; if(logDEBUG) Logger.debug(this, "Persistent class: " + clazz.getCanonicalName() + "; hasIndex==" + classHasIndex); // TODO: Make very sure that it has no negative side effects if we disable class indices for some classes // Maybe benchmark in comparison to a database which has class indices enabled for ALL classes. cfg.objectClass(clazz).indexed(classHasIndex); // Check the class' fields for @IndexedField annotations for(Field field : clazz.getDeclaredFields()) { if(field.getAnnotation(Persistent.IndexedField.class) != null) { if(logDEBUG) Logger.debug(this, "Registering indexed field " + clazz.getCanonicalName() + '.' + field.getName()); cfg.objectClass(clazz).objectField(field.getName()).indexed(true); } } // Check whether the class itself has an @IndexedField annotation final Persistent.IndexedField annotation = clazz.getAnnotation(Persistent.IndexedField.class); if(annotation != null) { for(String fieldName : annotation.names()) { if(logDEBUG) Logger.debug(this, "Registering indexed field " + clazz.getCanonicalName() + '.' + fieldName); cfg.objectClass(clazz).objectField(fieldName).indexed(true); } } } // TODO: We should check whether db4o inherits the indexed attribute to child classes, for example for this one: // Unforunately, db4o does not provide any way to query the indexed() property of fields, you can only set it // We might figure out whether inheritance works by writing a benchmark. return cfg; } private synchronized void restoreDatabaseBackup(File databaseFile, File backupFile) throws IOException { Logger.warning(this, "Trying to restore database backup: " + backupFile.getAbsolutePath()); if(mDB != null) throw new RuntimeException("Database is opened already!"); if(backupFile.exists()) { try { FileUtil.secureDelete(databaseFile, mPR.getNode().fastWeakRandom); } catch(IOException e) { Logger.warning(this, "Deleting of the database failed: " + databaseFile.getAbsolutePath()); } if(backupFile.renameTo(databaseFile)) { Logger.warning(this, "Backup restored!"); } else { throw new IOException("Unable to rename backup file back to database file: " + databaseFile.getAbsolutePath()); } } else { throw new IOException("Cannot restore backup, it does not exist!"); } } private synchronized void defragmentDatabase(File databaseFile) throws IOException { Logger.normal(this, "Defragmenting database ..."); if(mDB != null) throw new RuntimeException("Database is opened already!"); if(mPR == null) { Logger.normal(this, "No PluginRespirator found, probably running as unit test, not defragmenting."); return; } final Random random = mPR.getNode().fastWeakRandom; // Open it first, because defrag will throw if it needs to upgrade the file. { final ObjectContainer database = Db4o.openFile(getNewDatabaseConfiguration(), databaseFile.getAbsolutePath()); // Db4o will throw during defragmentation if new fields were added to classes and we didn't initialize their values on existing // objects before defragmenting. So we just don't defragment if the database format version has changed. final boolean canDefragment = peekDatabaseFormatVersion(this, database.ext()) == WebOfTrust.DATABASE_FORMAT_VERSION; while(!database.close()); if(!canDefragment) { Logger.normal(this, "Not defragmenting, database format version changed!"); return; } if(!databaseFile.exists()) { Logger.error(this, "Database file does not exist after openFile: " + databaseFile.getAbsolutePath()); return; } } final File backupFile = new File(databaseFile.getAbsolutePath() + ".backup"); if(backupFile.exists()) { Logger.error(this, "Not defragmenting database: Backup file exists, maybe the node was shot during defrag: " + backupFile.getAbsolutePath()); return; } final File tmpFile = new File(databaseFile.getAbsolutePath() + ".temp"); FileUtil.secureDelete(tmpFile, random); /* As opposed to the default, BTreeIDMapping uses an on-disk file instead of in-memory for mapping IDs. /* Reduces memory usage during defragmentation while being slower. /* However as of db4o 7.4.63.11890, it is bugged and prevents defragmentation from succeeding for my database, so we don't use it for now. */ final DefragmentConfig config = new DefragmentConfig(databaseFile.getAbsolutePath(), backupFile.getAbsolutePath() // ,new BTreeIDMapping(tmpFile.getAbsolutePath()) ); /* Delete classes which are not known to the classloader anymore - We do NOT do this because: /* - It is buggy and causes exceptions often as of db4o 7.4.63.11890 /* - WOT has always had proper database upgrade code (function upgradeDB()) and does not rely on automatic schema evolution. /* If we need to get rid of certain objects we should do it in the database upgrade code, */ // config.storedClassFilter(new AvailableClassFilter()); config.db4oConfig(getNewDatabaseConfiguration()); try { Defragment.defrag(config); } catch (Exception e) { Logger.error(this, "Defragment failed", e); try { restoreDatabaseBackup(databaseFile, backupFile); return; } catch(IOException e2) { Logger.error(this, "Unable to restore backup", e2); throw new IOException(e); } } final long oldSize = backupFile.length(); final long newSize = databaseFile.length(); if(newSize <= 0) { Logger.error(this, "Defrag produced an empty file! Trying to restore old database file..."); databaseFile.delete(); try { restoreDatabaseBackup(databaseFile, backupFile); } catch(IOException e2) { Logger.error(this, "Unable to restore backup", e2); throw new IOException(e2); } } else { final double change = 100.0 * (((double)(oldSize - newSize)) / ((double)oldSize)); FileUtil.secureDelete(tmpFile, random); FileUtil.secureDelete(backupFile, random); Logger.normal(this, "Defragment completed. "+SizeUtil.formatSize(oldSize)+" ("+oldSize+") -> " +SizeUtil.formatSize(newSize)+" ("+newSize+") ("+(int)change+"% shrink)"); } } /** * ATTENTION: This function is duplicated in the Freetalk plugin, please backport any changes. * * Initializes the plugin's db4o database. */ private synchronized ExtObjectContainer openDatabase(File file) { Logger.normal(this, "Opening database using db4o " + Db4o.version()); if(mDB != null) throw new RuntimeException("Database is opened already!"); try { defragmentDatabase(file); } catch (IOException e) { throw new RuntimeException(e); } return Db4o.openFile(getNewDatabaseConfiguration(), file.getAbsolutePath()).ext(); } /** * ATTENTION: Please ensure that no threads are using the IntroductionPuzzleStore / IdentityFetcher while this is executing. * It doesn't synchronize on the IntroductionPuzzleStore and IdentityFetcher because it assumes that they are not being used yet. * (I didn't upgrade this function to do the locking because it would be much work to test the changes for little benefit) */ @SuppressWarnings("deprecation") private synchronized void upgradeDB() { int databaseVersion = mConfig.getDatabaseFormatVersion(); if(databaseVersion == WebOfTrust.DATABASE_FORMAT_VERSION) return; // Insert upgrade code here. See Freetalk.java for a skeleton. if(databaseVersion == 1) { Logger.normal(this, "Upgrading database version " + databaseVersion); //synchronized(this) { // Already done at function level //synchronized(mPuzzleStore) { // Normally would be needed for deleteWithoutCommit(Identity) but IntroductionClient/Server are not running yet //synchronized(mFetcher) { // Normally would be needed for deleteWithoutCommit(Identity) but the IdentityFetcher is not running yet synchronized(Persistent.transactionLock(mDB)) { try { Logger.normal(this, "Generating Score IDs..."); for(Score score : getAllScores()) { score.generateID(); score.storeWithoutCommit(); } Logger.normal(this, "Generating Trust IDs..."); for(Trust trust : getAllTrusts()) { trust.generateID(); trust.storeWithoutCommit(); } Logger.normal(this, "Searching for identities with mixed up insert/request URIs..."); for(Identity identity : getAllIdentities()) { try { USK.create(identity.getRequestURI()); } catch (MalformedURLException e) { if(identity instanceof OwnIdentity) { Logger.error(this, "Insert URI specified as request URI for OwnIdentity, not correcting the URIs as the insert URI" + "might have been published by solving captchas - the identity could be compromised: " + identity); } else { Logger.error(this, "Insert URI specified as request URI for non-own Identity, deleting: " + identity); deleteWithoutCommit(identity); } } } mConfig.setDatabaseFormatVersion(++databaseVersion); mConfig.storeAndCommit(); Logger.normal(this, "Upgraded database to version " + databaseVersion); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } //} } if(databaseVersion != WebOfTrust.DATABASE_FORMAT_VERSION) throw new RuntimeException("Your database is too outdated to be upgraded automatically, please create a new one by deleting " + DATABASE_FILENAME + ". Contact the developers if you really need your old data."); } /** * DO NOT USE THIS FUNCTION ON A DATABASE WHICH YOU WANT TO CONTINUE TO USE! * * Debug function for finding object leaks in the database. * * - Deletes all identities in the database - This should delete ALL objects in the database. * - Then it checks for whether any objects still exist - those are leaks. */ private synchronized void checkForDatabaseLeaks() { Logger.normal(this, "Checking for database leaks... This will delete all identities!"); { Logger.debug(this, "Checking FetchState leakage..."); final Query query = mDB.query(); query.constrain(FetchState.class); @SuppressWarnings("unchecked") ObjectSet<FetchState> result = (ObjectSet<FetchState>)query.execute(); for(FetchState state : result) { Logger.debug(this, "Checking " + state); final Query query2 = mDB.query(); query2.constrain(Identity.class); query.descend("mCurrentEditionFetchState").constrain(state).identity(); @SuppressWarnings("unchecked") ObjectSet<FetchState> result2 = (ObjectSet<FetchState>)query.execute(); switch(result2.size()) { case 0: Logger.error(this, "Found leaked FetchState!"); break; case 1: break; default: Logger.error(this, "Found re-used FetchState, count: " + result2.size()); break; } } Logger.debug(this, "Finished checking FetchState leakage, amount:" + result.size()); } Logger.normal(this, "Deleting ALL identities..."); synchronized(mPuzzleStore) { synchronized(mFetcher) { synchronized(Persistent.transactionLock(mDB)) { try { beginTrustListImport(); for(Identity identity : getAllIdentities()) { deleteWithoutCommit(identity); } finishTrustListImport(); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } Logger.normal(this, "Deleting ALL identities finished."); Query query = mDB.query(); query.constrain(Object.class); @SuppressWarnings("unchecked") ObjectSet<Object> result = query.execute(); for(Object leak : result) { Logger.error(this, "Found leaked object: " + leak); } Logger.warning(this, "Finished checking for database leaks. This database is empty now, delete it."); } private synchronized boolean verifyDatabaseIntegrity() { deleteDuplicateObjects(); deleteOrphanObjects(); Logger.debug(this, "Testing database integrity..."); final Query q = mDB.query(); q.constrain(Persistent.class); boolean result = true; for(final Persistent p : new Persistent.InitializingObjectSet<Persistent>(this, q)) { try { p.startupDatabaseIntegrityTest(); } catch(Exception e) { result = false; try { Logger.error(this, "Integrity test failed for " + p, e); } catch(Exception e2) { Logger.error(this, "Integrity test failed for Persistent of class " + p.getClass(), e); Logger.error(this, "Exception thrown by toString() was:", e2); } } } Logger.debug(this, "Database integrity test finished."); return result; } /** * Does not do proper synchronization! Only use it in single-thread-mode during startup. * * Does a backup of the database using db4o's backup mechanism. * * This will NOT fix corrupted internal structures of databases - use cloneDatabase if you need to fix your database. */ private synchronized void backupDatabase(File newDatabase) { Logger.normal(this, "Backing up database to " + newDatabase.getAbsolutePath()); if(newDatabase.exists()) throw new RuntimeException("Target exists already: " + newDatabase.getAbsolutePath()); WebOfTrust backup = null; boolean success = false; try { mDB.backup(newDatabase.getAbsolutePath()); if(logDEBUG) { backup = new WebOfTrust(newDatabase.getAbsolutePath()); // We do not throw to make the clone mechanism more robust in case it is being used for creating backups Logger.debug(this, "Checking database integrity of clone..."); if(backup.verifyDatabaseIntegrity()) Logger.debug(this, "Checking database integrity of clone finished."); else Logger.error(this, "Database integrity check of clone failed!"); Logger.debug(this, "Checking this.equals(clone)..."); if(equals(backup)) Logger.normal(this, "Clone is equal!"); else Logger.error(this, "Clone is not equal!"); } success = true; } finally { if(backup != null) backup.terminate(); if(!success) newDatabase.delete(); } Logger.normal(this, "Backing up database finished."); } /** * Does not do proper synchronization! Only use it in single-thread-mode during startup. * * Creates a clone of the source database by reading all objects of it into memory and then writing them out to the target database. * Does NOT copy the Configuration, the IntroductionPuzzles or the IdentityFetcher command queue. * * The difference to backupDatabase is that it does NOT use db4o's backup mechanism, instead it creates the whole database from scratch. * This is useful because the backup mechanism of db4o does nothing but copying the raw file: * It wouldn't fix databases which cannot be defragmented anymore due to internal corruption. * - Databases which were cloned by this function CAN be defragmented even if the original database couldn't. * * HOWEVER this function uses lots of memory as the whole database is copied into memory. */ private synchronized void cloneDatabase(File sourceDatabase, File targetDatabase) { Logger.normal(this, "Cloning " + sourceDatabase.getAbsolutePath() + " to " + targetDatabase.getAbsolutePath()); if(targetDatabase.exists()) throw new RuntimeException("Target exists already: " + targetDatabase.getAbsolutePath()); WebOfTrust original = null; WebOfTrust clone = null; boolean success = false; try { original = new WebOfTrust(sourceDatabase.getAbsolutePath()); // We need to copy all objects into memory and then close & unload the source database before writing the objects to the target one. // - I tried implementing this function in a way where it directly takes the objects from the source database and stores them // in the target database while the source is still open. This did not work: Identity objects disappeared magically, resulting // in Trust objects .storeWithoutCommit throwing "Mandatory object not found" on their associated identities. final HashSet<Identity> allIdentities = new HashSet<Identity>(original.getAllIdentities()); final HashSet<Trust> allTrusts = new HashSet<Trust>(original.getAllTrusts()); final HashSet<Score> allScores = new HashSet<Score>(original.getAllScores()); for(Identity identity : allIdentities) { identity.checkedActivate(16); identity.mWebOfTrust = null; identity.mDB = null; } for(Trust trust : allTrusts) { trust.checkedActivate(16); trust.mWebOfTrust = null; trust.mDB = null; } for(Score score : allScores) { score.checkedActivate(16); score.mWebOfTrust = null; score.mDB = null; } original.terminate(); original = null; System.gc(); // Now we write out the in-memory copies ... clone = new WebOfTrust(targetDatabase.getAbsolutePath()); for(Identity identity : allIdentities) { identity.initializeTransient(clone); identity.storeWithoutCommit(); } Persistent.checkedCommit(clone.getDatabase(), clone); for(Trust trust : allTrusts) { trust.initializeTransient(clone); trust.storeWithoutCommit(); } Persistent.checkedCommit(clone.getDatabase(), clone); for(Score score : allScores) { score.initializeTransient(clone); score.storeWithoutCommit(); } Persistent.checkedCommit(clone.getDatabase(), clone); // And because cloning is a complex operation we do a mandatory database integrity check Logger.normal(this, "Checking database integrity of clone..."); if(clone.verifyDatabaseIntegrity()) Logger.normal(this, "Checking database integrity of clone finished."); else throw new RuntimeException("Database integrity check of clone failed!"); // ... and also test whether the Web Of Trust is equals() to the clone. This does a deep check of all identities, scores & trusts! original = new WebOfTrust(sourceDatabase.getAbsolutePath()); Logger.normal(this, "Checking original.equals(clone)..."); if(original.equals(clone)) Logger.normal(this, "Clone is equal!"); else throw new RuntimeException("Clone is not equal!"); success = true; } finally { if(original != null) original.terminate(); if(clone != null) clone.terminate(); if(!success) targetDatabase.delete(); } Logger.normal(this, "Cloning database finished."); } /** * Recomputes the {@link Score} of all identities and checks whether the score which is stored in the database is correct. * Incorrect scores are corrected & stored. * * The function is synchronized and does a transaction, no outer synchronization is needed. * ATTENTION: It is NOT synchronized on the IntroductionPuzzleStore or the IdentityFetcher. They must NOT be running yet when using this function! */ protected synchronized void verifyAndCorrectStoredScores() { Logger.normal(this, "Veriying all stored scores ..."); synchronized(Persistent.transactionLock(mDB)) { try { computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } Logger.normal(this, "Veriying all stored scores finished."); } /** * Debug function for deleting duplicate identities etc. which might have been created due to bugs :) */ private synchronized void deleteDuplicateObjects() { synchronized(mPuzzleStore) { // Needed for deleteIdentity() synchronized(mFetcher) { // // Needed for deleteIdentity() synchronized(Persistent.transactionLock(mDB)) { try { HashSet<String> deleted = new HashSet<String>(); if(logDEBUG) Logger.debug(this, "Searching for duplicate identities ..."); for(Identity identity : getAllIdentities()) { Query q = mDB.query(); q.constrain(Identity.class); q.descend("mID").constrain(identity.getID()); q.constrain(identity).identity().not(); ObjectSet<Identity> duplicates = new Persistent.InitializingObjectSet<Identity>(this, q); for(Identity duplicate : duplicates) { if(deleted.contains(duplicate.getID()) == false) { Logger.error(duplicate, "Deleting duplicate identity " + duplicate.getRequestURI()); deleteWithoutCommit(duplicate); Persistent.checkedCommit(mDB, this); } } deleted.add(identity.getID()); } Persistent.checkedCommit(mDB, this); if(logDEBUG) Logger.debug(this, "Finished searching for duplicate identities."); } catch(RuntimeException e) { Persistent.checkedRollback(mDB, this, e); } } } } // synchronized(this) { // For removeTrustWithoutCommit. Done at function level already. synchronized(mFetcher) { // For removeTrustWithoutCommit synchronized(Persistent.transactionLock(mDB)) { try { if(logDEBUG) Logger.debug(this, "Searching for duplicate Trust objects ..."); boolean duplicateTrustFound = false; for(OwnIdentity truster : getAllOwnIdentities()) { HashSet<String> givenTo = new HashSet<String>(); for(Trust trust : getGivenTrusts(truster)) { if(givenTo.contains(trust.getTrustee().getID()) == false) givenTo.add(trust.getTrustee().getID()); else { Logger.error(this, "Deleting duplicate given trust:" + trust); removeTrustWithoutCommit(trust); duplicateTrustFound = true; } } } if(duplicateTrustFound) { computeAllScoresWithoutCommit(); } Persistent.checkedCommit(mDB, this); if(logDEBUG) Logger.debug(this, "Finished searching for duplicate trust objects."); } catch(RuntimeException e) { Persistent.checkedRollback(mDB, this, e); } } // synchronized(Persistent.transactionLock(mDB)) { } // synchronized(mFetcher) { /* TODO: Also delete duplicate score */ } /** * Debug function for deleting trusts or scores of which one of the involved partners is missing. */ private synchronized void deleteOrphanObjects() { synchronized(Persistent.transactionLock(mDB)) { try { boolean orphanTrustFound = false; Query q = mDB.query(); q.constrain(Trust.class); q.descend("mTruster").constrain(null).identity().or(q.descend("mTrustee").constrain(null).identity()); ObjectSet<Trust> orphanTrusts = new Persistent.InitializingObjectSet<Trust>(this, q); for(Trust trust : orphanTrusts) { if(trust.getTruster() != null && trust.getTrustee() != null) { // TODO: Remove this workaround for the db4o bug as soon as we are sure that it does not happen anymore. Logger.error(this, "Db4o bug: constrain(null).identity() did not work for " + trust); continue; } Logger.error(trust, "Deleting orphan trust, truster = " + trust.getTruster() + ", trustee = " + trust.getTrustee()); orphanTrustFound = true; trust.deleteWithoutCommit(); } if(orphanTrustFound) { computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); } } catch(Exception e) { Persistent.checkedRollback(mDB, this, e); } } synchronized(Persistent.transactionLock(mDB)) { try { boolean orphanScoresFound = false; Query q = mDB.query(); q.constrain(Score.class); q.descend("mTruster").constrain(null).identity().or(q.descend("mTrustee").constrain(null).identity()); ObjectSet<Score> orphanScores = new Persistent.InitializingObjectSet<Score>(this, q); for(Score score : orphanScores) { if(score.getTruster() != null && score.getTrustee() != null) { // TODO: Remove this workaround for the db4o bug as soon as we are sure that it does not happen anymore. Logger.error(this, "Db4o bug: constrain(null).identity() did not work for " + score); continue; } Logger.error(score, "Deleting orphan score, truster = " + score.getTruster() + ", trustee = " + score.getTrustee()); orphanScoresFound = true; score.deleteWithoutCommit(); } if(orphanScoresFound) { computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); } } catch(Exception e) { Persistent.checkedRollback(mDB, this, e); } } } /** * Warning: This function is not synchronized, use it only in single threaded mode. * @return The WOT database format version of the given database. -1 if there is no Configuration stored in it or multiple configurations exist. */ @SuppressWarnings("deprecation") private static int peekDatabaseFormatVersion(WebOfTrust wot, ExtObjectContainer database) { final Query query = database.query(); query.constrain(Configuration.class); @SuppressWarnings("unchecked") ObjectSet<Configuration> result = (ObjectSet<Configuration>)query.execute(); switch(result.size()) { case 1: { final Configuration config = (Configuration)result.next(); config.initializeTransient(wot, database); // For the HashMaps to stay alive we need to activate to full depth. config.checkedActivate(4); return config.getDatabaseFormatVersion(); } default: return -1; } } /** * Loads an existing Config object from the database and adds any missing default values to it, creates and stores a new one if none exists. * @return The config object. */ private synchronized Configuration getOrCreateConfig() { final Query query = mDB.query(); query.constrain(Configuration.class); final ObjectSet<Configuration> result = new Persistent.InitializingObjectSet<Configuration>(this, query); switch(result.size()) { case 1: { final Configuration config = result.next(); // For the HashMaps to stay alive we need to activate to full depth. config.checkedActivate(4); config.setDefaultValues(false); config.storeAndCommit(); return config; } case 0: { final Configuration config = new Configuration(this); config.initializeTransient(this); config.storeAndCommit(); return config; } default: throw new RuntimeException("Multiple config objects found: " + result.size()); } } /** Capacity is the maximum amount of points an identity can give to an other by trusting it. * * Values choice : * Advogato Trust metric recommends that values decrease by rounded 2.5 times. * This makes sense, making the need of 3 N+1 ranked people to overpower * the trust given by a N ranked identity. * * Number of ranks choice : * When someone creates a fresh identity, he gets the seed identity at * rank 1 and freenet developpers at rank 2. That means that * he will see people that were : * - given 7 trust by freenet devs (rank 2) * - given 17 trust by rank 3 * - given 50 trust by rank 4 * - given 100 trust by rank 5 and above. * This makes the range small enough to avoid a newbie * to even see spam, and large enough to make him see a reasonnable part * of the community right out-of-the-box. * Of course, as soon as he will start to give trust, he will put more * people at rank 1 and enlarge his WoT. */ protected static final int capacities[] = { 100,// Rank 0 : Own identities 40, // Rank 1 : Identities directly trusted by ownIdenties 16, // Rank 2 : Identities trusted by rank 1 identities 6, // So on... 2, 1 // Every identity above rank 5 can give 1 point }; // Identities with negative score have zero capacity /** * Computes the capacity of a truster. The capacity is a weight function in percent which is used to decide how much * trust points an identity can add to the score of identities which it has assigned trust values to. * The higher the rank of an identity, the less is it's capacity. * * If the rank of the identity is Integer.MAX_VALUE (infinite, this means it has only received negative or 0 trust values from identities with rank >= 0 and less * than infinite) or -1 (this means that it has only received trust values from identities with infinite rank) then its capacity is 0. * * If the truster has assigned a trust value to the trustee the capacity will be computed only from that trust value: * The decision of the truster should always overpower the view of remote identities. * * Notice that 0 is included in infinite rank to prevent identities which have only solved introduction puzzles from having a capacity. * * @param truster The {@link OwnIdentity} in whose trust tree the capacity shall be computed * @param trustee The {@link Identity} of which the capacity shall be computed. * @param rank The rank of the identity. The rank is the distance in trust steps from the OwnIdentity which views the web of trust, * - its rank is 0, the rank of its trustees is 1 and so on. Must be -1 if the truster has no rank in the tree owners view. */ protected int computeCapacity(OwnIdentity truster, Identity trustee, int rank) { if(truster == trustee) return 100; try { if(getTrust(truster, trustee).getValue() <= 0) { // Security check, if rank computation breaks this will hit. assert(rank == Integer.MAX_VALUE); return 0; } } catch(NotTrustedException e) { } if(rank == -1 || rank == Integer.MAX_VALUE) return 0; return (rank < capacities.length) ? capacities[rank] : 1; } /** * Reference-implementation of score computation. This means:<br /> * - It is not used by the real WoT code because its slow<br /> * - It is used by unit tests (and WoT) to check whether the real implementation works<br /> * - It is the function which you should read if you want to understand how WoT works.<br /> * * Computes all rank and score values and checks whether the database is correct. If wrong values are found, they are correct.<br /> * * There was a bug in the score computation for a long time which resulted in wrong computation when trust values very removed under certain conditions.<br /> * * Further, rank values are shortest paths and the path-finding algorithm is not executed from the source * to the target upon score computation: It uses the rank of the neighbor nodes to find a shortest path. * Therefore, the algorithm is very vulnerable to bugs since one wrong value will stay in the database * and affect many others. So it is useful to have this function. * * @return True if all stored scores were correct. False if there were any errors in stored scores. */ protected synchronized boolean computeAllScoresWithoutCommit() { if(logMINOR) Logger.minor(this, "Doing a full computation of all Scores..."); final long beginTime = CurrentTimeUTC.getInMillis(); boolean returnValue = true; final ObjectSet<Identity> allIdentities = getAllIdentities(); // Scores are a rating of an identity from the view of an OwnIdentity so we compute them per OwnIdentity. for(OwnIdentity treeOwner : getAllOwnIdentities()) { // At the end of the loop body, this table will be filled with the ranks of all identities which are visible for treeOwner. // An identity is visible if there is a trust chain from the owner to it. // The rank is the distance in trust steps from the treeOwner. // So the treeOwner is rank 0, the trustees of the treeOwner are rank 1 and so on. final HashMap<Identity, Integer> rankValues = new HashMap<Identity, Integer>(allIdentities.size() * 2); // Compute the rank values { // For each identity which is added to rankValues, all its trustees are added to unprocessedTrusters. // The inner loop then pulls out one unprocessed identity and computes the rank of its trustees: // All trustees which have received positive (> 0) trust will get his rank + 1 // Trustees with negative trust or 0 trust will get a rank of Integer.MAX_VALUE. // Trusters with rank Integer.MAX_VALUE cannot inherit their rank to their trustees so the trustees will get no rank at all. // Identities with no rank are considered to be not in the trust tree of the own identity and their score will be null / none. // // Further, if the treeOwner has assigned a trust value to an identity, the rank decision is done by only considering this trust value: // The decision of the own identity shall not be overpowered by the view of the remote identities. // // The purpose of differentiation between Integer.MAX_VALUE and -1 is: // Score objects of identities with rank Integer.MAX_VALUE are kept in the database because WoT will usually "hear" about those identities by seeing // them in the trust lists of trusted identities (with 0 or negative trust values). So it must store the trust values to those identities and // have a way of telling the user "this identity is not trusted" by keeping a score object of them. // Score objects of identities with rank -1 are deleted because they are the trustees of distrusted identities and we will not get to the point where // we hear about those identities because the only way of hearing about them is importing a trust list of a identity with Integer.MAX_VALUE rank // - and we never import their trust lists. // We include trust values of 0 in the set of rank Integer.MAX_VALUE (instead of only NEGATIVE trust) so that identities which only have solved // introduction puzzles cannot inherit their rank to their trustees. final LinkedList<Identity> unprocessedTrusters = new LinkedList<Identity>(); // The own identity is the root of the trust tree, it should assign itself a rank of 0 , a capacity of 100 and a symbolic score of Integer.MAX_VALUE try { Score selfScore = getScore(treeOwner, treeOwner); if(selfScore.getRank() >= 0) { // It can only give it's rank if it has a valid one rankValues.put(treeOwner, selfScore.getRank()); unprocessedTrusters.addLast(treeOwner); } else { rankValues.put(treeOwner, null); } } catch(NotInTrustTreeException e) { // This only happens in unit tests. } while(!unprocessedTrusters.isEmpty()) { final Identity truster = unprocessedTrusters.removeFirst(); final Integer trusterRank = rankValues.get(truster); // The truster cannot give his rank to his trustees because he has none (or infinite), they receive no rank at all. if(trusterRank == null || trusterRank == Integer.MAX_VALUE) { // (Normally this does not happen because we do not enqueue the identities if they have no rank but we check for security) continue; } final int trusteeRank = trusterRank + 1; for(Trust trust : getGivenTrusts(truster)) { final Identity trustee = trust.getTrustee(); final Integer oldTrusteeRank = rankValues.get(trustee); if(oldTrusteeRank == null) { // The trustee was not processed yet if(trust.getValue() > 0) { rankValues.put(trustee, trusteeRank); unprocessedTrusters.addLast(trustee); } else rankValues.put(trustee, Integer.MAX_VALUE); } else { // Breadth first search will process all rank one identities are processed before any rank two identities, etc. assert(oldTrusteeRank == Integer.MAX_VALUE || trusteeRank >= oldTrusteeRank); if(oldTrusteeRank == Integer.MAX_VALUE) { // If we found a rank less than infinite we can overwrite the old rank with this one, but only if the infinite rank was not // given by the tree owner. try { final Trust treeOwnerTrust = getTrust(treeOwner, trustee); assert(treeOwnerTrust.getValue() <= 0); // TODO: Is this correct? } catch(NotTrustedException e) { if(trust.getValue() > 0) { rankValues.put(trustee, trusteeRank); unprocessedTrusters.addLast(trustee); } } } } } } } // Rank values of all visible identities are computed now. // Next step is to compute the scores of all identities for(Identity target : allIdentities) { // The score of an identity is the sum of all weighted trust values it has received. // Each trust value is weighted with the capacity of the truster - the capacity decays with increasing rank. Integer targetScore; final Integer targetRank = rankValues.get(target); if(targetRank == null) { targetScore = null; } else { // The treeOwner trusts himself. if(targetRank == 0) { targetScore = Integer.MAX_VALUE; } else { // If the treeOwner has assigned a trust value to the target, it always overrides the "remote" score. try { targetScore = (int)getTrust(treeOwner, target).getValue(); } catch(NotTrustedException e) { targetScore = 0; for(Trust receivedTrust : getReceivedTrusts(target)) { final Identity truster = receivedTrust.getTruster(); final Integer trusterRank = rankValues.get(truster); // The capacity is a weight function for trust values which are given from an identity: // The higher the rank, the less the capacity. // If the rank is Integer.MAX_VALUE (infinite) or -1 (no rank at all) the capacity will be 0. final int capacity = computeCapacity(treeOwner, truster, trusterRank != null ? trusterRank : -1); targetScore += (receivedTrust.getValue() * capacity) / 100; } } } } Score newScore = null; if(targetScore != null) { newScore = new Score(this, treeOwner, target, targetScore, targetRank, computeCapacity(treeOwner, target, targetRank)); } boolean needToCheckFetchStatus = false; boolean oldShouldFetch = false; int oldCapacity = 0; // Now we have the rank and the score of the target computed and can check whether the database-stored score object is correct. try { Score currentStoredScore = getScore(treeOwner, target); oldCapacity = currentStoredScore.getCapacity(); if(newScore == null) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: The identity has no rank and should have no score but score was " + currentStoredScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); currentStoredScore.deleteWithoutCommit(); } else { if(!newScore.equals(currentStoredScore)) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: Should have been " + newScore + " but was " + currentStoredScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); currentStoredScore.setRank(newScore.getRank()); currentStoredScore.setCapacity(newScore.getCapacity()); currentStoredScore.setValue(newScore.getScore()); currentStoredScore.storeWithoutCommit(); } } } catch(NotInTrustTreeException e) { oldCapacity = 0; if(newScore != null) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: No score was stored for the identity but it should be " + newScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); newScore.storeWithoutCommit(); } } if(needToCheckFetchStatus) { // If fetch status changed from false to true, we need to start fetching it // If the capacity changed from 0 to positive, we need to refetch the current edition: Identities with capacity 0 cannot // cause new identities to be imported from their trust list, capacity > 0 allows this. // If the fetch status changed from true to false, we need to stop fetching it if((!oldShouldFetch || (oldCapacity == 0 && newScore != null && newScore.getCapacity() > 0)) && shouldFetchIdentity(target) ) { if(!oldShouldFetch) if(logDEBUG) Logger.debug(this, "Fetch status changed from false to true, refetching " + target); else if(logDEBUG) Logger.debug(this, "Capacity changed from 0 to " + newScore.getCapacity() + ", refetching" + target); target.markForRefetch(); target.storeWithoutCommit(); mFetcher.storeStartFetchCommandWithoutCommit(target); } else if(oldShouldFetch && !shouldFetchIdentity(target)) { if(logDEBUG) Logger.debug(this, "Fetch status changed from true to false, aborting fetch of " + target); mFetcher.storeAbortFetchCommandWithoutCommit(target); } } } } mFullScoreComputationNeeded = false; ++mFullScoreRecomputationCount; mFullScoreRecomputationMilliseconds += CurrentTimeUTC.getInMillis() - beginTime; if(logMINOR) { Logger.minor(this, "Full score computation finished. Amount: " + mFullScoreRecomputationCount + "; Avg Time:" + getAverageFullScoreRecomputationTime() + "s"); } return returnValue; } private synchronized void createSeedIdentities() { for(String seedURI : SEED_IDENTITIES) { Identity seed; synchronized(Persistent.transactionLock(mDB)) { try { seed = getIdentityByURI(seedURI); if(seed instanceof OwnIdentity) { OwnIdentity ownSeed = (OwnIdentity)seed; ownSeed.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); ownSeed.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.SEED_IDENTITY_PUZZLE_COUNT)); ownSeed.storeAndCommit(); } else { try { seed.setEdition(new FreenetURI(seedURI).getEdition()); seed.storeAndCommit(); } catch(InvalidParameterException e) { /* We already have the latest edition stored */ } } } catch (UnknownIdentityException uie) { try { seed = new Identity(this, seedURI, null, true); // We have to explicitely set the edition number because the constructor only considers the given edition as a hint. seed.setEdition(new FreenetURI(seedURI).getEdition()); seed.storeAndCommit(); } catch (Exception e) { Logger.error(this, "Seed identity creation error", e); } } catch (Exception e) { Persistent.checkedRollback(mDB, this, e); } } } } public void terminate() { if(logDEBUG) Logger.debug(this, "WoT plugin terminating ..."); /* We use single try/catch blocks so that failure of termination of one service does not prevent termination of the others */ try { if(mWebInterface != null) this.mWebInterface.unload(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mIntroductionClient != null) mIntroductionClient.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mIntroductionServer != null) mIntroductionServer.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mInserter != null) mInserter.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mFetcher != null) mFetcher.stop(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mDB != null) { /* TODO: At 2009-06-15, it does not seem possible to ask db4o for whether a transaction is pending. * If it becomes possible some day, we should check that here, and log an error if there is an uncommitted transaction. * - All transactions should be committed after obtaining the lock() on the database. */ synchronized(Persistent.transactionLock(mDB)) { System.gc(); mDB.rollback(); System.gc(); mDB.close(); } } } catch(Exception e) { Logger.error(this, "Error during termination.", e); } if(logDEBUG) Logger.debug(this, "WoT plugin terminated."); } /** * Inherited event handler from FredPluginFCP, handled in <code>class FCPInterface</code>. */ public void handle(PluginReplySender replysender, SimpleFieldSet params, Bucket data, int accesstype) { mFCPInterface.handle(replysender, params, data, accesstype); } /** * Loads an own or normal identity from the database, querying on its ID. * * @param id The ID of the identity to load * @return The identity matching the supplied ID. * @throws DuplicateIdentityException if there are more than one identity with this id in the database * @throws UnknownIdentityException if there is no identity with this id in the database */ public synchronized Identity getIdentityByID(String id) throws UnknownIdentityException { final Query query = mDB.query(); query.constrain(Identity.class); query.descend("mID").constrain(id); final ObjectSet<Identity> result = new Persistent.InitializingObjectSet<Identity>(this, query); switch(result.size()) { case 1: return result.next(); case 0: throw new UnknownIdentityException(id); default: throw new DuplicateIdentityException(id, result.size()); } } /** * Gets an OwnIdentity by its ID. * * @param id The unique identifier to query an OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if there is now OwnIdentity with that id */ public synchronized OwnIdentity getOwnIdentityByID(String id) throws UnknownIdentityException { final Query query = mDB.query(); query.constrain(OwnIdentity.class); query.descend("mID").constrain(id); final ObjectSet<OwnIdentity> result = new Persistent.InitializingObjectSet<OwnIdentity>(this, query); switch(result.size()) { case 1: return result.next(); case 0: throw new UnknownIdentityException(id); default: throw new DuplicateIdentityException(id, result.size()); } } /** * Loads an identity from the database, querying on its requestURI (a valid {@link FreenetURI}) * * @param uri The requestURI of the identity * @return The identity matching the supplied requestURI * @throws UnknownIdentityException if there is no identity with this id in the database */ public Identity getIdentityByURI(FreenetURI uri) throws UnknownIdentityException { return getIdentityByID(IdentityID.constructAndValidateFromURI(uri).toString()); } /** * Loads an identity from the database, querying on its requestURI (as String) * * @param uri The requestURI of the identity which will be converted to {@link FreenetURI} * @return The identity matching the supplied requestURI * @throws UnknownIdentityException if there is no identity with this id in the database * @throws MalformedURLException if the requestURI isn't a valid FreenetURI */ public Identity getIdentityByURI(String uri) throws UnknownIdentityException, MalformedURLException { return getIdentityByURI(new FreenetURI(uri)); } /** * Gets an OwnIdentity by its requestURI (a {@link FreenetURI}). * The OwnIdentity's unique identifier is extracted from the supplied requestURI. * * @param uri The requestURI of the desired OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if the OwnIdentity isn't in the database */ public OwnIdentity getOwnIdentityByURI(FreenetURI uri) throws UnknownIdentityException { return getOwnIdentityByID(IdentityID.constructAndValidateFromURI(uri).toString()); } /** * Gets an OwnIdentity by its requestURI (as String). * The given String is converted to {@link FreenetURI} in order to extract a unique id. * * @param uri The requestURI (as String) of the desired OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if the OwnIdentity isn't in the database * @throws MalformedURLException if the supplied requestURI is not a valid FreenetURI */ public OwnIdentity getOwnIdentityByURI(String uri) throws UnknownIdentityException, MalformedURLException { return getOwnIdentityByURI(new FreenetURI(uri)); } /** * Returns all identities that are in the database * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all identities present in the database */ public ObjectSet<Identity> getAllIdentities() { final Query query = mDB.query(); query.constrain(Identity.class); return new Persistent.InitializingObjectSet<Identity>(this, query); } public static enum SortOrder { ByNicknameAscending, ByNicknameDescending, ByScoreAscending, ByScoreDescending, ByLocalTrustAscending, ByLocalTrustDescending } /** * Get a filtered and sorted list of identities. * You have to synchronize on this WoT when calling the function and processing the returned list. */ public ObjectSet<Identity> getAllIdentitiesFilteredAndSorted(OwnIdentity truster, String nickFilter, SortOrder sortInstruction) { Query q = mDB.query(); switch(sortInstruction) { case ByNicknameAscending: q.constrain(Identity.class); q.descend("mNickname").orderAscending(); break; case ByNicknameDescending: q.constrain(Identity.class); q.descend("mNickname").orderDescending(); break; case ByScoreAscending: q.constrain(Score.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderAscending(); q = q.descend("mTrustee"); break; case ByScoreDescending: // TODO: This excludes identities which have no score q.constrain(Score.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderDescending(); q = q.descend("mTrustee"); break; case ByLocalTrustAscending: q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderAscending(); q = q.descend("mTrustee"); break; case ByLocalTrustDescending: // TODO: This excludes untrusted identities. q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderDescending(); q = q.descend("mTrustee"); break; } if(nickFilter != null) { nickFilter = nickFilter.trim(); if(!nickFilter.equals("")) q.descend("mNickname").constrain(nickFilter).like(); } return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all non-own identities that are in the database. * * You have to synchronize on this WoT when calling the function and processing the returned list! */ public ObjectSet<Identity> getAllNonOwnIdentities() { final Query q = mDB.query(); q.constrain(Identity.class); q.constrain(OwnIdentity.class).not(); return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all non-own identities that are in the database, sorted descending by their date of modification, i.e. recently * modified identities will be at the beginning of the list. * * You have to synchronize on this WoT when calling the function and processing the returned list! * * Used by the IntroductionClient for fetching puzzles from recently modified identities. */ public ObjectSet<Identity> getAllNonOwnIdentitiesSortedByModification () { final Query q = mDB.query(); q.constrain(Identity.class); q.constrain(OwnIdentity.class).not(); /* TODO: As soon as identities announce that they were online every day, uncomment the following line */ /* q.descend("mLastChangedDate").constrain(new Date(CurrentTimeUTC.getInMillis() - 1 * 24 * 60 * 60 * 1000)).greater(); */ q.descend("mLastFetchedDate").orderDescending(); return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all own identities that are in the database * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all identities present in the database. */ public ObjectSet<OwnIdentity> getAllOwnIdentities() { final Query q = mDB.query(); q.constrain(OwnIdentity.class); return new Persistent.InitializingObjectSet<OwnIdentity>(this, q); } /** * DO NOT USE THIS FUNCTION FOR DELETING OWN IDENTITIES UPON USER REQUEST! * IN FACT BE VERY CAREFUL WHEN USING IT FOR ANYTHING FOR THE FOLLOWING REASONS: * - This function deletes ALL given and received trust values of the given identity. This modifies the trust list of the trusters against their will. * - Especially it might be an information leak if the trust values of other OwnIdentities are deleted! * - If WOT one day is designed to be used by many different users at once, the deletion of other OwnIdentity's trust values would even be corruption. * * The intended purpose of this function is: * - To specify which objects have to be dealt with when messing with storage of an identity. * - To be able to do database object leakage tests: Many classes have a deleteWithoutCommit function and there are valid usecases for them. * However, the implementations of those functions might cause leaks by forgetting to delete certain object members. * If you call this function for ALL identities in a database, EVERYTHING should be deleted and the database SHOULD be empty. * You then can check whether the database actually IS empty to test for leakage. * * You have to lock the WebOfTrust, the IntroductionPuzzleStore and the IdentityFetcher before calling this function. */ private void deleteWithoutCommit(Identity identity) { // We want to use beginTrustListImport, finishTrustListImport / abortTrustListImport. // If the caller already handles that for us though, we should not call those function again. // So we check whether the caller already started an import. boolean trustListImportWasInProgress = mTrustListImportInProgress; try { if(!trustListImportWasInProgress) beginTrustListImport(); if(logDEBUG) Logger.debug(this, "Deleting identity " + identity + " ..."); if(logDEBUG) Logger.debug(this, "Deleting received scores..."); for(Score score : getScores(identity)) score.deleteWithoutCommit(); if(identity instanceof OwnIdentity) { if(logDEBUG) Logger.debug(this, "Deleting given scores..."); for(Score score : getGivenScores((OwnIdentity)identity)) score.deleteWithoutCommit(); } if(logDEBUG) Logger.debug(this, "Deleting received trusts..."); for(Trust trust : getReceivedTrusts(identity)) trust.deleteWithoutCommit(); if(logDEBUG) Logger.debug(this, "Deleting given trusts..."); for(Trust givenTrust : getGivenTrusts(identity)) { givenTrust.deleteWithoutCommit(); // We call computeAllScores anyway so we do not use removeTrustWithoutCommit() } mFullScoreComputationNeeded = true; // finishTrustListImport will call computeAllScoresWithoutCommit for us. if(logDEBUG) Logger.debug(this, "Deleting associated introduction puzzles ..."); mPuzzleStore.onIdentityDeletion(identity); if(logDEBUG) Logger.debug(this, "Storing an abort-fetch-command..."); if(mFetcher != null) { // Can be null if we use this function in upgradeDB() mFetcher.storeAbortFetchCommandWithoutCommit(identity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. } if(logDEBUG) Logger.debug(this, "Deleting the identity..."); identity.deleteWithoutCommit(); if(!trustListImportWasInProgress) finishTrustListImport(); } catch(RuntimeException e) { if(!trustListImportWasInProgress) abortTrustListImport(e); Persistent.checkedRollbackAndThrow(mDB, this, e); } } /** * Gets the score of this identity in a trust tree. * Each {@link OwnIdentity} has its own trust tree. * * @param truster The owner of the trust tree * @return The {@link Score} of this Identity in the required trust tree * @throws NotInTrustTreeException if this identity is not in the required trust tree */ public synchronized Score getScore(final OwnIdentity truster, final Identity trustee) throws NotInTrustTreeException { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mID").constrain(new ScoreID(truster, trustee).toString()); final ObjectSet<Score> result = new Persistent.InitializingObjectSet<Score>(this, query); switch(result.size()) { case 1: final Score score = result.next(); assert(score.getTruster() == truster); assert(score.getTrustee() == trustee); return score; case 0: throw new NotInTrustTreeException(truster, trustee); default: throw new DuplicateScoreException(truster, trustee, result.size()); } } /** * Gets a list of all this Identity's Scores. * You have to synchronize on this WoT around the call to this function and the processing of the returned list! * * @return An {@link ObjectSet} containing all {@link Score} this Identity has. */ public ObjectSet<Score> getScores(final Identity identity) { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mTrustee").constrain(identity).identity(); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Get a list of all scores which the passed own identity has assigned to other identities. * * You have to synchronize on this WoT around the call to this function and the processing of the returned list! * @return An {@link ObjectSet} containing all {@link Score} this Identity has given. */ public ObjectSet<Score> getGivenScores(final OwnIdentity truster) { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mTruster").constrain(truster).identity(); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Gets the best score this Identity has in existing trust trees. * * @return the best score this Identity has * @throws NotInTrustTreeException If the identity has no score in any trusttree. */ public synchronized int getBestScore(final Identity identity) throws NotInTrustTreeException { int bestScore = Integer.MIN_VALUE; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) throw new NotInTrustTreeException(identity); // TODO: Cache the best score of an identity as a member variable. for(final Score score : scores) bestScore = Math.max(score.getScore(), bestScore); return bestScore; } /** * Gets the best capacity this identity has in any trust tree. * @throws NotInTrustTreeException If the identity is not in any trust tree. Can be interpreted as capacity 0. */ public int getBestCapacity(final Identity identity) throws NotInTrustTreeException { int bestCapacity = 0; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) throw new NotInTrustTreeException(identity); // TODO: Cache the best score of an identity as a member variable. for(final Score score : scores) bestCapacity = Math.max(score.getCapacity(), bestCapacity); return bestCapacity; } /** * Get all scores in the database. * You have to synchronize on this WoT when calling the function and processing the returned list! */ public ObjectSet<Score> getAllScores() { final Query query = mDB.query(); query.constrain(Score.class); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Checks whether the given identity should be downloaded. * @return Returns true if the identity has any capacity > 0, any score >= 0 or if it is an own identity. */ public boolean shouldFetchIdentity(final Identity identity) { if(identity instanceof OwnIdentity) return true; int bestScore = Integer.MIN_VALUE; int bestCapacity = 0; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) return false; // TODO: Cache the best score of an identity as a member variable. for(Score score : scores) { bestCapacity = Math.max(score.getCapacity(), bestCapacity); bestScore = Math.max(score.getScore(), bestScore); if(bestCapacity > 0 || bestScore >= 0) return true; } return false; } /** * Gets non-own Identities matching a specified score criteria. * TODO: Rename to getNonOwnIdentitiesByScore. Or even better: Make it return own identities as well, this will speed up the database query and clients might be ok with it. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param truster The owner of the trust tree, null if you want the trusted identities of all owners. * @param select Score criteria, can be > zero, zero or negative. Greater than zero returns all identities with score >= 0, zero with score equal to 0 * and negative with score < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a trust value of 0. * @return an {@link ObjectSet} containing Scores of the identities that match the criteria */ public ObjectSet<Score> getIdentitiesByScore(final OwnIdentity truster, final int select) { final Query query = mDB.query(); query.constrain(Score.class); if(truster != null) query.descend("mTruster").constrain(truster).identity(); query.descend("mTrustee").constrain(OwnIdentity.class).not(); /* We include 0 in the list of identities with positive score because solving captchas gives no points to score */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Gets {@link Trust} from a specified truster to a specified trustee. * * @param truster The identity that gives trust to this Identity * @param trustee The identity which receives the trust * @return The trust given to the trustee by the specified truster * @throws NotTrustedException if the truster doesn't trust the trustee */ public synchronized Trust getTrust(final Identity truster, final Identity trustee) throws NotTrustedException, DuplicateTrustException { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mID").constrain(new TrustID(truster, trustee).toString()); final ObjectSet<Trust> result = new Persistent.InitializingObjectSet<Trust>(this, query); switch(result.size()) { case 1: final Trust trust = result.next(); assert(trust.getTruster() == truster); assert(trust.getTrustee() == trustee); return trust; case 0: throw new NotTrustedException(truster, trustee); default: throw new DuplicateTrustException(truster, trustee, result.size()); } } /** * Gets all trusts given by the given truster. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has given. */ public ObjectSet<Trust> getGivenTrusts(final Identity truster) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts given by the given truster. * The result is sorted descending by the time we last fetched the trusted identity. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has given. */ public ObjectSet<Trust> getGivenTrustsSortedDescendingByLastSeen(final Identity truster) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); query.descend("mTrustee").descend("mLastFetchedDate").orderDescending(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets given trust values of an identity matching a specified trust value criteria. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param truster The identity which given the trust values. * @param select Trust value criteria, can be > zero, zero or negative. Greater than zero returns all trust values >= 0, zero returns trust values equal to 0. * Negative returns trust values < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a value of 0. * @return an {@link ObjectSet} containing received trust values that match the criteria. */ public ObjectSet<Trust> getGivenTrusts(final Identity truster, final int select) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); /* We include 0 in the list of identities with positive trust because solving captchas gives 0 trust */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0 ) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts given by the given truster in a trust list with a different edition than the passed in one. * You have to synchronize on this WoT when calling the function and processing the returned list! */ protected ObjectSet<Trust> getGivenTrustsOfDifferentEdition(final Identity truster, final long edition) { final Query q = mDB.query(); q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mTrusterTrustListEdition").constrain(edition).not(); return new Persistent.InitializingObjectSet<Trust>(this, q); } /** * Gets all trusts received by the given trustee. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has received. */ public ObjectSet<Trust> getReceivedTrusts(final Identity trustee) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTrustee").constrain(trustee).identity(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets received trust values of an identity matching a specified trust value criteria. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param trustee The identity which has received the trust values. * @param select Trust value criteria, can be > zero, zero or negative. Greater than zero returns all trust values >= 0, zero returns trust values equal to 0. * Negative returns trust values < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a value of 0. * @return an {@link ObjectSet} containing received trust values that match the criteria. */ public ObjectSet<Trust> getReceivedTrusts(final Identity trustee, final int select) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTrustee").constrain(trustee).identity(); /* We include 0 in the list of identities with positive trust because solving captchas gives 0 trust */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0 ) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has received. */ public ObjectSet<Trust> getAllTrusts() { final Query query = mDB.query(); query.constrain(Trust.class); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gives some {@link Trust} to another Identity. * It creates or updates an existing Trust object and make the trustee compute its {@link Score}. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(WebOfTrust.this) { + * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... setTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } - * } - * } + * }}} * * @param truster The Identity that gives the trust * @param trustee The Identity that receives the trust * @param newValue Numeric value of the trust * @param newComment A comment to explain the given value * @throws InvalidParameterException if a given parameter isn't valid, see {@link Trust} for details on accepted values. */ protected void setTrustWithoutCommit(Identity truster, Identity trustee, byte newValue, String newComment) throws InvalidParameterException { try { // Check if we are updating an existing trust value final Trust trust = getTrust(truster, trustee); final Trust oldTrust = trust.clone(); trust.trusterEditionUpdated(); trust.setComment(newComment); trust.storeWithoutCommit(); if(trust.getValue() != newValue) { trust.setValue(newValue); trust.storeWithoutCommit(); if(logDEBUG) Logger.debug(this, "Updated trust value ("+ trust +"), now updating Score."); updateScoresWithoutCommit(oldTrust, trust); } } catch (NotTrustedException e) { final Trust trust = new Trust(this, truster, trustee, newValue, newComment); trust.storeWithoutCommit(); if(logDEBUG) Logger.debug(this, "New trust value ("+ trust +"), now updating Score."); updateScoresWithoutCommit(null, trust); } truster.updated(); truster.storeWithoutCommit(); } /** * Only for being used by WoT internally and by unit tests! */ synchronized void setTrust(OwnIdentity truster, Identity trustee, byte newValue, String newComment) throws InvalidParameterException { synchronized(Persistent.transactionLock(mDB)) { try { setTrustWithoutCommit(truster, trustee, newValue, newComment); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } /** * Deletes a trust object. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... removeTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}} * * @param truster * @param trustee */ protected void removeTrustWithoutCommit(OwnIdentity truster, Identity trustee) { try { try { removeTrustWithoutCommit(getTrust(truster, trustee)); } catch (NotTrustedException e) { Logger.error(this, "Cannot remove trust - there is none - from " + truster.getNickname() + " to " + trustee.getNickname()); } } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } /** * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... setTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}} * */ protected void removeTrustWithoutCommit(Trust trust) { trust.deleteWithoutCommit(); updateScoresWithoutCommit(trust, null); } /** * Initializes this OwnIdentity's trust tree without commiting the transaction. * Meaning : It creates a Score object for this OwnIdentity in its own trust so it can give trust to other Identities. * * The score will have a rank of 0, a capacity of 100 (= 100 percent) and a score value of Integer.MAX_VALUE. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(Persistent.transactionLock(mDB)) { * try { ... initTrustTreeWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * } * * @throws DuplicateScoreException if there already is more than one Score for this identity (should never happen) */ private synchronized void initTrustTreeWithoutCommit(OwnIdentity identity) throws DuplicateScoreException { try { getScore(identity, identity); Logger.error(this, "initTrustTreeWithoutCommit called even though there is already one for " + identity); return; } catch (NotInTrustTreeException e) { final Score score = new Score(this, identity, identity, Integer.MAX_VALUE, 0, 100); score.storeWithoutCommit(); } } /** * Computes the trustee's Score value according to the trusts it has received and the capacity of its trusters in the specified * trust tree. * * @param truster The OwnIdentity that owns the trust tree * @param trustee The identity for which the score shall be computed. * @return The new Score of the identity. Integer.MAX_VALUE if the trustee is equal to the truster. * @throws DuplicateScoreException if there already exist more than one {@link Score} objects for the trustee (should never happen) */ private synchronized int computeScoreValue(OwnIdentity truster, Identity trustee) throws DuplicateScoreException { if(trustee == truster) return Integer.MAX_VALUE; int value = 0; try { return getTrust(truster, trustee).getValue(); } catch(NotTrustedException e) { } for(Trust trust : getReceivedTrusts(trustee)) { try { final Score trusterScore = getScore(truster, trust.getTruster()); value += ( trust.getValue() * trusterScore.getCapacity() ) / 100; } catch (NotInTrustTreeException e) {} } return value; } /** * Computes the trustees's rank in the trust tree of the truster. * It gets its best ranked non-zero-capacity truster's rank, plus one. * If it has only received negative trust values from identities which have a non-zero-capacity it gets a rank of Integer.MAX_VALUE (infinite). * If it has only received trust values from identities with rank of Integer.MAX_VALUE it gets a rank of -1. * * If the tree owner has assigned a trust value to the identity, the rank computation is only done from that value because the score decisions of the * tree owner are always absolute (if you distrust someone, the remote identities should not be allowed to overpower your decision). * * The purpose of differentiation between Integer.MAX_VALUE and -1 is: * Score objects of identities with rank Integer.MAX_VALUE are kept in the database because WoT will usually "hear" about those identities by seeing them * in the trust lists of trusted identities (with negative trust values). So it must store the trust values to those identities and have a way of telling the * user "this identity is not trusted" by keeping a score object of them. * Score objects of identities with rank -1 are deleted because they are the trustees of distrusted identities and we will not get to the point where we * hear about those identities because the only way of hearing about them is downloading a trust list of a identity with Integer.MAX_VALUE rank - and * we never download their trust lists. * * Notice that 0 is included in infinite rank to prevent identities which have only solved introduction puzzles from having a capacity. * * @param truster The OwnIdentity that owns the trust tree * @return The new Rank if this Identity * @throws DuplicateScoreException if there already exist more than one {@link Score} objects for the trustee (should never happen) */ private synchronized int computeRank(OwnIdentity truster, Identity trustee) throws DuplicateScoreException { if(trustee == truster) return 0; int rank = -1; try { Trust treeOwnerTrust = getTrust(truster, trustee); if(treeOwnerTrust.getValue() > 0) return 1; else return Integer.MAX_VALUE; } catch(NotTrustedException e) { } for(Trust trust : getReceivedTrusts(trustee)) { try { Score score = getScore(truster, trust.getTruster()); if(score.getCapacity() != 0) { // If the truster has no capacity, he can't give his rank // A truster only gives his rank to a trustee if he has assigned a strictly positive trust value if(trust.getValue() > 0 ) { // We give the rank to the trustee if it is better than its current rank or he has no rank yet. if(rank == -1 || score.getRank() < rank) rank = score.getRank(); } else { // If the trustee has no rank yet we give him an infinite rank. because he is distrusted by the truster. if(rank == -1) rank = Integer.MAX_VALUE; } } } catch (NotInTrustTreeException e) {} } if(rank == -1) return -1; else if(rank == Integer.MAX_VALUE) return Integer.MAX_VALUE; else return rank+1; } /** * Begins the import of a trust list. This sets a flag on this WoT which signals that the import of a trust list is in progress. * This speeds up setTrust/removeTrust as the score calculation is only performed when endTrustListImport is called. * * You MUST synchronize on this WoT around beginTrustListImport, abortTrustListImport and finishTrustListImport! * You MUST create a database transaction by synchronizing on Persistent.transactionLock(db). */ protected void beginTrustListImport() { if(logMINOR) Logger.minor(this, "beginTrustListImport()"); if(mTrustListImportInProgress) { abortTrustListImport(new RuntimeException("There was already a trust list import in progress!")); mFullScoreComputationNeeded = true; computeAllScoresWithoutCommit(); assert(mFullScoreComputationNeeded == false); } mTrustListImportInProgress = true; assert(!mFullScoreComputationNeeded); assert(computeAllScoresWithoutCommit()); // The database is intact before the import } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * * Aborts the import of a trust list and rolls back the current transaction. * * @param e The exception which triggered the abort. Will be logged to the Freenet log file. * @param logLevel The {@link LogLevel} to use when logging the abort to the Freenet log file. */ protected void abortTrustListImport(Exception e, LogLevel logLevel) { if(logMINOR) Logger.minor(this, "abortTrustListImport()"); assert(mTrustListImportInProgress); mTrustListImportInProgress = false; mFullScoreComputationNeeded = false; Persistent.checkedRollback(mDB, this, e, logLevel); assert(computeAllScoresWithoutCommit()); // Test rollback. } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * * Aborts the import of a trust list and rolls back the current transaction. * * @param e The exception which triggered the abort. Will be logged to the Freenet log file with log level {@link LogLevel.ERROR} */ protected void abortTrustListImport(Exception e) { abortTrustListImport(e, Logger.LogLevel.ERROR); } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * * Finishes the import of the current trust list and clears the "trust list * * Does NOT commit the transaction, you must do this. */ protected void finishTrustListImport() { if(logMINOR) Logger.minor(this, "finishTrustListImport()"); if(!mTrustListImportInProgress) { Logger.error(this, "There was no trust list import in progress!"); return; } if(mFullScoreComputationNeeded) { computeAllScoresWithoutCommit(); assert(!mFullScoreComputationNeeded); // It properly clears the flag assert(computeAllScoresWithoutCommit()); // computeAllScoresWithoutCommit() is stable } else assert(computeAllScoresWithoutCommit()); // Verify whether updateScoresWithoutCommit worked. mTrustListImportInProgress = false; } /** * Updates all trust trees which are affected by the given modified score. * For understanding how score calculation works you should first read {@link computeAllScores * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... updateScoreWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e);; } * }}} */ private void updateScoresWithoutCommit(final Trust oldTrust, final Trust newTrust) { if(logMINOR) Logger.minor(this, "Doing an incremental computation of all Scores..."); final long beginTime = CurrentTimeUTC.getInMillis(); // We only include the time measurement if we actually do something. // If we figure out that a full score recomputation is needed just by looking at the initial parameters, the measurement won't be included. boolean includeMeasurement = false; final boolean trustWasCreated = (oldTrust == null); final boolean trustWasDeleted = (newTrust == null); final boolean trustWasModified = !trustWasCreated && !trustWasDeleted; if(trustWasCreated && trustWasDeleted) throw new NullPointerException("No old/new trust specified."); if(trustWasModified && oldTrust.getTruster() != newTrust.getTruster()) throw new IllegalArgumentException("oldTrust has different truster, oldTrust:" + oldTrust + "; newTrust: " + newTrust); if(trustWasModified && oldTrust.getTrustee() != newTrust.getTrustee()) throw new IllegalArgumentException("oldTrust has different trustee, oldTrust:" + oldTrust + "; newTrust: " + newTrust); // We cannot iteratively REMOVE an inherited rank from the trustees because we don't know whether there is a circle in the trust values // which would make the current identity get its old rank back via the circle: computeRank searches the trusters of an identity for the best // rank, if we remove the rank from an identity, all its trustees will have a better rank and if one of them trusts the original identity // then this function would run into an infinite loop. Decreasing or incrementing an existing rank is possible with this function because // the rank received from the trustees will always be higher (that is exactly 1 more) than this identities rank. if(trustWasDeleted) { mFullScoreComputationNeeded = true; } if(!mFullScoreComputationNeeded && (trustWasCreated || trustWasModified)) { includeMeasurement = true; for(OwnIdentity treeOwner : getAllOwnIdentities()) { try { // Throws to abort the update of the trustee's score: If the truster has no rank or capacity in the tree owner's view then we don't need to update the trustee's score. if(getScore(treeOwner, newTrust.getTruster()).getCapacity() == 0) continue; } catch(NotInTrustTreeException e) { continue; } // See explanation above "We cannot iteratively REMOVE an inherited rank..." if(trustWasModified && oldTrust.getValue() > 0 && newTrust.getValue() <= 0) { mFullScoreComputationNeeded = true; break; } final LinkedList<Trust> unprocessedEdges = new LinkedList<Trust>(); unprocessedEdges.add(newTrust); while(!unprocessedEdges.isEmpty()) { final Trust trust = unprocessedEdges.removeFirst(); final Identity trustee = trust.getTrustee(); if(trustee == treeOwner) continue; Score currentStoredTrusteeScore; try { currentStoredTrusteeScore = getScore(treeOwner, trustee); } catch(NotInTrustTreeException e) { currentStoredTrusteeScore = new Score(this, treeOwner, trustee, 0, -1, 0); } final Score oldScore = currentStoredTrusteeScore.clone(); boolean oldShouldFetch = shouldFetchIdentity(trustee); final int newScoreValue = computeScoreValue(treeOwner, trustee); final int newRank = computeRank(treeOwner, trustee); final int newCapacity = computeCapacity(treeOwner, trustee, newRank); final Score newScore = new Score(this, treeOwner, trustee, newScoreValue, newRank, newCapacity); // Normally we couldn't detect the following two cases due to circular trust values. However, if an own identity assigns a trust value, // the rank and capacity are always computed based on the trust value of the own identity so we must also check this here: if((oldScore.getRank() >= 0 && oldScore.getRank() < Integer.MAX_VALUE) // It had an inheritable rank && (newScore.getRank() == -1 || newScore.getRank() == Integer.MAX_VALUE)) { // It has no inheritable rank anymore mFullScoreComputationNeeded = true; break; } if(oldScore.getCapacity() > 0 && newScore.getCapacity() == 0) { mFullScoreComputationNeeded = true; break; } // We are OK to update it now. We must not update the values of the stored score object before determining whether we need // a full score computation - the full computation needs the old values of the object. currentStoredTrusteeScore.setValue(newScore.getScore()); currentStoredTrusteeScore.setRank(newScore.getRank()); currentStoredTrusteeScore.setCapacity(newScore.getCapacity()); // Identities should not get into the queue if they have no rank, see the large if() about 20 lines below assert(currentStoredTrusteeScore.getRank() >= 0); if(currentStoredTrusteeScore.getRank() >= 0) currentStoredTrusteeScore.storeWithoutCommit(); // If fetch status changed from false to true, we need to start fetching it // If the capacity changed from 0 to positive, we need to refetch the current edition: Identities with capacity 0 cannot // cause new identities to be imported from their trust list, capacity > 0 allows this. // If the fetch status changed from true to false, we need to stop fetching it if((!oldShouldFetch || (oldScore.getCapacity()== 0 && newScore.getCapacity() > 0)) && shouldFetchIdentity(trustee)) { if(!oldShouldFetch) if(logDEBUG) Logger.debug(this, "Fetch status changed from false to true, refetching " + trustee); else if(logDEBUG) Logger.debug(this, "Capacity changed from 0 to " + newScore.getCapacity() + ", refetching" + trustee); trustee.markForRefetch(); trustee.storeWithoutCommit(); mFetcher.storeStartFetchCommandWithoutCommit(trustee); } else if(oldShouldFetch && !shouldFetchIdentity(trustee)) { if(logDEBUG) Logger.debug(this, "Fetch status changed from true to false, aborting fetch of " + trustee); mFetcher.storeAbortFetchCommandWithoutCommit(trustee); } // If the rank or capacity changed then the trustees might be affected because the could have inherited theirs if(oldScore.getRank() != newScore.getRank() || oldScore.getCapacity() != newScore.getCapacity()) { // If this identity has no capacity or no rank then it cannot affect its trustees: // (- If it had none and it has none now then there is none which can be inherited, this is obvious) // - If it had one before and it was removed, this algorithm will have aborted already because a full computation is needed if(newScore.getCapacity() > 0 || (newScore.getRank() >= 0 && newScore.getRank() < Integer.MAX_VALUE)) { // We need to update the trustees of trustee for(Trust givenTrust : getGivenTrusts(trustee)) { unprocessedEdges.add(givenTrust); } } } } if(mFullScoreComputationNeeded) break; } } if(includeMeasurement) { ++mIncrementalScoreRecomputationCount; mIncrementalScoreRecomputationMilliseconds += CurrentTimeUTC.getInMillis() - beginTime; } if(logMINOR) { final String time = includeMeasurement ? ("Stats: Amount: " + mIncrementalScoreRecomputationCount + "; Avg Time:" + getAverageIncrementalScoreRecomputationTime() + "s") : ("Time not measured: Computation was aborted before doing anything."); if(!mFullScoreComputationNeeded) Logger.minor(this, "Incremental computation of all Scores finished. " + time); else Logger.minor(this, "Incremental computation of all Scores not possible, full computation is needed. " + time); } if(!mTrustListImportInProgress) { if(mFullScoreComputationNeeded) { // TODO: Optimization: This uses very much CPU and memory. Write a partial computation function... // TODO: Optimization: While we do not have a partial computation function, we could at least optimize computeAllScores to NOT // keep all objects in memory etc. computeAllScoresWithoutCommit(); assert(computeAllScoresWithoutCommit()); // computeAllScoresWithoutCommit is stable } else { assert(computeAllScoresWithoutCommit()); // This function worked correctly. } } else { // a trust list import is in progress // We not do the following here because it would cause too much CPU usage during debugging: Trust lists are large and therefore // updateScoresWithoutCommit is called often during import of a single trust list // assert(computeAllScoresWithoutCommit()); } } /* Client interface functions */ public synchronized Identity addIdentity(String requestURI) throws MalformedURLException, InvalidParameterException { try { getIdentityByURI(requestURI); throw new InvalidParameterException("We already have this identity"); } catch(UnknownIdentityException e) { final Identity identity = new Identity(this, requestURI, null, false); identity.storeAndCommit(); if(logDEBUG) Logger.debug(this, "Created identity " + identity); // The identity hasn't received a trust value. Therefore, there is no reason to fetch it and we don't notify the IdentityFetcher. // TODO: Document this function and the UI which uses is to warn the user that the identity won't be fetched without trust. return identity; } } public OwnIdentity createOwnIdentity(String nickName, boolean publishTrustList, String context) throws MalformedURLException, InvalidParameterException { FreenetURI[] keypair = getPluginRespirator().getHLSimpleClient().generateKeyPair(WOT_NAME); return createOwnIdentity(keypair[0], nickName, publishTrustList, context); } /** * @param context A context with which you want to use the identity. Null if you want to add it later. */ public synchronized OwnIdentity createOwnIdentity(FreenetURI insertURI, String nickName, boolean publishTrustList, String context) throws MalformedURLException, InvalidParameterException { synchronized(Persistent.transactionLock(mDB)) { OwnIdentity identity; try { identity = getOwnIdentityByURI(insertURI); throw new InvalidParameterException("The URI you specified is already used by the own identity " + identity.getNickname() + "."); } catch(UnknownIdentityException uie) { identity = new OwnIdentity(this, insertURI, nickName, publishTrustList); if(context != null) identity.addContext(context); if(publishTrustList) { identity.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); /* TODO: make configureable */ identity.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.DEFAULT_PUZZLE_COUNT)); } try { identity.storeWithoutCommit(); initTrustTreeWithoutCommit(identity); beginTrustListImport(); // Incremental score computation has proven to be very very slow when creating identities so we just schedule a full computation. mFullScoreComputationNeeded = true; for(String seedURI : SEED_IDENTITIES) { try { setTrustWithoutCommit(identity, getIdentityByURI(seedURI), (byte)100, "Automatically assigned trust to a seed identity."); } catch(UnknownIdentityException e) { Logger.error(this, "SHOULD NOT HAPPEN: Seed identity not known: " + e); } } finishTrustListImport(); Persistent.checkedCommit(mDB, this); if(mIntroductionClient != null) mIntroductionClient.nextIteration(); // This will make it fetch more introduction puzzles. if(logDEBUG) Logger.debug(this, "Successfully created a new OwnIdentity (" + identity.getNickname() + ")"); return identity; } catch(RuntimeException e) { abortTrustListImport(e); // Rolls back for us throw e; // Satisfy the compiler } } } } /** * This "deletes" an {@link OwnIdentity} by replacing it with an {@link Identity}. * * The {@link OwnIdentity} is not deleted because this would be a security issue: * If other {@link OwnIdentity}s have assigned a trust value to it, the trust value would be gone if there is no {@link Identity} object to be the target * * @param id The {@link Identity.IdentityID} of the identity. * @throws UnknownIdentityException If there is no {@link OwnIdentity} with the given ID. Also thrown if a non-own identity exists with the given ID. */ public synchronized void deleteOwnIdentity(String id) throws UnknownIdentityException { Logger.normal(this, "deleteOwnIdentity(): Starting... "); synchronized(mPuzzleStore) { synchronized(mFetcher) { synchronized(Persistent.transactionLock(mDB)) { final OwnIdentity oldIdentity = getOwnIdentityByID(id); try { Logger.normal(this, "Deleting an OwnIdentity by converting it to a non-own Identity: " + oldIdentity); // We don't need any score computations to happen (explanation will follow below) so we don't need the following: /* beginTrustListImport(); */ // This function messes with the score graph manually so it is a good idea to check whether it is intact before and afterwards. assert(computeAllScoresWithoutCommit()); final Identity newIdentity; try { newIdentity = new Identity(this, oldIdentity.getRequestURI(), oldIdentity.getNickname(), oldIdentity.doesPublishTrustList()); } catch(MalformedURLException e) { // The data was taken from the OwnIdentity so this shouldn't happen throw new RuntimeException(e); } catch (InvalidParameterException e) { // The data was taken from the OwnIdentity so this shouldn't happen throw new RuntimeException(e); } newIdentity.setContexts(oldIdentity.getContexts()); newIdentity.setProperties(oldIdentity.getProperties()); try { newIdentity.setEdition(oldIdentity.getEdition()); } catch (InvalidParameterException e) { // The data was taken from old identity so this shouldn't happen throw new RuntimeException(e); } // In theory we do not need to re-fetch the current trust list edition: // The trust list of an own identity is always stored completely in the database, i.e. all trustees exist. // HOWEVER if the user had used the restoreOwnIdentity feature and then used this function, it might be the case that // the current edition of the old OwndIdentity was not fetched yet. // So we set the fetch state to FetchState.Fetched if the oldIdentity's fetch state was like that as well. if(oldIdentity.getCurrentEditionFetchState() == FetchState.Fetched) { newIdentity.onFetched(oldIdentity.getLastFetchedDate()); } // An else to set the fetch state to FetchState.NotFetched is not necessary, newIdentity.setEdition() did that already. newIdentity.storeWithoutCommit(); // Copy all received trusts. // We don't have to modify them because they are user-assigned values and the assignment // of the user does not change just because the type of the identity changes. for(Trust oldReceivedTrust : getReceivedTrusts(oldIdentity)) { Trust newReceivedTrust; try { newReceivedTrust = new Trust(this, oldReceivedTrust.getTruster(), newIdentity, oldReceivedTrust.getValue(), oldReceivedTrust.getComment()); } catch (InvalidParameterException e) { // The data was taken from the old Trust so this shouldn't happen throw new RuntimeException(e); } // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newReceivedTrust.equals(oldReceivedTrust)); */ oldReceivedTrust.deleteWithoutCommit(); newReceivedTrust.storeWithoutCommit(); } assert(getReceivedTrusts(oldIdentity).size() == 0); // Copy all received scores. // We don't have to modify them because the rating of the identity from the perspective of a // different own identity should NOT be dependent upon whether it is an own identity or not. for(Score oldScore : getScores(oldIdentity)) { Score newScore = new Score(this, oldScore.getTruster(), newIdentity, oldScore.getScore(), oldScore.getRank(), oldScore.getCapacity()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newScore.equals(oldScore)); */ oldScore.deleteWithoutCommit(); newScore.storeWithoutCommit(); } assert(getScores(oldIdentity).size() == 0); // Delete all given scores: // Non-own identities do not assign scores to other identities so we can just delete them. for(Score oldScore : getGivenScores(oldIdentity)) { final Identity trustee = oldScore.getTrustee(); final boolean oldShouldFetchTrustee = shouldFetchIdentity(trustee); oldScore.deleteWithoutCommit(); // If the OwnIdentity which we are converting was the only source of trust to the trustee // of this Score value, the should-fetch state of the trustee might change to false. if(oldShouldFetchTrustee && shouldFetchIdentity(trustee) == false) { mFetcher.storeAbortFetchCommandWithoutCommit(trustee); } } assert(getGivenScores(oldIdentity).size() == 0); // Copy all given trusts: // We don't have to use the removeTrust/setTrust functions because the score graph does not need updating: // - To the rating of the converted identity in the score graphs of other own identities it is irrelevant // whether it is an own identity or not. The rating should never depend on whether it is an own identity! // - Non-own identities do not have a score graph. So the score graph of the converted identity is deleted // completely and therefore it does not need to be updated. for(Trust oldGivenTrust : getGivenTrusts(oldIdentity)) { Trust newGivenTrust; try { newGivenTrust = new Trust(this, newIdentity, oldGivenTrust.getTrustee(), oldGivenTrust.getValue(), oldGivenTrust.getComment()); } catch (InvalidParameterException e) { // The data was taken from the old Trust so this shouldn't happen throw new RuntimeException(e); } // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newGivenTrust.equals(oldGivenTrust)); */ oldGivenTrust.deleteWithoutCommit(); newGivenTrust.storeWithoutCommit(); } mPuzzleStore.onIdentityDeletion(oldIdentity); mFetcher.storeAbortFetchCommandWithoutCommit(oldIdentity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. oldIdentity.deleteWithoutCommit(); mFetcher.storeStartFetchCommandWithoutCommit(newIdentity); // This function messes with the score graph manually so it is a good idea to check whether it is intact before and afterwards. assert(computeAllScoresWithoutCommit()); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } Logger.normal(this, "deleteOwnIdentity(): Finished."); } /** * NOTICE: When changing this function, please also take care of {@link OwnIdentity.isRestoreInProgress()} */ public synchronized void restoreOwnIdentity(FreenetURI insertFreenetURI) throws MalformedURLException, InvalidParameterException { Logger.normal(this, "restoreOwnIdentity(): Starting... "); OwnIdentity identity; synchronized(mPuzzleStore) { synchronized(mFetcher) { synchronized(Persistent.transactionLock(mDB)) { try { long edition = 0; try { edition = Math.max(edition, insertFreenetURI.getEdition()); } catch(IllegalStateException e) { // The user supplied URI did not have an edition specified } try { // Try replacing an existing non-own version of the identity with an OwnIdentity Identity oldIdentity = getIdentityByURI(insertFreenetURI); if(oldIdentity instanceof OwnIdentity) throw new InvalidParameterException("There is already an own identity with the given URI pair."); Logger.normal(this, "Restoring an already known identity from Freenet: " + oldIdentity); // Normally, one would expect beginTrustListImport() to happen close to the actual trust list changes later on in this function. // But beginTrustListImport() contains an assert(computeAllScoresWithoutCommit()) and that call to the score computation reference // implementation will fail if two identities with the same ID exist. // This would be the case later on - we cannot delete the non-own version of the OwnIdentity before we modified the trust graph // but we must also store the own version to be able to modify the trust graph. beginTrustListImport(); // We already have fetched this identity as a stranger's one. We need to update the database. identity = new OwnIdentity(this, insertFreenetURI, oldIdentity.getNickname(), oldIdentity.doesPublishTrustList()); /* We re-fetch the most recent edition to make sure all trustees are imported */ edition = Math.max(edition, oldIdentity.getEdition()); identity.restoreEdition(edition, oldIdentity.getLastFetchedDate()); identity.setContexts(oldIdentity.getContexts()); identity.setProperties(oldIdentity.getProperties()); identity.storeWithoutCommit(); initTrustTreeWithoutCommit(identity); // Copy all received trusts. // We don't have to modify them because they are user-assigned values and the assignment // of the user does not change just because the type of the identity changes. for(Trust oldReceivedTrust : getReceivedTrusts(oldIdentity)) { Trust newReceivedTrust = new Trust(this, oldReceivedTrust.getTruster(), identity, oldReceivedTrust.getValue(), oldReceivedTrust.getComment()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newReceivedTrust.equals(oldReceivedTrust)); */ oldReceivedTrust.deleteWithoutCommit(); newReceivedTrust.storeWithoutCommit(); } assert(getReceivedTrusts(oldIdentity).size() == 0); // Copy all received scores. // We don't have to modify them because the rating of the identity from the perspective of a // different own identity should NOT be dependent upon whether it is an own identity or not. for(Score oldScore : getScores(oldIdentity)) { Score newScore = new Score(this, oldScore.getTruster(), identity, oldScore.getScore(), oldScore.getRank(), oldScore.getCapacity()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newScore.equals(oldScore)); */ oldScore.deleteWithoutCommit(); newScore.storeWithoutCommit(); } assert(getScores(oldIdentity).size() == 0); // What we do NOT have to deal with is the given scores of the old identity: // Given scores do NOT exist for non-own identities, so there are no old ones to update. // Of cause there WILL be scores because it is an own identity now. // They will be created automatically when updating the given trusts // - so thats what we will do now. // Update all given trusts for(Trust givenTrust : getGivenTrusts(oldIdentity)) { // TODO: Instead of using the regular removeTrustWithoutCommit on all trust values, we could: // - manually delete the old Trust objects from the database // - manually store the new trust objects // - Realize that only the trust graph of the restored identity needs to be updated and write an optimized version // of setTrustWithoutCommit which deals with that. // But before we do that, we should first do the existing possible optimization of removeTrustWithoutCommit: // To get rid of removeTrustWithoutCommit always triggering a FULL score recomputation and instead make // it only update the parts of the trust graph which are affected. // Maybe the optimized version is fast enough that we don't have to do the optimization which this TODO suggests. removeTrustWithoutCommit(givenTrust); setTrustWithoutCommit(identity, givenTrust.getTrustee(), givenTrust.getValue(), givenTrust.getComment()); } // We do not call finishTrustListImport() now: It might trigger execution of computeAllScoresWithoutCommit // which would re-create scores of the old identity. We later call it AFTER deleting the old identity. /* finishTrustListImport(); */ mPuzzleStore.onIdentityDeletion(oldIdentity); mFetcher.storeAbortFetchCommandWithoutCommit(oldIdentity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. oldIdentity.deleteWithoutCommit(); finishTrustListImport(); } catch (UnknownIdentityException e) { // The identity did NOT exist as non-own identity yet so we can just create an OwnIdentity and store it. identity = new OwnIdentity(this, insertFreenetURI, null, false); Logger.normal(this, "Restoring not-yet-known identity from Freenet: " + identity); identity.restoreEdition(edition, null); // Store the new identity identity.storeWithoutCommit(); initTrustTreeWithoutCommit(identity); } mFetcher.storeStartFetchCommandWithoutCommit(identity); // This function messes with the trust graph manually so it is a good idea to check whether it is intact afterwards. assert(computeAllScoresWithoutCommit()); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { abortTrustListImport(e); Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } Logger.normal(this, "restoreOwnIdentity(): Finished."); } public synchronized void setTrust(String ownTrusterID, String trusteeID, byte value, String comment) throws UnknownIdentityException, NumberFormatException, InvalidParameterException { final OwnIdentity truster = getOwnIdentityByID(ownTrusterID); Identity trustee = getIdentityByID(trusteeID); setTrust(truster, trustee, value, comment); } public synchronized void removeTrust(String ownTrusterID, String trusteeID) throws UnknownIdentityException { final OwnIdentity truster = getOwnIdentityByID(ownTrusterID); final Identity trustee = getIdentityByID(trusteeID); synchronized(mFetcher) { synchronized(Persistent.transactionLock(mDB)) { try { removeTrustWithoutCommit(truster, trustee); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } public synchronized void addContext(String ownIdentityID, String newContext) throws UnknownIdentityException, InvalidParameterException { final Identity identity = getOwnIdentityByID(ownIdentityID); identity.addContext(newContext); identity.storeAndCommit(); if(logDEBUG) Logger.debug(this, "Added context '" + newContext + "' to identity '" + identity.getNickname() + "'"); } public synchronized void removeContext(String ownIdentityID, String context) throws UnknownIdentityException, InvalidParameterException { final Identity identity = getOwnIdentityByID(ownIdentityID); identity.removeContext(context); identity.storeAndCommit(); if(logDEBUG) Logger.debug(this, "Removed context '" + context + "' from identity '" + identity.getNickname() + "'"); } public synchronized String getProperty(String identityID, String property) throws InvalidParameterException, UnknownIdentityException { return getIdentityByID(identityID).getProperty(property); } public synchronized void setProperty(String ownIdentityID, String property, String value) throws UnknownIdentityException, InvalidParameterException { Identity identity = getOwnIdentityByID(ownIdentityID); identity.setProperty(property, value); identity.storeAndCommit(); if(logDEBUG) Logger.debug(this, "Added property '" + property + "=" + value + "' to identity '" + identity.getNickname() + "'"); } public synchronized void removeProperty(String ownIdentityID, String property) throws UnknownIdentityException, InvalidParameterException { final Identity identity = getOwnIdentityByID(ownIdentityID); identity.removeProperty(property); identity.storeAndCommit(); if(logDEBUG) Logger.debug(this, "Removed property '" + property + "' from identity '" + identity.getNickname() + "'"); } public String getVersion() { return Version.getMarketingVersion(); } public long getRealVersion() { return Version.getRealVersion(); } public String getString(String key) { return getBaseL10n().getString(key); } public void setLanguage(LANGUAGE newLanguage) { WebOfTrust.l10n = new PluginL10n(this, newLanguage); if(logDEBUG) Logger.debug(this, "Set LANGUAGE to: " + newLanguage.isoCode); } public PluginRespirator getPluginRespirator() { return mPR; } public ExtObjectContainer getDatabase() { return mDB; } public Configuration getConfig() { return mConfig; } public IdentityFetcher getIdentityFetcher() { return mFetcher; } public XMLTransformer getXMLTransformer() { return mXMLTransformer; } public IntroductionPuzzleStore getIntroductionPuzzleStore() { return mPuzzleStore; } public IntroductionClient getIntroductionClient() { return mIntroductionClient; } public RequestClient getRequestClient() { return mRequestClient; } /** * This is where our L10n files are stored. * @return Path of our L10n files. */ public String getL10nFilesBasePath() { return "plugins/WebOfTrust/l10n/"; } /** * This is the mask of our L10n files : lang_en.l10n, lang_de.10n, ... * @return Mask of the L10n files. */ public String getL10nFilesMask() { return "lang_${lang}.l10n"; } /** * Override L10n files are stored on the disk, their names should be explicit * we put here the plugin name, and the "override" indication. Plugin L10n * override is not implemented in the node yet. * @return Mask of the override L10n files. */ public String getL10nOverrideFilesMask() { return "WebOfTrust_lang_${lang}.override.l10n"; } /** * Get the ClassLoader of this plugin. This is necessary when getting * resources inside the plugin's Jar, for example L10n files. * @return ClassLoader object */ public ClassLoader getPluginClassLoader() { return WebOfTrust.class.getClassLoader(); } /** * Access to the current L10n data. * * @return L10n object. */ public BaseL10n getBaseL10n() { return WebOfTrust.l10n.getBase(); } public int getNumberOfFullScoreRecomputations() { return mFullScoreRecomputationCount; } public synchronized double getAverageFullScoreRecomputationTime() { return (double)mFullScoreRecomputationMilliseconds / ((mFullScoreRecomputationCount!= 0 ? mFullScoreRecomputationCount : 1) * 1000); } public int getNumberOfIncrementalScoreRecomputations() { return mIncrementalScoreRecomputationCount; } public synchronized double getAverageIncrementalScoreRecomputationTime() { return (double)mIncrementalScoreRecomputationMilliseconds / ((mIncrementalScoreRecomputationCount!= 0 ? mIncrementalScoreRecomputationCount : 1) * 1000); } /** * Tests whether two WoT are equal. * This is a complex operation in terms of execution time and memory usage and only intended for being used in unit tests. */ public synchronized boolean equals(Object obj) { if(obj == this) return true; if(!(obj instanceof WebOfTrust)) return false; WebOfTrust other = (WebOfTrust)obj; synchronized(other) { { // Compare own identities final ObjectSet<OwnIdentity> allIdentities = getAllOwnIdentities(); if(allIdentities.size() != other.getAllOwnIdentities().size()) return false; for(OwnIdentity identity : allIdentities) { try { if(!identity.equals(other.getOwnIdentityByID(identity.getID()))) return false; } catch(UnknownIdentityException e) { return false; } } } { // Compare identities final ObjectSet<Identity> allIdentities = getAllIdentities(); if(allIdentities.size() != other.getAllIdentities().size()) return false; for(Identity identity : allIdentities) { try { if(!identity.equals(other.getIdentityByID(identity.getID()))) return false; } catch(UnknownIdentityException e) { return false; } } } { // Compare trusts final ObjectSet<Trust> allTrusts = getAllTrusts(); if(allTrusts.size() != other.getAllTrusts().size()) return false; for(Trust trust : allTrusts) { try { Identity otherTruster = other.getIdentityByID(trust.getTruster().getID()); Identity otherTrustee = other.getIdentityByID(trust.getTrustee().getID()); if(!trust.equals(other.getTrust(otherTruster, otherTrustee))) return false; } catch(UnknownIdentityException e) { return false; } catch(NotTrustedException e) { return false; } } } { // Compare scores final ObjectSet<Score> allScores = getAllScores(); if(allScores.size() != other.getAllScores().size()) return false; for(Score score : allScores) { try { OwnIdentity otherTruster = other.getOwnIdentityByID(score.getTruster().getID()); Identity otherTrustee = other.getIdentityByID(score.getTrustee().getID()); if(!score.equals(other.getScore(otherTruster, otherTrustee))) return false; } catch(UnknownIdentityException e) { return false; } catch(NotInTrustTreeException e) { return false; } } } } return true; } }
false
true
private synchronized void deleteDuplicateObjects() { synchronized(mPuzzleStore) { // Needed for deleteIdentity() synchronized(mFetcher) { // // Needed for deleteIdentity() synchronized(Persistent.transactionLock(mDB)) { try { HashSet<String> deleted = new HashSet<String>(); if(logDEBUG) Logger.debug(this, "Searching for duplicate identities ..."); for(Identity identity : getAllIdentities()) { Query q = mDB.query(); q.constrain(Identity.class); q.descend("mID").constrain(identity.getID()); q.constrain(identity).identity().not(); ObjectSet<Identity> duplicates = new Persistent.InitializingObjectSet<Identity>(this, q); for(Identity duplicate : duplicates) { if(deleted.contains(duplicate.getID()) == false) { Logger.error(duplicate, "Deleting duplicate identity " + duplicate.getRequestURI()); deleteWithoutCommit(duplicate); Persistent.checkedCommit(mDB, this); } } deleted.add(identity.getID()); } Persistent.checkedCommit(mDB, this); if(logDEBUG) Logger.debug(this, "Finished searching for duplicate identities."); } catch(RuntimeException e) { Persistent.checkedRollback(mDB, this, e); } } } } // synchronized(this) { // For removeTrustWithoutCommit. Done at function level already. synchronized(mFetcher) { // For removeTrustWithoutCommit synchronized(Persistent.transactionLock(mDB)) { try { if(logDEBUG) Logger.debug(this, "Searching for duplicate Trust objects ..."); boolean duplicateTrustFound = false; for(OwnIdentity truster : getAllOwnIdentities()) { HashSet<String> givenTo = new HashSet<String>(); for(Trust trust : getGivenTrusts(truster)) { if(givenTo.contains(trust.getTrustee().getID()) == false) givenTo.add(trust.getTrustee().getID()); else { Logger.error(this, "Deleting duplicate given trust:" + trust); removeTrustWithoutCommit(trust); duplicateTrustFound = true; } } } if(duplicateTrustFound) { computeAllScoresWithoutCommit(); } Persistent.checkedCommit(mDB, this); if(logDEBUG) Logger.debug(this, "Finished searching for duplicate trust objects."); } catch(RuntimeException e) { Persistent.checkedRollback(mDB, this, e); } } // synchronized(Persistent.transactionLock(mDB)) { } // synchronized(mFetcher) { /* TODO: Also delete duplicate score */ } /** * Debug function for deleting trusts or scores of which one of the involved partners is missing. */ private synchronized void deleteOrphanObjects() { synchronized(Persistent.transactionLock(mDB)) { try { boolean orphanTrustFound = false; Query q = mDB.query(); q.constrain(Trust.class); q.descend("mTruster").constrain(null).identity().or(q.descend("mTrustee").constrain(null).identity()); ObjectSet<Trust> orphanTrusts = new Persistent.InitializingObjectSet<Trust>(this, q); for(Trust trust : orphanTrusts) { if(trust.getTruster() != null && trust.getTrustee() != null) { // TODO: Remove this workaround for the db4o bug as soon as we are sure that it does not happen anymore. Logger.error(this, "Db4o bug: constrain(null).identity() did not work for " + trust); continue; } Logger.error(trust, "Deleting orphan trust, truster = " + trust.getTruster() + ", trustee = " + trust.getTrustee()); orphanTrustFound = true; trust.deleteWithoutCommit(); } if(orphanTrustFound) { computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); } } catch(Exception e) { Persistent.checkedRollback(mDB, this, e); } } synchronized(Persistent.transactionLock(mDB)) { try { boolean orphanScoresFound = false; Query q = mDB.query(); q.constrain(Score.class); q.descend("mTruster").constrain(null).identity().or(q.descend("mTrustee").constrain(null).identity()); ObjectSet<Score> orphanScores = new Persistent.InitializingObjectSet<Score>(this, q); for(Score score : orphanScores) { if(score.getTruster() != null && score.getTrustee() != null) { // TODO: Remove this workaround for the db4o bug as soon as we are sure that it does not happen anymore. Logger.error(this, "Db4o bug: constrain(null).identity() did not work for " + score); continue; } Logger.error(score, "Deleting orphan score, truster = " + score.getTruster() + ", trustee = " + score.getTrustee()); orphanScoresFound = true; score.deleteWithoutCommit(); } if(orphanScoresFound) { computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); } } catch(Exception e) { Persistent.checkedRollback(mDB, this, e); } } } /** * Warning: This function is not synchronized, use it only in single threaded mode. * @return The WOT database format version of the given database. -1 if there is no Configuration stored in it or multiple configurations exist. */ @SuppressWarnings("deprecation") private static int peekDatabaseFormatVersion(WebOfTrust wot, ExtObjectContainer database) { final Query query = database.query(); query.constrain(Configuration.class); @SuppressWarnings("unchecked") ObjectSet<Configuration> result = (ObjectSet<Configuration>)query.execute(); switch(result.size()) { case 1: { final Configuration config = (Configuration)result.next(); config.initializeTransient(wot, database); // For the HashMaps to stay alive we need to activate to full depth. config.checkedActivate(4); return config.getDatabaseFormatVersion(); } default: return -1; } } /** * Loads an existing Config object from the database and adds any missing default values to it, creates and stores a new one if none exists. * @return The config object. */ private synchronized Configuration getOrCreateConfig() { final Query query = mDB.query(); query.constrain(Configuration.class); final ObjectSet<Configuration> result = new Persistent.InitializingObjectSet<Configuration>(this, query); switch(result.size()) { case 1: { final Configuration config = result.next(); // For the HashMaps to stay alive we need to activate to full depth. config.checkedActivate(4); config.setDefaultValues(false); config.storeAndCommit(); return config; } case 0: { final Configuration config = new Configuration(this); config.initializeTransient(this); config.storeAndCommit(); return config; } default: throw new RuntimeException("Multiple config objects found: " + result.size()); } } /** Capacity is the maximum amount of points an identity can give to an other by trusting it. * * Values choice : * Advogato Trust metric recommends that values decrease by rounded 2.5 times. * This makes sense, making the need of 3 N+1 ranked people to overpower * the trust given by a N ranked identity. * * Number of ranks choice : * When someone creates a fresh identity, he gets the seed identity at * rank 1 and freenet developpers at rank 2. That means that * he will see people that were : * - given 7 trust by freenet devs (rank 2) * - given 17 trust by rank 3 * - given 50 trust by rank 4 * - given 100 trust by rank 5 and above. * This makes the range small enough to avoid a newbie * to even see spam, and large enough to make him see a reasonnable part * of the community right out-of-the-box. * Of course, as soon as he will start to give trust, he will put more * people at rank 1 and enlarge his WoT. */ protected static final int capacities[] = { 100,// Rank 0 : Own identities 40, // Rank 1 : Identities directly trusted by ownIdenties 16, // Rank 2 : Identities trusted by rank 1 identities 6, // So on... 2, 1 // Every identity above rank 5 can give 1 point }; // Identities with negative score have zero capacity /** * Computes the capacity of a truster. The capacity is a weight function in percent which is used to decide how much * trust points an identity can add to the score of identities which it has assigned trust values to. * The higher the rank of an identity, the less is it's capacity. * * If the rank of the identity is Integer.MAX_VALUE (infinite, this means it has only received negative or 0 trust values from identities with rank >= 0 and less * than infinite) or -1 (this means that it has only received trust values from identities with infinite rank) then its capacity is 0. * * If the truster has assigned a trust value to the trustee the capacity will be computed only from that trust value: * The decision of the truster should always overpower the view of remote identities. * * Notice that 0 is included in infinite rank to prevent identities which have only solved introduction puzzles from having a capacity. * * @param truster The {@link OwnIdentity} in whose trust tree the capacity shall be computed * @param trustee The {@link Identity} of which the capacity shall be computed. * @param rank The rank of the identity. The rank is the distance in trust steps from the OwnIdentity which views the web of trust, * - its rank is 0, the rank of its trustees is 1 and so on. Must be -1 if the truster has no rank in the tree owners view. */ protected int computeCapacity(OwnIdentity truster, Identity trustee, int rank) { if(truster == trustee) return 100; try { if(getTrust(truster, trustee).getValue() <= 0) { // Security check, if rank computation breaks this will hit. assert(rank == Integer.MAX_VALUE); return 0; } } catch(NotTrustedException e) { } if(rank == -1 || rank == Integer.MAX_VALUE) return 0; return (rank < capacities.length) ? capacities[rank] : 1; } /** * Reference-implementation of score computation. This means:<br /> * - It is not used by the real WoT code because its slow<br /> * - It is used by unit tests (and WoT) to check whether the real implementation works<br /> * - It is the function which you should read if you want to understand how WoT works.<br /> * * Computes all rank and score values and checks whether the database is correct. If wrong values are found, they are correct.<br /> * * There was a bug in the score computation for a long time which resulted in wrong computation when trust values very removed under certain conditions.<br /> * * Further, rank values are shortest paths and the path-finding algorithm is not executed from the source * to the target upon score computation: It uses the rank of the neighbor nodes to find a shortest path. * Therefore, the algorithm is very vulnerable to bugs since one wrong value will stay in the database * and affect many others. So it is useful to have this function. * * @return True if all stored scores were correct. False if there were any errors in stored scores. */ protected synchronized boolean computeAllScoresWithoutCommit() { if(logMINOR) Logger.minor(this, "Doing a full computation of all Scores..."); final long beginTime = CurrentTimeUTC.getInMillis(); boolean returnValue = true; final ObjectSet<Identity> allIdentities = getAllIdentities(); // Scores are a rating of an identity from the view of an OwnIdentity so we compute them per OwnIdentity. for(OwnIdentity treeOwner : getAllOwnIdentities()) { // At the end of the loop body, this table will be filled with the ranks of all identities which are visible for treeOwner. // An identity is visible if there is a trust chain from the owner to it. // The rank is the distance in trust steps from the treeOwner. // So the treeOwner is rank 0, the trustees of the treeOwner are rank 1 and so on. final HashMap<Identity, Integer> rankValues = new HashMap<Identity, Integer>(allIdentities.size() * 2); // Compute the rank values { // For each identity which is added to rankValues, all its trustees are added to unprocessedTrusters. // The inner loop then pulls out one unprocessed identity and computes the rank of its trustees: // All trustees which have received positive (> 0) trust will get his rank + 1 // Trustees with negative trust or 0 trust will get a rank of Integer.MAX_VALUE. // Trusters with rank Integer.MAX_VALUE cannot inherit their rank to their trustees so the trustees will get no rank at all. // Identities with no rank are considered to be not in the trust tree of the own identity and their score will be null / none. // // Further, if the treeOwner has assigned a trust value to an identity, the rank decision is done by only considering this trust value: // The decision of the own identity shall not be overpowered by the view of the remote identities. // // The purpose of differentiation between Integer.MAX_VALUE and -1 is: // Score objects of identities with rank Integer.MAX_VALUE are kept in the database because WoT will usually "hear" about those identities by seeing // them in the trust lists of trusted identities (with 0 or negative trust values). So it must store the trust values to those identities and // have a way of telling the user "this identity is not trusted" by keeping a score object of them. // Score objects of identities with rank -1 are deleted because they are the trustees of distrusted identities and we will not get to the point where // we hear about those identities because the only way of hearing about them is importing a trust list of a identity with Integer.MAX_VALUE rank // - and we never import their trust lists. // We include trust values of 0 in the set of rank Integer.MAX_VALUE (instead of only NEGATIVE trust) so that identities which only have solved // introduction puzzles cannot inherit their rank to their trustees. final LinkedList<Identity> unprocessedTrusters = new LinkedList<Identity>(); // The own identity is the root of the trust tree, it should assign itself a rank of 0 , a capacity of 100 and a symbolic score of Integer.MAX_VALUE try { Score selfScore = getScore(treeOwner, treeOwner); if(selfScore.getRank() >= 0) { // It can only give it's rank if it has a valid one rankValues.put(treeOwner, selfScore.getRank()); unprocessedTrusters.addLast(treeOwner); } else { rankValues.put(treeOwner, null); } } catch(NotInTrustTreeException e) { // This only happens in unit tests. } while(!unprocessedTrusters.isEmpty()) { final Identity truster = unprocessedTrusters.removeFirst(); final Integer trusterRank = rankValues.get(truster); // The truster cannot give his rank to his trustees because he has none (or infinite), they receive no rank at all. if(trusterRank == null || trusterRank == Integer.MAX_VALUE) { // (Normally this does not happen because we do not enqueue the identities if they have no rank but we check for security) continue; } final int trusteeRank = trusterRank + 1; for(Trust trust : getGivenTrusts(truster)) { final Identity trustee = trust.getTrustee(); final Integer oldTrusteeRank = rankValues.get(trustee); if(oldTrusteeRank == null) { // The trustee was not processed yet if(trust.getValue() > 0) { rankValues.put(trustee, trusteeRank); unprocessedTrusters.addLast(trustee); } else rankValues.put(trustee, Integer.MAX_VALUE); } else { // Breadth first search will process all rank one identities are processed before any rank two identities, etc. assert(oldTrusteeRank == Integer.MAX_VALUE || trusteeRank >= oldTrusteeRank); if(oldTrusteeRank == Integer.MAX_VALUE) { // If we found a rank less than infinite we can overwrite the old rank with this one, but only if the infinite rank was not // given by the tree owner. try { final Trust treeOwnerTrust = getTrust(treeOwner, trustee); assert(treeOwnerTrust.getValue() <= 0); // TODO: Is this correct? } catch(NotTrustedException e) { if(trust.getValue() > 0) { rankValues.put(trustee, trusteeRank); unprocessedTrusters.addLast(trustee); } } } } } } } // Rank values of all visible identities are computed now. // Next step is to compute the scores of all identities for(Identity target : allIdentities) { // The score of an identity is the sum of all weighted trust values it has received. // Each trust value is weighted with the capacity of the truster - the capacity decays with increasing rank. Integer targetScore; final Integer targetRank = rankValues.get(target); if(targetRank == null) { targetScore = null; } else { // The treeOwner trusts himself. if(targetRank == 0) { targetScore = Integer.MAX_VALUE; } else { // If the treeOwner has assigned a trust value to the target, it always overrides the "remote" score. try { targetScore = (int)getTrust(treeOwner, target).getValue(); } catch(NotTrustedException e) { targetScore = 0; for(Trust receivedTrust : getReceivedTrusts(target)) { final Identity truster = receivedTrust.getTruster(); final Integer trusterRank = rankValues.get(truster); // The capacity is a weight function for trust values which are given from an identity: // The higher the rank, the less the capacity. // If the rank is Integer.MAX_VALUE (infinite) or -1 (no rank at all) the capacity will be 0. final int capacity = computeCapacity(treeOwner, truster, trusterRank != null ? trusterRank : -1); targetScore += (receivedTrust.getValue() * capacity) / 100; } } } } Score newScore = null; if(targetScore != null) { newScore = new Score(this, treeOwner, target, targetScore, targetRank, computeCapacity(treeOwner, target, targetRank)); } boolean needToCheckFetchStatus = false; boolean oldShouldFetch = false; int oldCapacity = 0; // Now we have the rank and the score of the target computed and can check whether the database-stored score object is correct. try { Score currentStoredScore = getScore(treeOwner, target); oldCapacity = currentStoredScore.getCapacity(); if(newScore == null) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: The identity has no rank and should have no score but score was " + currentStoredScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); currentStoredScore.deleteWithoutCommit(); } else { if(!newScore.equals(currentStoredScore)) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: Should have been " + newScore + " but was " + currentStoredScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); currentStoredScore.setRank(newScore.getRank()); currentStoredScore.setCapacity(newScore.getCapacity()); currentStoredScore.setValue(newScore.getScore()); currentStoredScore.storeWithoutCommit(); } } } catch(NotInTrustTreeException e) { oldCapacity = 0; if(newScore != null) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: No score was stored for the identity but it should be " + newScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); newScore.storeWithoutCommit(); } } if(needToCheckFetchStatus) { // If fetch status changed from false to true, we need to start fetching it // If the capacity changed from 0 to positive, we need to refetch the current edition: Identities with capacity 0 cannot // cause new identities to be imported from their trust list, capacity > 0 allows this. // If the fetch status changed from true to false, we need to stop fetching it if((!oldShouldFetch || (oldCapacity == 0 && newScore != null && newScore.getCapacity() > 0)) && shouldFetchIdentity(target) ) { if(!oldShouldFetch) if(logDEBUG) Logger.debug(this, "Fetch status changed from false to true, refetching " + target); else if(logDEBUG) Logger.debug(this, "Capacity changed from 0 to " + newScore.getCapacity() + ", refetching" + target); target.markForRefetch(); target.storeWithoutCommit(); mFetcher.storeStartFetchCommandWithoutCommit(target); } else if(oldShouldFetch && !shouldFetchIdentity(target)) { if(logDEBUG) Logger.debug(this, "Fetch status changed from true to false, aborting fetch of " + target); mFetcher.storeAbortFetchCommandWithoutCommit(target); } } } } mFullScoreComputationNeeded = false; ++mFullScoreRecomputationCount; mFullScoreRecomputationMilliseconds += CurrentTimeUTC.getInMillis() - beginTime; if(logMINOR) { Logger.minor(this, "Full score computation finished. Amount: " + mFullScoreRecomputationCount + "; Avg Time:" + getAverageFullScoreRecomputationTime() + "s"); } return returnValue; } private synchronized void createSeedIdentities() { for(String seedURI : SEED_IDENTITIES) { Identity seed; synchronized(Persistent.transactionLock(mDB)) { try { seed = getIdentityByURI(seedURI); if(seed instanceof OwnIdentity) { OwnIdentity ownSeed = (OwnIdentity)seed; ownSeed.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); ownSeed.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.SEED_IDENTITY_PUZZLE_COUNT)); ownSeed.storeAndCommit(); } else { try { seed.setEdition(new FreenetURI(seedURI).getEdition()); seed.storeAndCommit(); } catch(InvalidParameterException e) { /* We already have the latest edition stored */ } } } catch (UnknownIdentityException uie) { try { seed = new Identity(this, seedURI, null, true); // We have to explicitely set the edition number because the constructor only considers the given edition as a hint. seed.setEdition(new FreenetURI(seedURI).getEdition()); seed.storeAndCommit(); } catch (Exception e) { Logger.error(this, "Seed identity creation error", e); } } catch (Exception e) { Persistent.checkedRollback(mDB, this, e); } } } } public void terminate() { if(logDEBUG) Logger.debug(this, "WoT plugin terminating ..."); /* We use single try/catch blocks so that failure of termination of one service does not prevent termination of the others */ try { if(mWebInterface != null) this.mWebInterface.unload(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mIntroductionClient != null) mIntroductionClient.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mIntroductionServer != null) mIntroductionServer.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mInserter != null) mInserter.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mFetcher != null) mFetcher.stop(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mDB != null) { /* TODO: At 2009-06-15, it does not seem possible to ask db4o for whether a transaction is pending. * If it becomes possible some day, we should check that here, and log an error if there is an uncommitted transaction. * - All transactions should be committed after obtaining the lock() on the database. */ synchronized(Persistent.transactionLock(mDB)) { System.gc(); mDB.rollback(); System.gc(); mDB.close(); } } } catch(Exception e) { Logger.error(this, "Error during termination.", e); } if(logDEBUG) Logger.debug(this, "WoT plugin terminated."); } /** * Inherited event handler from FredPluginFCP, handled in <code>class FCPInterface</code>. */ public void handle(PluginReplySender replysender, SimpleFieldSet params, Bucket data, int accesstype) { mFCPInterface.handle(replysender, params, data, accesstype); } /** * Loads an own or normal identity from the database, querying on its ID. * * @param id The ID of the identity to load * @return The identity matching the supplied ID. * @throws DuplicateIdentityException if there are more than one identity with this id in the database * @throws UnknownIdentityException if there is no identity with this id in the database */ public synchronized Identity getIdentityByID(String id) throws UnknownIdentityException { final Query query = mDB.query(); query.constrain(Identity.class); query.descend("mID").constrain(id); final ObjectSet<Identity> result = new Persistent.InitializingObjectSet<Identity>(this, query); switch(result.size()) { case 1: return result.next(); case 0: throw new UnknownIdentityException(id); default: throw new DuplicateIdentityException(id, result.size()); } } /** * Gets an OwnIdentity by its ID. * * @param id The unique identifier to query an OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if there is now OwnIdentity with that id */ public synchronized OwnIdentity getOwnIdentityByID(String id) throws UnknownIdentityException { final Query query = mDB.query(); query.constrain(OwnIdentity.class); query.descend("mID").constrain(id); final ObjectSet<OwnIdentity> result = new Persistent.InitializingObjectSet<OwnIdentity>(this, query); switch(result.size()) { case 1: return result.next(); case 0: throw new UnknownIdentityException(id); default: throw new DuplicateIdentityException(id, result.size()); } } /** * Loads an identity from the database, querying on its requestURI (a valid {@link FreenetURI}) * * @param uri The requestURI of the identity * @return The identity matching the supplied requestURI * @throws UnknownIdentityException if there is no identity with this id in the database */ public Identity getIdentityByURI(FreenetURI uri) throws UnknownIdentityException { return getIdentityByID(IdentityID.constructAndValidateFromURI(uri).toString()); } /** * Loads an identity from the database, querying on its requestURI (as String) * * @param uri The requestURI of the identity which will be converted to {@link FreenetURI} * @return The identity matching the supplied requestURI * @throws UnknownIdentityException if there is no identity with this id in the database * @throws MalformedURLException if the requestURI isn't a valid FreenetURI */ public Identity getIdentityByURI(String uri) throws UnknownIdentityException, MalformedURLException { return getIdentityByURI(new FreenetURI(uri)); } /** * Gets an OwnIdentity by its requestURI (a {@link FreenetURI}). * The OwnIdentity's unique identifier is extracted from the supplied requestURI. * * @param uri The requestURI of the desired OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if the OwnIdentity isn't in the database */ public OwnIdentity getOwnIdentityByURI(FreenetURI uri) throws UnknownIdentityException { return getOwnIdentityByID(IdentityID.constructAndValidateFromURI(uri).toString()); } /** * Gets an OwnIdentity by its requestURI (as String). * The given String is converted to {@link FreenetURI} in order to extract a unique id. * * @param uri The requestURI (as String) of the desired OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if the OwnIdentity isn't in the database * @throws MalformedURLException if the supplied requestURI is not a valid FreenetURI */ public OwnIdentity getOwnIdentityByURI(String uri) throws UnknownIdentityException, MalformedURLException { return getOwnIdentityByURI(new FreenetURI(uri)); } /** * Returns all identities that are in the database * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all identities present in the database */ public ObjectSet<Identity> getAllIdentities() { final Query query = mDB.query(); query.constrain(Identity.class); return new Persistent.InitializingObjectSet<Identity>(this, query); } public static enum SortOrder { ByNicknameAscending, ByNicknameDescending, ByScoreAscending, ByScoreDescending, ByLocalTrustAscending, ByLocalTrustDescending } /** * Get a filtered and sorted list of identities. * You have to synchronize on this WoT when calling the function and processing the returned list. */ public ObjectSet<Identity> getAllIdentitiesFilteredAndSorted(OwnIdentity truster, String nickFilter, SortOrder sortInstruction) { Query q = mDB.query(); switch(sortInstruction) { case ByNicknameAscending: q.constrain(Identity.class); q.descend("mNickname").orderAscending(); break; case ByNicknameDescending: q.constrain(Identity.class); q.descend("mNickname").orderDescending(); break; case ByScoreAscending: q.constrain(Score.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderAscending(); q = q.descend("mTrustee"); break; case ByScoreDescending: // TODO: This excludes identities which have no score q.constrain(Score.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderDescending(); q = q.descend("mTrustee"); break; case ByLocalTrustAscending: q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderAscending(); q = q.descend("mTrustee"); break; case ByLocalTrustDescending: // TODO: This excludes untrusted identities. q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderDescending(); q = q.descend("mTrustee"); break; } if(nickFilter != null) { nickFilter = nickFilter.trim(); if(!nickFilter.equals("")) q.descend("mNickname").constrain(nickFilter).like(); } return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all non-own identities that are in the database. * * You have to synchronize on this WoT when calling the function and processing the returned list! */ public ObjectSet<Identity> getAllNonOwnIdentities() { final Query q = mDB.query(); q.constrain(Identity.class); q.constrain(OwnIdentity.class).not(); return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all non-own identities that are in the database, sorted descending by their date of modification, i.e. recently * modified identities will be at the beginning of the list. * * You have to synchronize on this WoT when calling the function and processing the returned list! * * Used by the IntroductionClient for fetching puzzles from recently modified identities. */ public ObjectSet<Identity> getAllNonOwnIdentitiesSortedByModification () { final Query q = mDB.query(); q.constrain(Identity.class); q.constrain(OwnIdentity.class).not(); /* TODO: As soon as identities announce that they were online every day, uncomment the following line */ /* q.descend("mLastChangedDate").constrain(new Date(CurrentTimeUTC.getInMillis() - 1 * 24 * 60 * 60 * 1000)).greater(); */ q.descend("mLastFetchedDate").orderDescending(); return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all own identities that are in the database * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all identities present in the database. */ public ObjectSet<OwnIdentity> getAllOwnIdentities() { final Query q = mDB.query(); q.constrain(OwnIdentity.class); return new Persistent.InitializingObjectSet<OwnIdentity>(this, q); } /** * DO NOT USE THIS FUNCTION FOR DELETING OWN IDENTITIES UPON USER REQUEST! * IN FACT BE VERY CAREFUL WHEN USING IT FOR ANYTHING FOR THE FOLLOWING REASONS: * - This function deletes ALL given and received trust values of the given identity. This modifies the trust list of the trusters against their will. * - Especially it might be an information leak if the trust values of other OwnIdentities are deleted! * - If WOT one day is designed to be used by many different users at once, the deletion of other OwnIdentity's trust values would even be corruption. * * The intended purpose of this function is: * - To specify which objects have to be dealt with when messing with storage of an identity. * - To be able to do database object leakage tests: Many classes have a deleteWithoutCommit function and there are valid usecases for them. * However, the implementations of those functions might cause leaks by forgetting to delete certain object members. * If you call this function for ALL identities in a database, EVERYTHING should be deleted and the database SHOULD be empty. * You then can check whether the database actually IS empty to test for leakage. * * You have to lock the WebOfTrust, the IntroductionPuzzleStore and the IdentityFetcher before calling this function. */ private void deleteWithoutCommit(Identity identity) { // We want to use beginTrustListImport, finishTrustListImport / abortTrustListImport. // If the caller already handles that for us though, we should not call those function again. // So we check whether the caller already started an import. boolean trustListImportWasInProgress = mTrustListImportInProgress; try { if(!trustListImportWasInProgress) beginTrustListImport(); if(logDEBUG) Logger.debug(this, "Deleting identity " + identity + " ..."); if(logDEBUG) Logger.debug(this, "Deleting received scores..."); for(Score score : getScores(identity)) score.deleteWithoutCommit(); if(identity instanceof OwnIdentity) { if(logDEBUG) Logger.debug(this, "Deleting given scores..."); for(Score score : getGivenScores((OwnIdentity)identity)) score.deleteWithoutCommit(); } if(logDEBUG) Logger.debug(this, "Deleting received trusts..."); for(Trust trust : getReceivedTrusts(identity)) trust.deleteWithoutCommit(); if(logDEBUG) Logger.debug(this, "Deleting given trusts..."); for(Trust givenTrust : getGivenTrusts(identity)) { givenTrust.deleteWithoutCommit(); // We call computeAllScores anyway so we do not use removeTrustWithoutCommit() } mFullScoreComputationNeeded = true; // finishTrustListImport will call computeAllScoresWithoutCommit for us. if(logDEBUG) Logger.debug(this, "Deleting associated introduction puzzles ..."); mPuzzleStore.onIdentityDeletion(identity); if(logDEBUG) Logger.debug(this, "Storing an abort-fetch-command..."); if(mFetcher != null) { // Can be null if we use this function in upgradeDB() mFetcher.storeAbortFetchCommandWithoutCommit(identity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. } if(logDEBUG) Logger.debug(this, "Deleting the identity..."); identity.deleteWithoutCommit(); if(!trustListImportWasInProgress) finishTrustListImport(); } catch(RuntimeException e) { if(!trustListImportWasInProgress) abortTrustListImport(e); Persistent.checkedRollbackAndThrow(mDB, this, e); } } /** * Gets the score of this identity in a trust tree. * Each {@link OwnIdentity} has its own trust tree. * * @param truster The owner of the trust tree * @return The {@link Score} of this Identity in the required trust tree * @throws NotInTrustTreeException if this identity is not in the required trust tree */ public synchronized Score getScore(final OwnIdentity truster, final Identity trustee) throws NotInTrustTreeException { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mID").constrain(new ScoreID(truster, trustee).toString()); final ObjectSet<Score> result = new Persistent.InitializingObjectSet<Score>(this, query); switch(result.size()) { case 1: final Score score = result.next(); assert(score.getTruster() == truster); assert(score.getTrustee() == trustee); return score; case 0: throw new NotInTrustTreeException(truster, trustee); default: throw new DuplicateScoreException(truster, trustee, result.size()); } } /** * Gets a list of all this Identity's Scores. * You have to synchronize on this WoT around the call to this function and the processing of the returned list! * * @return An {@link ObjectSet} containing all {@link Score} this Identity has. */ public ObjectSet<Score> getScores(final Identity identity) { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mTrustee").constrain(identity).identity(); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Get a list of all scores which the passed own identity has assigned to other identities. * * You have to synchronize on this WoT around the call to this function and the processing of the returned list! * @return An {@link ObjectSet} containing all {@link Score} this Identity has given. */ public ObjectSet<Score> getGivenScores(final OwnIdentity truster) { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mTruster").constrain(truster).identity(); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Gets the best score this Identity has in existing trust trees. * * @return the best score this Identity has * @throws NotInTrustTreeException If the identity has no score in any trusttree. */ public synchronized int getBestScore(final Identity identity) throws NotInTrustTreeException { int bestScore = Integer.MIN_VALUE; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) throw new NotInTrustTreeException(identity); // TODO: Cache the best score of an identity as a member variable. for(final Score score : scores) bestScore = Math.max(score.getScore(), bestScore); return bestScore; } /** * Gets the best capacity this identity has in any trust tree. * @throws NotInTrustTreeException If the identity is not in any trust tree. Can be interpreted as capacity 0. */ public int getBestCapacity(final Identity identity) throws NotInTrustTreeException { int bestCapacity = 0; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) throw new NotInTrustTreeException(identity); // TODO: Cache the best score of an identity as a member variable. for(final Score score : scores) bestCapacity = Math.max(score.getCapacity(), bestCapacity); return bestCapacity; } /** * Get all scores in the database. * You have to synchronize on this WoT when calling the function and processing the returned list! */ public ObjectSet<Score> getAllScores() { final Query query = mDB.query(); query.constrain(Score.class); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Checks whether the given identity should be downloaded. * @return Returns true if the identity has any capacity > 0, any score >= 0 or if it is an own identity. */ public boolean shouldFetchIdentity(final Identity identity) { if(identity instanceof OwnIdentity) return true; int bestScore = Integer.MIN_VALUE; int bestCapacity = 0; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) return false; // TODO: Cache the best score of an identity as a member variable. for(Score score : scores) { bestCapacity = Math.max(score.getCapacity(), bestCapacity); bestScore = Math.max(score.getScore(), bestScore); if(bestCapacity > 0 || bestScore >= 0) return true; } return false; } /** * Gets non-own Identities matching a specified score criteria. * TODO: Rename to getNonOwnIdentitiesByScore. Or even better: Make it return own identities as well, this will speed up the database query and clients might be ok with it. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param truster The owner of the trust tree, null if you want the trusted identities of all owners. * @param select Score criteria, can be > zero, zero or negative. Greater than zero returns all identities with score >= 0, zero with score equal to 0 * and negative with score < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a trust value of 0. * @return an {@link ObjectSet} containing Scores of the identities that match the criteria */ public ObjectSet<Score> getIdentitiesByScore(final OwnIdentity truster, final int select) { final Query query = mDB.query(); query.constrain(Score.class); if(truster != null) query.descend("mTruster").constrain(truster).identity(); query.descend("mTrustee").constrain(OwnIdentity.class).not(); /* We include 0 in the list of identities with positive score because solving captchas gives no points to score */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Gets {@link Trust} from a specified truster to a specified trustee. * * @param truster The identity that gives trust to this Identity * @param trustee The identity which receives the trust * @return The trust given to the trustee by the specified truster * @throws NotTrustedException if the truster doesn't trust the trustee */ public synchronized Trust getTrust(final Identity truster, final Identity trustee) throws NotTrustedException, DuplicateTrustException { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mID").constrain(new TrustID(truster, trustee).toString()); final ObjectSet<Trust> result = new Persistent.InitializingObjectSet<Trust>(this, query); switch(result.size()) { case 1: final Trust trust = result.next(); assert(trust.getTruster() == truster); assert(trust.getTrustee() == trustee); return trust; case 0: throw new NotTrustedException(truster, trustee); default: throw new DuplicateTrustException(truster, trustee, result.size()); } } /** * Gets all trusts given by the given truster. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has given. */ public ObjectSet<Trust> getGivenTrusts(final Identity truster) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts given by the given truster. * The result is sorted descending by the time we last fetched the trusted identity. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has given. */ public ObjectSet<Trust> getGivenTrustsSortedDescendingByLastSeen(final Identity truster) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); query.descend("mTrustee").descend("mLastFetchedDate").orderDescending(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets given trust values of an identity matching a specified trust value criteria. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param truster The identity which given the trust values. * @param select Trust value criteria, can be > zero, zero or negative. Greater than zero returns all trust values >= 0, zero returns trust values equal to 0. * Negative returns trust values < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a value of 0. * @return an {@link ObjectSet} containing received trust values that match the criteria. */ public ObjectSet<Trust> getGivenTrusts(final Identity truster, final int select) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); /* We include 0 in the list of identities with positive trust because solving captchas gives 0 trust */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0 ) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts given by the given truster in a trust list with a different edition than the passed in one. * You have to synchronize on this WoT when calling the function and processing the returned list! */ protected ObjectSet<Trust> getGivenTrustsOfDifferentEdition(final Identity truster, final long edition) { final Query q = mDB.query(); q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mTrusterTrustListEdition").constrain(edition).not(); return new Persistent.InitializingObjectSet<Trust>(this, q); } /** * Gets all trusts received by the given trustee. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has received. */ public ObjectSet<Trust> getReceivedTrusts(final Identity trustee) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTrustee").constrain(trustee).identity(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets received trust values of an identity matching a specified trust value criteria. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param trustee The identity which has received the trust values. * @param select Trust value criteria, can be > zero, zero or negative. Greater than zero returns all trust values >= 0, zero returns trust values equal to 0. * Negative returns trust values < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a value of 0. * @return an {@link ObjectSet} containing received trust values that match the criteria. */ public ObjectSet<Trust> getReceivedTrusts(final Identity trustee, final int select) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTrustee").constrain(trustee).identity(); /* We include 0 in the list of identities with positive trust because solving captchas gives 0 trust */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0 ) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has received. */ public ObjectSet<Trust> getAllTrusts() { final Query query = mDB.query(); query.constrain(Trust.class); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gives some {@link Trust} to another Identity. * It creates or updates an existing Trust object and make the trustee compute its {@link Score}. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(WebOfTrust.this) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... setTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * } * } * * @param truster The Identity that gives the trust * @param trustee The Identity that receives the trust * @param newValue Numeric value of the trust * @param newComment A comment to explain the given value * @throws InvalidParameterException if a given parameter isn't valid, see {@link Trust} for details on accepted values. */ protected void setTrustWithoutCommit(Identity truster, Identity trustee, byte newValue, String newComment) throws InvalidParameterException { try { // Check if we are updating an existing trust value final Trust trust = getTrust(truster, trustee); final Trust oldTrust = trust.clone(); trust.trusterEditionUpdated(); trust.setComment(newComment); trust.storeWithoutCommit(); if(trust.getValue() != newValue) { trust.setValue(newValue); trust.storeWithoutCommit(); if(logDEBUG) Logger.debug(this, "Updated trust value ("+ trust +"), now updating Score."); updateScoresWithoutCommit(oldTrust, trust); } } catch (NotTrustedException e) { final Trust trust = new Trust(this, truster, trustee, newValue, newComment); trust.storeWithoutCommit(); if(logDEBUG) Logger.debug(this, "New trust value ("+ trust +"), now updating Score."); updateScoresWithoutCommit(null, trust); } truster.updated(); truster.storeWithoutCommit(); } /** * Only for being used by WoT internally and by unit tests! */ synchronized void setTrust(OwnIdentity truster, Identity trustee, byte newValue, String newComment) throws InvalidParameterException { synchronized(Persistent.transactionLock(mDB)) { try { setTrustWithoutCommit(truster, trustee, newValue, newComment); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } /** * Deletes a trust object. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... removeTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}} * * @param truster * @param trustee */ protected void removeTrustWithoutCommit(OwnIdentity truster, Identity trustee) { try { try { removeTrustWithoutCommit(getTrust(truster, trustee)); } catch (NotTrustedException e) { Logger.error(this, "Cannot remove trust - there is none - from " + truster.getNickname() + " to " + trustee.getNickname()); } } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } /** * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... setTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}} * */ protected void removeTrustWithoutCommit(Trust trust) { trust.deleteWithoutCommit(); updateScoresWithoutCommit(trust, null); } /** * Initializes this OwnIdentity's trust tree without commiting the transaction. * Meaning : It creates a Score object for this OwnIdentity in its own trust so it can give trust to other Identities. * * The score will have a rank of 0, a capacity of 100 (= 100 percent) and a score value of Integer.MAX_VALUE. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(Persistent.transactionLock(mDB)) { * try { ... initTrustTreeWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * } * * @throws DuplicateScoreException if there already is more than one Score for this identity (should never happen) */ private synchronized void initTrustTreeWithoutCommit(OwnIdentity identity) throws DuplicateScoreException { try { getScore(identity, identity); Logger.error(this, "initTrustTreeWithoutCommit called even though there is already one for " + identity); return; } catch (NotInTrustTreeException e) { final Score score = new Score(this, identity, identity, Integer.MAX_VALUE, 0, 100); score.storeWithoutCommit(); } } /** * Computes the trustee's Score value according to the trusts it has received and the capacity of its trusters in the specified * trust tree. * * @param truster The OwnIdentity that owns the trust tree * @param trustee The identity for which the score shall be computed. * @return The new Score of the identity. Integer.MAX_VALUE if the trustee is equal to the truster. * @throws DuplicateScoreException if there already exist more than one {@link Score} objects for the trustee (should never happen) */ private synchronized int computeScoreValue(OwnIdentity truster, Identity trustee) throws DuplicateScoreException { if(trustee == truster) return Integer.MAX_VALUE; int value = 0; try { return getTrust(truster, trustee).getValue(); } catch(NotTrustedException e) { } for(Trust trust : getReceivedTrusts(trustee)) { try { final Score trusterScore = getScore(truster, trust.getTruster()); value += ( trust.getValue() * trusterScore.getCapacity() ) / 100; } catch (NotInTrustTreeException e) {} } return value; } /** * Computes the trustees's rank in the trust tree of the truster. * It gets its best ranked non-zero-capacity truster's rank, plus one. * If it has only received negative trust values from identities which have a non-zero-capacity it gets a rank of Integer.MAX_VALUE (infinite). * If it has only received trust values from identities with rank of Integer.MAX_VALUE it gets a rank of -1. * * If the tree owner has assigned a trust value to the identity, the rank computation is only done from that value because the score decisions of the * tree owner are always absolute (if you distrust someone, the remote identities should not be allowed to overpower your decision). * * The purpose of differentiation between Integer.MAX_VALUE and -1 is: * Score objects of identities with rank Integer.MAX_VALUE are kept in the database because WoT will usually "hear" about those identities by seeing them * in the trust lists of trusted identities (with negative trust values). So it must store the trust values to those identities and have a way of telling the * user "this identity is not trusted" by keeping a score object of them. * Score objects of identities with rank -1 are deleted because they are the trustees of distrusted identities and we will not get to the point where we * hear about those identities because the only way of hearing about them is downloading a trust list of a identity with Integer.MAX_VALUE rank - and * we never download their trust lists. * * Notice that 0 is included in infinite rank to prevent identities which have only solved introduction puzzles from having a capacity. * * @param truster The OwnIdentity that owns the trust tree * @return The new Rank if this Identity * @throws DuplicateScoreException if there already exist more than one {@link Score} objects for the trustee (should never happen) */ private synchronized int computeRank(OwnIdentity truster, Identity trustee) throws DuplicateScoreException { if(trustee == truster) return 0; int rank = -1; try { Trust treeOwnerTrust = getTrust(truster, trustee); if(treeOwnerTrust.getValue() > 0) return 1; else return Integer.MAX_VALUE; } catch(NotTrustedException e) { } for(Trust trust : getReceivedTrusts(trustee)) { try { Score score = getScore(truster, trust.getTruster()); if(score.getCapacity() != 0) { // If the truster has no capacity, he can't give his rank // A truster only gives his rank to a trustee if he has assigned a strictly positive trust value if(trust.getValue() > 0 ) { // We give the rank to the trustee if it is better than its current rank or he has no rank yet. if(rank == -1 || score.getRank() < rank) rank = score.getRank(); } else { // If the trustee has no rank yet we give him an infinite rank. because he is distrusted by the truster. if(rank == -1) rank = Integer.MAX_VALUE; } } } catch (NotInTrustTreeException e) {} } if(rank == -1) return -1; else if(rank == Integer.MAX_VALUE) return Integer.MAX_VALUE; else return rank+1; } /** * Begins the import of a trust list. This sets a flag on this WoT which signals that the import of a trust list is in progress. * This speeds up setTrust/removeTrust as the score calculation is only performed when endTrustListImport is called. * * You MUST synchronize on this WoT around beginTrustListImport, abortTrustListImport and finishTrustListImport! * You MUST create a database transaction by synchronizing on Persistent.transactionLock(db). */ protected void beginTrustListImport() { if(logMINOR) Logger.minor(this, "beginTrustListImport()"); if(mTrustListImportInProgress) { abortTrustListImport(new RuntimeException("There was already a trust list import in progress!")); mFullScoreComputationNeeded = true; computeAllScoresWithoutCommit(); assert(mFullScoreComputationNeeded == false); } mTrustListImportInProgress = true; assert(!mFullScoreComputationNeeded); assert(computeAllScoresWithoutCommit()); // The database is intact before the import } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * * Aborts the import of a trust list and rolls back the current transaction. * * @param e The exception which triggered the abort. Will be logged to the Freenet log file. * @param logLevel The {@link LogLevel} to use when logging the abort to the Freenet log file. */ protected void abortTrustListImport(Exception e, LogLevel logLevel) { if(logMINOR) Logger.minor(this, "abortTrustListImport()"); assert(mTrustListImportInProgress); mTrustListImportInProgress = false; mFullScoreComputationNeeded = false; Persistent.checkedRollback(mDB, this, e, logLevel); assert(computeAllScoresWithoutCommit()); // Test rollback. } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * * Aborts the import of a trust list and rolls back the current transaction. * * @param e The exception which triggered the abort. Will be logged to the Freenet log file with log level {@link LogLevel.ERROR} */ protected void abortTrustListImport(Exception e) { abortTrustListImport(e, Logger.LogLevel.ERROR); } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * * Finishes the import of the current trust list and clears the "trust list * * Does NOT commit the transaction, you must do this. */ protected void finishTrustListImport() { if(logMINOR) Logger.minor(this, "finishTrustListImport()"); if(!mTrustListImportInProgress) { Logger.error(this, "There was no trust list import in progress!"); return; } if(mFullScoreComputationNeeded) { computeAllScoresWithoutCommit(); assert(!mFullScoreComputationNeeded); // It properly clears the flag assert(computeAllScoresWithoutCommit()); // computeAllScoresWithoutCommit() is stable } else assert(computeAllScoresWithoutCommit()); // Verify whether updateScoresWithoutCommit worked. mTrustListImportInProgress = false; } /** * Updates all trust trees which are affected by the given modified score. * For understanding how score calculation works you should first read {@link computeAllScores * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... updateScoreWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e);; } * }}} */ private void updateScoresWithoutCommit(final Trust oldTrust, final Trust newTrust) { if(logMINOR) Logger.minor(this, "Doing an incremental computation of all Scores..."); final long beginTime = CurrentTimeUTC.getInMillis(); // We only include the time measurement if we actually do something. // If we figure out that a full score recomputation is needed just by looking at the initial parameters, the measurement won't be included. boolean includeMeasurement = false; final boolean trustWasCreated = (oldTrust == null); final boolean trustWasDeleted = (newTrust == null); final boolean trustWasModified = !trustWasCreated && !trustWasDeleted; if(trustWasCreated && trustWasDeleted) throw new NullPointerException("No old/new trust specified."); if(trustWasModified && oldTrust.getTruster() != newTrust.getTruster()) throw new IllegalArgumentException("oldTrust has different truster, oldTrust:" + oldTrust + "; newTrust: " + newTrust); if(trustWasModified && oldTrust.getTrustee() != newTrust.getTrustee()) throw new IllegalArgumentException("oldTrust has different trustee, oldTrust:" + oldTrust + "; newTrust: " + newTrust); // We cannot iteratively REMOVE an inherited rank from the trustees because we don't know whether there is a circle in the trust values // which would make the current identity get its old rank back via the circle: computeRank searches the trusters of an identity for the best // rank, if we remove the rank from an identity, all its trustees will have a better rank and if one of them trusts the original identity // then this function would run into an infinite loop. Decreasing or incrementing an existing rank is possible with this function because // the rank received from the trustees will always be higher (that is exactly 1 more) than this identities rank. if(trustWasDeleted) { mFullScoreComputationNeeded = true; } if(!mFullScoreComputationNeeded && (trustWasCreated || trustWasModified)) { includeMeasurement = true; for(OwnIdentity treeOwner : getAllOwnIdentities()) { try { // Throws to abort the update of the trustee's score: If the truster has no rank or capacity in the tree owner's view then we don't need to update the trustee's score. if(getScore(treeOwner, newTrust.getTruster()).getCapacity() == 0) continue; } catch(NotInTrustTreeException e) { continue; } // See explanation above "We cannot iteratively REMOVE an inherited rank..." if(trustWasModified && oldTrust.getValue() > 0 && newTrust.getValue() <= 0) { mFullScoreComputationNeeded = true; break; } final LinkedList<Trust> unprocessedEdges = new LinkedList<Trust>(); unprocessedEdges.add(newTrust); while(!unprocessedEdges.isEmpty()) { final Trust trust = unprocessedEdges.removeFirst(); final Identity trustee = trust.getTrustee(); if(trustee == treeOwner) continue; Score currentStoredTrusteeScore; try { currentStoredTrusteeScore = getScore(treeOwner, trustee); } catch(NotInTrustTreeException e) { currentStoredTrusteeScore = new Score(this, treeOwner, trustee, 0, -1, 0); } final Score oldScore = currentStoredTrusteeScore.clone(); boolean oldShouldFetch = shouldFetchIdentity(trustee); final int newScoreValue = computeScoreValue(treeOwner, trustee); final int newRank = computeRank(treeOwner, trustee); final int newCapacity = computeCapacity(treeOwner, trustee, newRank); final Score newScore = new Score(this, treeOwner, trustee, newScoreValue, newRank, newCapacity); // Normally we couldn't detect the following two cases due to circular trust values. However, if an own identity assigns a trust value, // the rank and capacity are always computed based on the trust value of the own identity so we must also check this here: if((oldScore.getRank() >= 0 && oldScore.getRank() < Integer.MAX_VALUE) // It had an inheritable rank && (newScore.getRank() == -1 || newScore.getRank() == Integer.MAX_VALUE)) { // It has no inheritable rank anymore mFullScoreComputationNeeded = true; break; } if(oldScore.getCapacity() > 0 && newScore.getCapacity() == 0) { mFullScoreComputationNeeded = true; break; } // We are OK to update it now. We must not update the values of the stored score object before determining whether we need // a full score computation - the full computation needs the old values of the object. currentStoredTrusteeScore.setValue(newScore.getScore()); currentStoredTrusteeScore.setRank(newScore.getRank()); currentStoredTrusteeScore.setCapacity(newScore.getCapacity()); // Identities should not get into the queue if they have no rank, see the large if() about 20 lines below assert(currentStoredTrusteeScore.getRank() >= 0); if(currentStoredTrusteeScore.getRank() >= 0) currentStoredTrusteeScore.storeWithoutCommit(); // If fetch status changed from false to true, we need to start fetching it // If the capacity changed from 0 to positive, we need to refetch the current edition: Identities with capacity 0 cannot // cause new identities to be imported from their trust list, capacity > 0 allows this. // If the fetch status changed from true to false, we need to stop fetching it if((!oldShouldFetch || (oldScore.getCapacity()== 0 && newScore.getCapacity() > 0)) && shouldFetchIdentity(trustee)) { if(!oldShouldFetch) if(logDEBUG) Logger.debug(this, "Fetch status changed from false to true, refetching " + trustee); else if(logDEBUG) Logger.debug(this, "Capacity changed from 0 to " + newScore.getCapacity() + ", refetching" + trustee); trustee.markForRefetch(); trustee.storeWithoutCommit(); mFetcher.storeStartFetchCommandWithoutCommit(trustee); } else if(oldShouldFetch && !shouldFetchIdentity(trustee)) { if(logDEBUG) Logger.debug(this, "Fetch status changed from true to false, aborting fetch of " + trustee); mFetcher.storeAbortFetchCommandWithoutCommit(trustee); } // If the rank or capacity changed then the trustees might be affected because the could have inherited theirs if(oldScore.getRank() != newScore.getRank() || oldScore.getCapacity() != newScore.getCapacity()) { // If this identity has no capacity or no rank then it cannot affect its trustees: // (- If it had none and it has none now then there is none which can be inherited, this is obvious) // - If it had one before and it was removed, this algorithm will have aborted already because a full computation is needed if(newScore.getCapacity() > 0 || (newScore.getRank() >= 0 && newScore.getRank() < Integer.MAX_VALUE)) { // We need to update the trustees of trustee for(Trust givenTrust : getGivenTrusts(trustee)) { unprocessedEdges.add(givenTrust); } } } } if(mFullScoreComputationNeeded) break; } } if(includeMeasurement) { ++mIncrementalScoreRecomputationCount; mIncrementalScoreRecomputationMilliseconds += CurrentTimeUTC.getInMillis() - beginTime; } if(logMINOR) { final String time = includeMeasurement ? ("Stats: Amount: " + mIncrementalScoreRecomputationCount + "; Avg Time:" + getAverageIncrementalScoreRecomputationTime() + "s") : ("Time not measured: Computation was aborted before doing anything."); if(!mFullScoreComputationNeeded) Logger.minor(this, "Incremental computation of all Scores finished. " + time); else Logger.minor(this, "Incremental computation of all Scores not possible, full computation is needed. " + time); } if(!mTrustListImportInProgress) { if(mFullScoreComputationNeeded) { // TODO: Optimization: This uses very much CPU and memory. Write a partial computation function... // TODO: Optimization: While we do not have a partial computation function, we could at least optimize computeAllScores to NOT // keep all objects in memory etc. computeAllScoresWithoutCommit(); assert(computeAllScoresWithoutCommit()); // computeAllScoresWithoutCommit is stable } else { assert(computeAllScoresWithoutCommit()); // This function worked correctly. } } else { // a trust list import is in progress // We not do the following here because it would cause too much CPU usage during debugging: Trust lists are large and therefore // updateScoresWithoutCommit is called often during import of a single trust list // assert(computeAllScoresWithoutCommit()); } } /* Client interface functions */ public synchronized Identity addIdentity(String requestURI) throws MalformedURLException, InvalidParameterException { try { getIdentityByURI(requestURI); throw new InvalidParameterException("We already have this identity"); } catch(UnknownIdentityException e) { final Identity identity = new Identity(this, requestURI, null, false); identity.storeAndCommit(); if(logDEBUG) Logger.debug(this, "Created identity " + identity); // The identity hasn't received a trust value. Therefore, there is no reason to fetch it and we don't notify the IdentityFetcher. // TODO: Document this function and the UI which uses is to warn the user that the identity won't be fetched without trust. return identity; } } public OwnIdentity createOwnIdentity(String nickName, boolean publishTrustList, String context) throws MalformedURLException, InvalidParameterException { FreenetURI[] keypair = getPluginRespirator().getHLSimpleClient().generateKeyPair(WOT_NAME); return createOwnIdentity(keypair[0], nickName, publishTrustList, context); } /** * @param context A context with which you want to use the identity. Null if you want to add it later. */ public synchronized OwnIdentity createOwnIdentity(FreenetURI insertURI, String nickName, boolean publishTrustList, String context) throws MalformedURLException, InvalidParameterException { synchronized(Persistent.transactionLock(mDB)) { OwnIdentity identity; try { identity = getOwnIdentityByURI(insertURI); throw new InvalidParameterException("The URI you specified is already used by the own identity " + identity.getNickname() + "."); } catch(UnknownIdentityException uie) { identity = new OwnIdentity(this, insertURI, nickName, publishTrustList); if(context != null) identity.addContext(context); if(publishTrustList) { identity.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); /* TODO: make configureable */ identity.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.DEFAULT_PUZZLE_COUNT)); } try { identity.storeWithoutCommit(); initTrustTreeWithoutCommit(identity); beginTrustListImport(); // Incremental score computation has proven to be very very slow when creating identities so we just schedule a full computation. mFullScoreComputationNeeded = true; for(String seedURI : SEED_IDENTITIES) { try { setTrustWithoutCommit(identity, getIdentityByURI(seedURI), (byte)100, "Automatically assigned trust to a seed identity."); } catch(UnknownIdentityException e) { Logger.error(this, "SHOULD NOT HAPPEN: Seed identity not known: " + e); } } finishTrustListImport(); Persistent.checkedCommit(mDB, this); if(mIntroductionClient != null) mIntroductionClient.nextIteration(); // This will make it fetch more introduction puzzles. if(logDEBUG) Logger.debug(this, "Successfully created a new OwnIdentity (" + identity.getNickname() + ")"); return identity; } catch(RuntimeException e) { abortTrustListImport(e); // Rolls back for us throw e; // Satisfy the compiler } } } } /** * This "deletes" an {@link OwnIdentity} by replacing it with an {@link Identity}. * * The {@link OwnIdentity} is not deleted because this would be a security issue: * If other {@link OwnIdentity}s have assigned a trust value to it, the trust value would be gone if there is no {@link Identity} object to be the target * * @param id The {@link Identity.IdentityID} of the identity. * @throws UnknownIdentityException If there is no {@link OwnIdentity} with the given ID. Also thrown if a non-own identity exists with the given ID. */ public synchronized void deleteOwnIdentity(String id) throws UnknownIdentityException { Logger.normal(this, "deleteOwnIdentity(): Starting... "); synchronized(mPuzzleStore) { synchronized(mFetcher) { synchronized(Persistent.transactionLock(mDB)) { final OwnIdentity oldIdentity = getOwnIdentityByID(id); try { Logger.normal(this, "Deleting an OwnIdentity by converting it to a non-own Identity: " + oldIdentity); // We don't need any score computations to happen (explanation will follow below) so we don't need the following: /* beginTrustListImport(); */ // This function messes with the score graph manually so it is a good idea to check whether it is intact before and afterwards. assert(computeAllScoresWithoutCommit()); final Identity newIdentity; try { newIdentity = new Identity(this, oldIdentity.getRequestURI(), oldIdentity.getNickname(), oldIdentity.doesPublishTrustList()); } catch(MalformedURLException e) { // The data was taken from the OwnIdentity so this shouldn't happen throw new RuntimeException(e); } catch (InvalidParameterException e) { // The data was taken from the OwnIdentity so this shouldn't happen throw new RuntimeException(e); } newIdentity.setContexts(oldIdentity.getContexts()); newIdentity.setProperties(oldIdentity.getProperties()); try { newIdentity.setEdition(oldIdentity.getEdition()); } catch (InvalidParameterException e) { // The data was taken from old identity so this shouldn't happen throw new RuntimeException(e); } // In theory we do not need to re-fetch the current trust list edition: // The trust list of an own identity is always stored completely in the database, i.e. all trustees exist. // HOWEVER if the user had used the restoreOwnIdentity feature and then used this function, it might be the case that // the current edition of the old OwndIdentity was not fetched yet. // So we set the fetch state to FetchState.Fetched if the oldIdentity's fetch state was like that as well. if(oldIdentity.getCurrentEditionFetchState() == FetchState.Fetched) { newIdentity.onFetched(oldIdentity.getLastFetchedDate()); } // An else to set the fetch state to FetchState.NotFetched is not necessary, newIdentity.setEdition() did that already. newIdentity.storeWithoutCommit(); // Copy all received trusts. // We don't have to modify them because they are user-assigned values and the assignment // of the user does not change just because the type of the identity changes. for(Trust oldReceivedTrust : getReceivedTrusts(oldIdentity)) { Trust newReceivedTrust; try { newReceivedTrust = new Trust(this, oldReceivedTrust.getTruster(), newIdentity, oldReceivedTrust.getValue(), oldReceivedTrust.getComment()); } catch (InvalidParameterException e) { // The data was taken from the old Trust so this shouldn't happen throw new RuntimeException(e); } // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newReceivedTrust.equals(oldReceivedTrust)); */ oldReceivedTrust.deleteWithoutCommit(); newReceivedTrust.storeWithoutCommit(); } assert(getReceivedTrusts(oldIdentity).size() == 0); // Copy all received scores. // We don't have to modify them because the rating of the identity from the perspective of a // different own identity should NOT be dependent upon whether it is an own identity or not. for(Score oldScore : getScores(oldIdentity)) { Score newScore = new Score(this, oldScore.getTruster(), newIdentity, oldScore.getScore(), oldScore.getRank(), oldScore.getCapacity()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newScore.equals(oldScore)); */ oldScore.deleteWithoutCommit(); newScore.storeWithoutCommit(); } assert(getScores(oldIdentity).size() == 0); // Delete all given scores: // Non-own identities do not assign scores to other identities so we can just delete them. for(Score oldScore : getGivenScores(oldIdentity)) { final Identity trustee = oldScore.getTrustee(); final boolean oldShouldFetchTrustee = shouldFetchIdentity(trustee); oldScore.deleteWithoutCommit(); // If the OwnIdentity which we are converting was the only source of trust to the trustee // of this Score value, the should-fetch state of the trustee might change to false. if(oldShouldFetchTrustee && shouldFetchIdentity(trustee) == false) { mFetcher.storeAbortFetchCommandWithoutCommit(trustee); } } assert(getGivenScores(oldIdentity).size() == 0); // Copy all given trusts: // We don't have to use the removeTrust/setTrust functions because the score graph does not need updating: // - To the rating of the converted identity in the score graphs of other own identities it is irrelevant // whether it is an own identity or not. The rating should never depend on whether it is an own identity! // - Non-own identities do not have a score graph. So the score graph of the converted identity is deleted // completely and therefore it does not need to be updated. for(Trust oldGivenTrust : getGivenTrusts(oldIdentity)) { Trust newGivenTrust; try { newGivenTrust = new Trust(this, newIdentity, oldGivenTrust.getTrustee(), oldGivenTrust.getValue(), oldGivenTrust.getComment()); } catch (InvalidParameterException e) { // The data was taken from the old Trust so this shouldn't happen throw new RuntimeException(e); } // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newGivenTrust.equals(oldGivenTrust)); */ oldGivenTrust.deleteWithoutCommit(); newGivenTrust.storeWithoutCommit(); } mPuzzleStore.onIdentityDeletion(oldIdentity); mFetcher.storeAbortFetchCommandWithoutCommit(oldIdentity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. oldIdentity.deleteWithoutCommit(); mFetcher.storeStartFetchCommandWithoutCommit(newIdentity); // This function messes with the score graph manually so it is a good idea to check whether it is intact before and afterwards. assert(computeAllScoresWithoutCommit()); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } Logger.normal(this, "deleteOwnIdentity(): Finished."); } /** * NOTICE: When changing this function, please also take care of {@link OwnIdentity.isRestoreInProgress()} */ public synchronized void restoreOwnIdentity(FreenetURI insertFreenetURI) throws MalformedURLException, InvalidParameterException { Logger.normal(this, "restoreOwnIdentity(): Starting... "); OwnIdentity identity; synchronized(mPuzzleStore) { synchronized(mFetcher) { synchronized(Persistent.transactionLock(mDB)) { try { long edition = 0; try { edition = Math.max(edition, insertFreenetURI.getEdition()); } catch(IllegalStateException e) { // The user supplied URI did not have an edition specified } try { // Try replacing an existing non-own version of the identity with an OwnIdentity Identity oldIdentity = getIdentityByURI(insertFreenetURI); if(oldIdentity instanceof OwnIdentity) throw new InvalidParameterException("There is already an own identity with the given URI pair."); Logger.normal(this, "Restoring an already known identity from Freenet: " + oldIdentity); // Normally, one would expect beginTrustListImport() to happen close to the actual trust list changes later on in this function. // But beginTrustListImport() contains an assert(computeAllScoresWithoutCommit()) and that call to the score computation reference // implementation will fail if two identities with the same ID exist. // This would be the case later on - we cannot delete the non-own version of the OwnIdentity before we modified the trust graph // but we must also store the own version to be able to modify the trust graph. beginTrustListImport(); // We already have fetched this identity as a stranger's one. We need to update the database. identity = new OwnIdentity(this, insertFreenetURI, oldIdentity.getNickname(), oldIdentity.doesPublishTrustList()); /* We re-fetch the most recent edition to make sure all trustees are imported */ edition = Math.max(edition, oldIdentity.getEdition()); identity.restoreEdition(edition, oldIdentity.getLastFetchedDate()); identity.setContexts(oldIdentity.getContexts()); identity.setProperties(oldIdentity.getProperties()); identity.storeWithoutCommit(); initTrustTreeWithoutCommit(identity); // Copy all received trusts. // We don't have to modify them because they are user-assigned values and the assignment // of the user does not change just because the type of the identity changes. for(Trust oldReceivedTrust : getReceivedTrusts(oldIdentity)) { Trust newReceivedTrust = new Trust(this, oldReceivedTrust.getTruster(), identity, oldReceivedTrust.getValue(), oldReceivedTrust.getComment()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newReceivedTrust.equals(oldReceivedTrust)); */ oldReceivedTrust.deleteWithoutCommit(); newReceivedTrust.storeWithoutCommit(); } assert(getReceivedTrusts(oldIdentity).size() == 0); // Copy all received scores. // We don't have to modify them because the rating of the identity from the perspective of a // different own identity should NOT be dependent upon whether it is an own identity or not. for(Score oldScore : getScores(oldIdentity)) { Score newScore = new Score(this, oldScore.getTruster(), identity, oldScore.getScore(), oldScore.getRank(), oldScore.getCapacity()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newScore.equals(oldScore)); */ oldScore.deleteWithoutCommit(); newScore.storeWithoutCommit(); } assert(getScores(oldIdentity).size() == 0); // What we do NOT have to deal with is the given scores of the old identity: // Given scores do NOT exist for non-own identities, so there are no old ones to update. // Of cause there WILL be scores because it is an own identity now. // They will be created automatically when updating the given trusts // - so thats what we will do now. // Update all given trusts for(Trust givenTrust : getGivenTrusts(oldIdentity)) { // TODO: Instead of using the regular removeTrustWithoutCommit on all trust values, we could: // - manually delete the old Trust objects from the database // - manually store the new trust objects // - Realize that only the trust graph of the restored identity needs to be updated and write an optimized version // of setTrustWithoutCommit which deals with that. // But before we do that, we should first do the existing possible optimization of removeTrustWithoutCommit: // To get rid of removeTrustWithoutCommit always triggering a FULL score recomputation and instead make // it only update the parts of the trust graph which are affected. // Maybe the optimized version is fast enough that we don't have to do the optimization which this TODO suggests. removeTrustWithoutCommit(givenTrust); setTrustWithoutCommit(identity, givenTrust.getTrustee(), givenTrust.getValue(), givenTrust.getComment()); } // We do not call finishTrustListImport() now: It might trigger execution of computeAllScoresWithoutCommit // which would re-create scores of the old identity. We later call it AFTER deleting the old identity. /* finishTrustListImport(); */ mPuzzleStore.onIdentityDeletion(oldIdentity); mFetcher.storeAbortFetchCommandWithoutCommit(oldIdentity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. oldIdentity.deleteWithoutCommit(); finishTrustListImport(); } catch (UnknownIdentityException e) { // The identity did NOT exist as non-own identity yet so we can just create an OwnIdentity and store it. identity = new OwnIdentity(this, insertFreenetURI, null, false); Logger.normal(this, "Restoring not-yet-known identity from Freenet: " + identity); identity.restoreEdition(edition, null); // Store the new identity identity.storeWithoutCommit(); initTrustTreeWithoutCommit(identity); } mFetcher.storeStartFetchCommandWithoutCommit(identity); // This function messes with the trust graph manually so it is a good idea to check whether it is intact afterwards. assert(computeAllScoresWithoutCommit()); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { abortTrustListImport(e); Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } Logger.normal(this, "restoreOwnIdentity(): Finished."); } public synchronized void setTrust(String ownTrusterID, String trusteeID, byte value, String comment) throws UnknownIdentityException, NumberFormatException, InvalidParameterException { final OwnIdentity truster = getOwnIdentityByID(ownTrusterID); Identity trustee = getIdentityByID(trusteeID); setTrust(truster, trustee, value, comment); } public synchronized void removeTrust(String ownTrusterID, String trusteeID) throws UnknownIdentityException { final OwnIdentity truster = getOwnIdentityByID(ownTrusterID); final Identity trustee = getIdentityByID(trusteeID); synchronized(mFetcher) { synchronized(Persistent.transactionLock(mDB)) { try { removeTrustWithoutCommit(truster, trustee); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } public synchronized void addContext(String ownIdentityID, String newContext) throws UnknownIdentityException, InvalidParameterException { final Identity identity = getOwnIdentityByID(ownIdentityID); identity.addContext(newContext); identity.storeAndCommit(); if(logDEBUG) Logger.debug(this, "Added context '" + newContext + "' to identity '" + identity.getNickname() + "'"); } public synchronized void removeContext(String ownIdentityID, String context) throws UnknownIdentityException, InvalidParameterException { final Identity identity = getOwnIdentityByID(ownIdentityID); identity.removeContext(context); identity.storeAndCommit(); if(logDEBUG) Logger.debug(this, "Removed context '" + context + "' from identity '" + identity.getNickname() + "'"); } public synchronized String getProperty(String identityID, String property) throws InvalidParameterException, UnknownIdentityException { return getIdentityByID(identityID).getProperty(property); } public synchronized void setProperty(String ownIdentityID, String property, String value) throws UnknownIdentityException, InvalidParameterException { Identity identity = getOwnIdentityByID(ownIdentityID); identity.setProperty(property, value); identity.storeAndCommit(); if(logDEBUG) Logger.debug(this, "Added property '" + property + "=" + value + "' to identity '" + identity.getNickname() + "'"); } public synchronized void removeProperty(String ownIdentityID, String property) throws UnknownIdentityException, InvalidParameterException { final Identity identity = getOwnIdentityByID(ownIdentityID); identity.removeProperty(property); identity.storeAndCommit(); if(logDEBUG) Logger.debug(this, "Removed property '" + property + "' from identity '" + identity.getNickname() + "'"); } public String getVersion() { return Version.getMarketingVersion(); } public long getRealVersion() { return Version.getRealVersion(); } public String getString(String key) { return getBaseL10n().getString(key); } public void setLanguage(LANGUAGE newLanguage) { WebOfTrust.l10n = new PluginL10n(this, newLanguage); if(logDEBUG) Logger.debug(this, "Set LANGUAGE to: " + newLanguage.isoCode); } public PluginRespirator getPluginRespirator() { return mPR; } public ExtObjectContainer getDatabase() { return mDB; } public Configuration getConfig() { return mConfig; } public IdentityFetcher getIdentityFetcher() { return mFetcher; } public XMLTransformer getXMLTransformer() { return mXMLTransformer; } public IntroductionPuzzleStore getIntroductionPuzzleStore() { return mPuzzleStore; } public IntroductionClient getIntroductionClient() { return mIntroductionClient; } public RequestClient getRequestClient() { return mRequestClient; } /** * This is where our L10n files are stored. * @return Path of our L10n files. */ public String getL10nFilesBasePath() { return "plugins/WebOfTrust/l10n/"; } /** * This is the mask of our L10n files : lang_en.l10n, lang_de.10n, ... * @return Mask of the L10n files. */ public String getL10nFilesMask() { return "lang_${lang}.l10n"; } /** * Override L10n files are stored on the disk, their names should be explicit * we put here the plugin name, and the "override" indication. Plugin L10n * override is not implemented in the node yet. * @return Mask of the override L10n files. */ public String getL10nOverrideFilesMask() { return "WebOfTrust_lang_${lang}.override.l10n"; } /** * Get the ClassLoader of this plugin. This is necessary when getting * resources inside the plugin's Jar, for example L10n files. * @return ClassLoader object */ public ClassLoader getPluginClassLoader() { return WebOfTrust.class.getClassLoader(); } /** * Access to the current L10n data. * * @return L10n object. */ public BaseL10n getBaseL10n() { return WebOfTrust.l10n.getBase(); } public int getNumberOfFullScoreRecomputations() { return mFullScoreRecomputationCount; } public synchronized double getAverageFullScoreRecomputationTime() { return (double)mFullScoreRecomputationMilliseconds / ((mFullScoreRecomputationCount!= 0 ? mFullScoreRecomputationCount : 1) * 1000); } public int getNumberOfIncrementalScoreRecomputations() { return mIncrementalScoreRecomputationCount; } public synchronized double getAverageIncrementalScoreRecomputationTime() { return (double)mIncrementalScoreRecomputationMilliseconds / ((mIncrementalScoreRecomputationCount!= 0 ? mIncrementalScoreRecomputationCount : 1) * 1000); } /** * Tests whether two WoT are equal. * This is a complex operation in terms of execution time and memory usage and only intended for being used in unit tests. */ public synchronized boolean equals(Object obj) { if(obj == this) return true; if(!(obj instanceof WebOfTrust)) return false; WebOfTrust other = (WebOfTrust)obj; synchronized(other) { { // Compare own identities final ObjectSet<OwnIdentity> allIdentities = getAllOwnIdentities(); if(allIdentities.size() != other.getAllOwnIdentities().size()) return false; for(OwnIdentity identity : allIdentities) { try { if(!identity.equals(other.getOwnIdentityByID(identity.getID()))) return false; } catch(UnknownIdentityException e) { return false; } } } { // Compare identities final ObjectSet<Identity> allIdentities = getAllIdentities(); if(allIdentities.size() != other.getAllIdentities().size()) return false; for(Identity identity : allIdentities) { try { if(!identity.equals(other.getIdentityByID(identity.getID()))) return false; } catch(UnknownIdentityException e) { return false; } } } { // Compare trusts final ObjectSet<Trust> allTrusts = getAllTrusts(); if(allTrusts.size() != other.getAllTrusts().size()) return false; for(Trust trust : allTrusts) { try { Identity otherTruster = other.getIdentityByID(trust.getTruster().getID()); Identity otherTrustee = other.getIdentityByID(trust.getTrustee().getID()); if(!trust.equals(other.getTrust(otherTruster, otherTrustee))) return false; } catch(UnknownIdentityException e) { return false; } catch(NotTrustedException e) { return false; } } } { // Compare scores final ObjectSet<Score> allScores = getAllScores(); if(allScores.size() != other.getAllScores().size()) return false; for(Score score : allScores) { try { OwnIdentity otherTruster = other.getOwnIdentityByID(score.getTruster().getID()); Identity otherTrustee = other.getIdentityByID(score.getTrustee().getID()); if(!score.equals(other.getScore(otherTruster, otherTrustee))) return false; } catch(UnknownIdentityException e) { return false; } catch(NotInTrustTreeException e) { return false; } } } } return true; } }
private synchronized void deleteDuplicateObjects() { synchronized(mPuzzleStore) { // Needed for deleteIdentity() synchronized(mFetcher) { // // Needed for deleteIdentity() synchronized(Persistent.transactionLock(mDB)) { try { HashSet<String> deleted = new HashSet<String>(); if(logDEBUG) Logger.debug(this, "Searching for duplicate identities ..."); for(Identity identity : getAllIdentities()) { Query q = mDB.query(); q.constrain(Identity.class); q.descend("mID").constrain(identity.getID()); q.constrain(identity).identity().not(); ObjectSet<Identity> duplicates = new Persistent.InitializingObjectSet<Identity>(this, q); for(Identity duplicate : duplicates) { if(deleted.contains(duplicate.getID()) == false) { Logger.error(duplicate, "Deleting duplicate identity " + duplicate.getRequestURI()); deleteWithoutCommit(duplicate); Persistent.checkedCommit(mDB, this); } } deleted.add(identity.getID()); } Persistent.checkedCommit(mDB, this); if(logDEBUG) Logger.debug(this, "Finished searching for duplicate identities."); } catch(RuntimeException e) { Persistent.checkedRollback(mDB, this, e); } } } } // synchronized(this) { // For removeTrustWithoutCommit. Done at function level already. synchronized(mFetcher) { // For removeTrustWithoutCommit synchronized(Persistent.transactionLock(mDB)) { try { if(logDEBUG) Logger.debug(this, "Searching for duplicate Trust objects ..."); boolean duplicateTrustFound = false; for(OwnIdentity truster : getAllOwnIdentities()) { HashSet<String> givenTo = new HashSet<String>(); for(Trust trust : getGivenTrusts(truster)) { if(givenTo.contains(trust.getTrustee().getID()) == false) givenTo.add(trust.getTrustee().getID()); else { Logger.error(this, "Deleting duplicate given trust:" + trust); removeTrustWithoutCommit(trust); duplicateTrustFound = true; } } } if(duplicateTrustFound) { computeAllScoresWithoutCommit(); } Persistent.checkedCommit(mDB, this); if(logDEBUG) Logger.debug(this, "Finished searching for duplicate trust objects."); } catch(RuntimeException e) { Persistent.checkedRollback(mDB, this, e); } } // synchronized(Persistent.transactionLock(mDB)) { } // synchronized(mFetcher) { /* TODO: Also delete duplicate score */ } /** * Debug function for deleting trusts or scores of which one of the involved partners is missing. */ private synchronized void deleteOrphanObjects() { synchronized(Persistent.transactionLock(mDB)) { try { boolean orphanTrustFound = false; Query q = mDB.query(); q.constrain(Trust.class); q.descend("mTruster").constrain(null).identity().or(q.descend("mTrustee").constrain(null).identity()); ObjectSet<Trust> orphanTrusts = new Persistent.InitializingObjectSet<Trust>(this, q); for(Trust trust : orphanTrusts) { if(trust.getTruster() != null && trust.getTrustee() != null) { // TODO: Remove this workaround for the db4o bug as soon as we are sure that it does not happen anymore. Logger.error(this, "Db4o bug: constrain(null).identity() did not work for " + trust); continue; } Logger.error(trust, "Deleting orphan trust, truster = " + trust.getTruster() + ", trustee = " + trust.getTrustee()); orphanTrustFound = true; trust.deleteWithoutCommit(); } if(orphanTrustFound) { computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); } } catch(Exception e) { Persistent.checkedRollback(mDB, this, e); } } synchronized(Persistent.transactionLock(mDB)) { try { boolean orphanScoresFound = false; Query q = mDB.query(); q.constrain(Score.class); q.descend("mTruster").constrain(null).identity().or(q.descend("mTrustee").constrain(null).identity()); ObjectSet<Score> orphanScores = new Persistent.InitializingObjectSet<Score>(this, q); for(Score score : orphanScores) { if(score.getTruster() != null && score.getTrustee() != null) { // TODO: Remove this workaround for the db4o bug as soon as we are sure that it does not happen anymore. Logger.error(this, "Db4o bug: constrain(null).identity() did not work for " + score); continue; } Logger.error(score, "Deleting orphan score, truster = " + score.getTruster() + ", trustee = " + score.getTrustee()); orphanScoresFound = true; score.deleteWithoutCommit(); } if(orphanScoresFound) { computeAllScoresWithoutCommit(); Persistent.checkedCommit(mDB, this); } } catch(Exception e) { Persistent.checkedRollback(mDB, this, e); } } } /** * Warning: This function is not synchronized, use it only in single threaded mode. * @return The WOT database format version of the given database. -1 if there is no Configuration stored in it or multiple configurations exist. */ @SuppressWarnings("deprecation") private static int peekDatabaseFormatVersion(WebOfTrust wot, ExtObjectContainer database) { final Query query = database.query(); query.constrain(Configuration.class); @SuppressWarnings("unchecked") ObjectSet<Configuration> result = (ObjectSet<Configuration>)query.execute(); switch(result.size()) { case 1: { final Configuration config = (Configuration)result.next(); config.initializeTransient(wot, database); // For the HashMaps to stay alive we need to activate to full depth. config.checkedActivate(4); return config.getDatabaseFormatVersion(); } default: return -1; } } /** * Loads an existing Config object from the database and adds any missing default values to it, creates and stores a new one if none exists. * @return The config object. */ private synchronized Configuration getOrCreateConfig() { final Query query = mDB.query(); query.constrain(Configuration.class); final ObjectSet<Configuration> result = new Persistent.InitializingObjectSet<Configuration>(this, query); switch(result.size()) { case 1: { final Configuration config = result.next(); // For the HashMaps to stay alive we need to activate to full depth. config.checkedActivate(4); config.setDefaultValues(false); config.storeAndCommit(); return config; } case 0: { final Configuration config = new Configuration(this); config.initializeTransient(this); config.storeAndCommit(); return config; } default: throw new RuntimeException("Multiple config objects found: " + result.size()); } } /** Capacity is the maximum amount of points an identity can give to an other by trusting it. * * Values choice : * Advogato Trust metric recommends that values decrease by rounded 2.5 times. * This makes sense, making the need of 3 N+1 ranked people to overpower * the trust given by a N ranked identity. * * Number of ranks choice : * When someone creates a fresh identity, he gets the seed identity at * rank 1 and freenet developpers at rank 2. That means that * he will see people that were : * - given 7 trust by freenet devs (rank 2) * - given 17 trust by rank 3 * - given 50 trust by rank 4 * - given 100 trust by rank 5 and above. * This makes the range small enough to avoid a newbie * to even see spam, and large enough to make him see a reasonnable part * of the community right out-of-the-box. * Of course, as soon as he will start to give trust, he will put more * people at rank 1 and enlarge his WoT. */ protected static final int capacities[] = { 100,// Rank 0 : Own identities 40, // Rank 1 : Identities directly trusted by ownIdenties 16, // Rank 2 : Identities trusted by rank 1 identities 6, // So on... 2, 1 // Every identity above rank 5 can give 1 point }; // Identities with negative score have zero capacity /** * Computes the capacity of a truster. The capacity is a weight function in percent which is used to decide how much * trust points an identity can add to the score of identities which it has assigned trust values to. * The higher the rank of an identity, the less is it's capacity. * * If the rank of the identity is Integer.MAX_VALUE (infinite, this means it has only received negative or 0 trust values from identities with rank >= 0 and less * than infinite) or -1 (this means that it has only received trust values from identities with infinite rank) then its capacity is 0. * * If the truster has assigned a trust value to the trustee the capacity will be computed only from that trust value: * The decision of the truster should always overpower the view of remote identities. * * Notice that 0 is included in infinite rank to prevent identities which have only solved introduction puzzles from having a capacity. * * @param truster The {@link OwnIdentity} in whose trust tree the capacity shall be computed * @param trustee The {@link Identity} of which the capacity shall be computed. * @param rank The rank of the identity. The rank is the distance in trust steps from the OwnIdentity which views the web of trust, * - its rank is 0, the rank of its trustees is 1 and so on. Must be -1 if the truster has no rank in the tree owners view. */ protected int computeCapacity(OwnIdentity truster, Identity trustee, int rank) { if(truster == trustee) return 100; try { if(getTrust(truster, trustee).getValue() <= 0) { // Security check, if rank computation breaks this will hit. assert(rank == Integer.MAX_VALUE); return 0; } } catch(NotTrustedException e) { } if(rank == -1 || rank == Integer.MAX_VALUE) return 0; return (rank < capacities.length) ? capacities[rank] : 1; } /** * Reference-implementation of score computation. This means:<br /> * - It is not used by the real WoT code because its slow<br /> * - It is used by unit tests (and WoT) to check whether the real implementation works<br /> * - It is the function which you should read if you want to understand how WoT works.<br /> * * Computes all rank and score values and checks whether the database is correct. If wrong values are found, they are correct.<br /> * * There was a bug in the score computation for a long time which resulted in wrong computation when trust values very removed under certain conditions.<br /> * * Further, rank values are shortest paths and the path-finding algorithm is not executed from the source * to the target upon score computation: It uses the rank of the neighbor nodes to find a shortest path. * Therefore, the algorithm is very vulnerable to bugs since one wrong value will stay in the database * and affect many others. So it is useful to have this function. * * @return True if all stored scores were correct. False if there were any errors in stored scores. */ protected synchronized boolean computeAllScoresWithoutCommit() { if(logMINOR) Logger.minor(this, "Doing a full computation of all Scores..."); final long beginTime = CurrentTimeUTC.getInMillis(); boolean returnValue = true; final ObjectSet<Identity> allIdentities = getAllIdentities(); // Scores are a rating of an identity from the view of an OwnIdentity so we compute them per OwnIdentity. for(OwnIdentity treeOwner : getAllOwnIdentities()) { // At the end of the loop body, this table will be filled with the ranks of all identities which are visible for treeOwner. // An identity is visible if there is a trust chain from the owner to it. // The rank is the distance in trust steps from the treeOwner. // So the treeOwner is rank 0, the trustees of the treeOwner are rank 1 and so on. final HashMap<Identity, Integer> rankValues = new HashMap<Identity, Integer>(allIdentities.size() * 2); // Compute the rank values { // For each identity which is added to rankValues, all its trustees are added to unprocessedTrusters. // The inner loop then pulls out one unprocessed identity and computes the rank of its trustees: // All trustees which have received positive (> 0) trust will get his rank + 1 // Trustees with negative trust or 0 trust will get a rank of Integer.MAX_VALUE. // Trusters with rank Integer.MAX_VALUE cannot inherit their rank to their trustees so the trustees will get no rank at all. // Identities with no rank are considered to be not in the trust tree of the own identity and their score will be null / none. // // Further, if the treeOwner has assigned a trust value to an identity, the rank decision is done by only considering this trust value: // The decision of the own identity shall not be overpowered by the view of the remote identities. // // The purpose of differentiation between Integer.MAX_VALUE and -1 is: // Score objects of identities with rank Integer.MAX_VALUE are kept in the database because WoT will usually "hear" about those identities by seeing // them in the trust lists of trusted identities (with 0 or negative trust values). So it must store the trust values to those identities and // have a way of telling the user "this identity is not trusted" by keeping a score object of them. // Score objects of identities with rank -1 are deleted because they are the trustees of distrusted identities and we will not get to the point where // we hear about those identities because the only way of hearing about them is importing a trust list of a identity with Integer.MAX_VALUE rank // - and we never import their trust lists. // We include trust values of 0 in the set of rank Integer.MAX_VALUE (instead of only NEGATIVE trust) so that identities which only have solved // introduction puzzles cannot inherit their rank to their trustees. final LinkedList<Identity> unprocessedTrusters = new LinkedList<Identity>(); // The own identity is the root of the trust tree, it should assign itself a rank of 0 , a capacity of 100 and a symbolic score of Integer.MAX_VALUE try { Score selfScore = getScore(treeOwner, treeOwner); if(selfScore.getRank() >= 0) { // It can only give it's rank if it has a valid one rankValues.put(treeOwner, selfScore.getRank()); unprocessedTrusters.addLast(treeOwner); } else { rankValues.put(treeOwner, null); } } catch(NotInTrustTreeException e) { // This only happens in unit tests. } while(!unprocessedTrusters.isEmpty()) { final Identity truster = unprocessedTrusters.removeFirst(); final Integer trusterRank = rankValues.get(truster); // The truster cannot give his rank to his trustees because he has none (or infinite), they receive no rank at all. if(trusterRank == null || trusterRank == Integer.MAX_VALUE) { // (Normally this does not happen because we do not enqueue the identities if they have no rank but we check for security) continue; } final int trusteeRank = trusterRank + 1; for(Trust trust : getGivenTrusts(truster)) { final Identity trustee = trust.getTrustee(); final Integer oldTrusteeRank = rankValues.get(trustee); if(oldTrusteeRank == null) { // The trustee was not processed yet if(trust.getValue() > 0) { rankValues.put(trustee, trusteeRank); unprocessedTrusters.addLast(trustee); } else rankValues.put(trustee, Integer.MAX_VALUE); } else { // Breadth first search will process all rank one identities are processed before any rank two identities, etc. assert(oldTrusteeRank == Integer.MAX_VALUE || trusteeRank >= oldTrusteeRank); if(oldTrusteeRank == Integer.MAX_VALUE) { // If we found a rank less than infinite we can overwrite the old rank with this one, but only if the infinite rank was not // given by the tree owner. try { final Trust treeOwnerTrust = getTrust(treeOwner, trustee); assert(treeOwnerTrust.getValue() <= 0); // TODO: Is this correct? } catch(NotTrustedException e) { if(trust.getValue() > 0) { rankValues.put(trustee, trusteeRank); unprocessedTrusters.addLast(trustee); } } } } } } } // Rank values of all visible identities are computed now. // Next step is to compute the scores of all identities for(Identity target : allIdentities) { // The score of an identity is the sum of all weighted trust values it has received. // Each trust value is weighted with the capacity of the truster - the capacity decays with increasing rank. Integer targetScore; final Integer targetRank = rankValues.get(target); if(targetRank == null) { targetScore = null; } else { // The treeOwner trusts himself. if(targetRank == 0) { targetScore = Integer.MAX_VALUE; } else { // If the treeOwner has assigned a trust value to the target, it always overrides the "remote" score. try { targetScore = (int)getTrust(treeOwner, target).getValue(); } catch(NotTrustedException e) { targetScore = 0; for(Trust receivedTrust : getReceivedTrusts(target)) { final Identity truster = receivedTrust.getTruster(); final Integer trusterRank = rankValues.get(truster); // The capacity is a weight function for trust values which are given from an identity: // The higher the rank, the less the capacity. // If the rank is Integer.MAX_VALUE (infinite) or -1 (no rank at all) the capacity will be 0. final int capacity = computeCapacity(treeOwner, truster, trusterRank != null ? trusterRank : -1); targetScore += (receivedTrust.getValue() * capacity) / 100; } } } } Score newScore = null; if(targetScore != null) { newScore = new Score(this, treeOwner, target, targetScore, targetRank, computeCapacity(treeOwner, target, targetRank)); } boolean needToCheckFetchStatus = false; boolean oldShouldFetch = false; int oldCapacity = 0; // Now we have the rank and the score of the target computed and can check whether the database-stored score object is correct. try { Score currentStoredScore = getScore(treeOwner, target); oldCapacity = currentStoredScore.getCapacity(); if(newScore == null) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: The identity has no rank and should have no score but score was " + currentStoredScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); currentStoredScore.deleteWithoutCommit(); } else { if(!newScore.equals(currentStoredScore)) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: Should have been " + newScore + " but was " + currentStoredScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); currentStoredScore.setRank(newScore.getRank()); currentStoredScore.setCapacity(newScore.getCapacity()); currentStoredScore.setValue(newScore.getScore()); currentStoredScore.storeWithoutCommit(); } } } catch(NotInTrustTreeException e) { oldCapacity = 0; if(newScore != null) { returnValue = false; if(!mFullScoreComputationNeeded) Logger.error(this, "Correcting wrong score: No score was stored for the identity but it should be " + newScore, new RuntimeException()); needToCheckFetchStatus = true; oldShouldFetch = shouldFetchIdentity(target); newScore.storeWithoutCommit(); } } if(needToCheckFetchStatus) { // If fetch status changed from false to true, we need to start fetching it // If the capacity changed from 0 to positive, we need to refetch the current edition: Identities with capacity 0 cannot // cause new identities to be imported from their trust list, capacity > 0 allows this. // If the fetch status changed from true to false, we need to stop fetching it if((!oldShouldFetch || (oldCapacity == 0 && newScore != null && newScore.getCapacity() > 0)) && shouldFetchIdentity(target) ) { if(!oldShouldFetch) if(logDEBUG) Logger.debug(this, "Fetch status changed from false to true, refetching " + target); else if(logDEBUG) Logger.debug(this, "Capacity changed from 0 to " + newScore.getCapacity() + ", refetching" + target); target.markForRefetch(); target.storeWithoutCommit(); mFetcher.storeStartFetchCommandWithoutCommit(target); } else if(oldShouldFetch && !shouldFetchIdentity(target)) { if(logDEBUG) Logger.debug(this, "Fetch status changed from true to false, aborting fetch of " + target); mFetcher.storeAbortFetchCommandWithoutCommit(target); } } } } mFullScoreComputationNeeded = false; ++mFullScoreRecomputationCount; mFullScoreRecomputationMilliseconds += CurrentTimeUTC.getInMillis() - beginTime; if(logMINOR) { Logger.minor(this, "Full score computation finished. Amount: " + mFullScoreRecomputationCount + "; Avg Time:" + getAverageFullScoreRecomputationTime() + "s"); } return returnValue; } private synchronized void createSeedIdentities() { for(String seedURI : SEED_IDENTITIES) { Identity seed; synchronized(Persistent.transactionLock(mDB)) { try { seed = getIdentityByURI(seedURI); if(seed instanceof OwnIdentity) { OwnIdentity ownSeed = (OwnIdentity)seed; ownSeed.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); ownSeed.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.SEED_IDENTITY_PUZZLE_COUNT)); ownSeed.storeAndCommit(); } else { try { seed.setEdition(new FreenetURI(seedURI).getEdition()); seed.storeAndCommit(); } catch(InvalidParameterException e) { /* We already have the latest edition stored */ } } } catch (UnknownIdentityException uie) { try { seed = new Identity(this, seedURI, null, true); // We have to explicitely set the edition number because the constructor only considers the given edition as a hint. seed.setEdition(new FreenetURI(seedURI).getEdition()); seed.storeAndCommit(); } catch (Exception e) { Logger.error(this, "Seed identity creation error", e); } } catch (Exception e) { Persistent.checkedRollback(mDB, this, e); } } } } public void terminate() { if(logDEBUG) Logger.debug(this, "WoT plugin terminating ..."); /* We use single try/catch blocks so that failure of termination of one service does not prevent termination of the others */ try { if(mWebInterface != null) this.mWebInterface.unload(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mIntroductionClient != null) mIntroductionClient.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mIntroductionServer != null) mIntroductionServer.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mInserter != null) mInserter.terminate(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mFetcher != null) mFetcher.stop(); } catch(Exception e) { Logger.error(this, "Error during termination.", e); } try { if(mDB != null) { /* TODO: At 2009-06-15, it does not seem possible to ask db4o for whether a transaction is pending. * If it becomes possible some day, we should check that here, and log an error if there is an uncommitted transaction. * - All transactions should be committed after obtaining the lock() on the database. */ synchronized(Persistent.transactionLock(mDB)) { System.gc(); mDB.rollback(); System.gc(); mDB.close(); } } } catch(Exception e) { Logger.error(this, "Error during termination.", e); } if(logDEBUG) Logger.debug(this, "WoT plugin terminated."); } /** * Inherited event handler from FredPluginFCP, handled in <code>class FCPInterface</code>. */ public void handle(PluginReplySender replysender, SimpleFieldSet params, Bucket data, int accesstype) { mFCPInterface.handle(replysender, params, data, accesstype); } /** * Loads an own or normal identity from the database, querying on its ID. * * @param id The ID of the identity to load * @return The identity matching the supplied ID. * @throws DuplicateIdentityException if there are more than one identity with this id in the database * @throws UnknownIdentityException if there is no identity with this id in the database */ public synchronized Identity getIdentityByID(String id) throws UnknownIdentityException { final Query query = mDB.query(); query.constrain(Identity.class); query.descend("mID").constrain(id); final ObjectSet<Identity> result = new Persistent.InitializingObjectSet<Identity>(this, query); switch(result.size()) { case 1: return result.next(); case 0: throw new UnknownIdentityException(id); default: throw new DuplicateIdentityException(id, result.size()); } } /** * Gets an OwnIdentity by its ID. * * @param id The unique identifier to query an OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if there is now OwnIdentity with that id */ public synchronized OwnIdentity getOwnIdentityByID(String id) throws UnknownIdentityException { final Query query = mDB.query(); query.constrain(OwnIdentity.class); query.descend("mID").constrain(id); final ObjectSet<OwnIdentity> result = new Persistent.InitializingObjectSet<OwnIdentity>(this, query); switch(result.size()) { case 1: return result.next(); case 0: throw new UnknownIdentityException(id); default: throw new DuplicateIdentityException(id, result.size()); } } /** * Loads an identity from the database, querying on its requestURI (a valid {@link FreenetURI}) * * @param uri The requestURI of the identity * @return The identity matching the supplied requestURI * @throws UnknownIdentityException if there is no identity with this id in the database */ public Identity getIdentityByURI(FreenetURI uri) throws UnknownIdentityException { return getIdentityByID(IdentityID.constructAndValidateFromURI(uri).toString()); } /** * Loads an identity from the database, querying on its requestURI (as String) * * @param uri The requestURI of the identity which will be converted to {@link FreenetURI} * @return The identity matching the supplied requestURI * @throws UnknownIdentityException if there is no identity with this id in the database * @throws MalformedURLException if the requestURI isn't a valid FreenetURI */ public Identity getIdentityByURI(String uri) throws UnknownIdentityException, MalformedURLException { return getIdentityByURI(new FreenetURI(uri)); } /** * Gets an OwnIdentity by its requestURI (a {@link FreenetURI}). * The OwnIdentity's unique identifier is extracted from the supplied requestURI. * * @param uri The requestURI of the desired OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if the OwnIdentity isn't in the database */ public OwnIdentity getOwnIdentityByURI(FreenetURI uri) throws UnknownIdentityException { return getOwnIdentityByID(IdentityID.constructAndValidateFromURI(uri).toString()); } /** * Gets an OwnIdentity by its requestURI (as String). * The given String is converted to {@link FreenetURI} in order to extract a unique id. * * @param uri The requestURI (as String) of the desired OwnIdentity * @return The requested OwnIdentity * @throws UnknownIdentityException if the OwnIdentity isn't in the database * @throws MalformedURLException if the supplied requestURI is not a valid FreenetURI */ public OwnIdentity getOwnIdentityByURI(String uri) throws UnknownIdentityException, MalformedURLException { return getOwnIdentityByURI(new FreenetURI(uri)); } /** * Returns all identities that are in the database * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all identities present in the database */ public ObjectSet<Identity> getAllIdentities() { final Query query = mDB.query(); query.constrain(Identity.class); return new Persistent.InitializingObjectSet<Identity>(this, query); } public static enum SortOrder { ByNicknameAscending, ByNicknameDescending, ByScoreAscending, ByScoreDescending, ByLocalTrustAscending, ByLocalTrustDescending } /** * Get a filtered and sorted list of identities. * You have to synchronize on this WoT when calling the function and processing the returned list. */ public ObjectSet<Identity> getAllIdentitiesFilteredAndSorted(OwnIdentity truster, String nickFilter, SortOrder sortInstruction) { Query q = mDB.query(); switch(sortInstruction) { case ByNicknameAscending: q.constrain(Identity.class); q.descend("mNickname").orderAscending(); break; case ByNicknameDescending: q.constrain(Identity.class); q.descend("mNickname").orderDescending(); break; case ByScoreAscending: q.constrain(Score.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderAscending(); q = q.descend("mTrustee"); break; case ByScoreDescending: // TODO: This excludes identities which have no score q.constrain(Score.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderDescending(); q = q.descend("mTrustee"); break; case ByLocalTrustAscending: q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderAscending(); q = q.descend("mTrustee"); break; case ByLocalTrustDescending: // TODO: This excludes untrusted identities. q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mValue").orderDescending(); q = q.descend("mTrustee"); break; } if(nickFilter != null) { nickFilter = nickFilter.trim(); if(!nickFilter.equals("")) q.descend("mNickname").constrain(nickFilter).like(); } return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all non-own identities that are in the database. * * You have to synchronize on this WoT when calling the function and processing the returned list! */ public ObjectSet<Identity> getAllNonOwnIdentities() { final Query q = mDB.query(); q.constrain(Identity.class); q.constrain(OwnIdentity.class).not(); return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all non-own identities that are in the database, sorted descending by their date of modification, i.e. recently * modified identities will be at the beginning of the list. * * You have to synchronize on this WoT when calling the function and processing the returned list! * * Used by the IntroductionClient for fetching puzzles from recently modified identities. */ public ObjectSet<Identity> getAllNonOwnIdentitiesSortedByModification () { final Query q = mDB.query(); q.constrain(Identity.class); q.constrain(OwnIdentity.class).not(); /* TODO: As soon as identities announce that they were online every day, uncomment the following line */ /* q.descend("mLastChangedDate").constrain(new Date(CurrentTimeUTC.getInMillis() - 1 * 24 * 60 * 60 * 1000)).greater(); */ q.descend("mLastFetchedDate").orderDescending(); return new Persistent.InitializingObjectSet<Identity>(this, q); } /** * Returns all own identities that are in the database * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all identities present in the database. */ public ObjectSet<OwnIdentity> getAllOwnIdentities() { final Query q = mDB.query(); q.constrain(OwnIdentity.class); return new Persistent.InitializingObjectSet<OwnIdentity>(this, q); } /** * DO NOT USE THIS FUNCTION FOR DELETING OWN IDENTITIES UPON USER REQUEST! * IN FACT BE VERY CAREFUL WHEN USING IT FOR ANYTHING FOR THE FOLLOWING REASONS: * - This function deletes ALL given and received trust values of the given identity. This modifies the trust list of the trusters against their will. * - Especially it might be an information leak if the trust values of other OwnIdentities are deleted! * - If WOT one day is designed to be used by many different users at once, the deletion of other OwnIdentity's trust values would even be corruption. * * The intended purpose of this function is: * - To specify which objects have to be dealt with when messing with storage of an identity. * - To be able to do database object leakage tests: Many classes have a deleteWithoutCommit function and there are valid usecases for them. * However, the implementations of those functions might cause leaks by forgetting to delete certain object members. * If you call this function for ALL identities in a database, EVERYTHING should be deleted and the database SHOULD be empty. * You then can check whether the database actually IS empty to test for leakage. * * You have to lock the WebOfTrust, the IntroductionPuzzleStore and the IdentityFetcher before calling this function. */ private void deleteWithoutCommit(Identity identity) { // We want to use beginTrustListImport, finishTrustListImport / abortTrustListImport. // If the caller already handles that for us though, we should not call those function again. // So we check whether the caller already started an import. boolean trustListImportWasInProgress = mTrustListImportInProgress; try { if(!trustListImportWasInProgress) beginTrustListImport(); if(logDEBUG) Logger.debug(this, "Deleting identity " + identity + " ..."); if(logDEBUG) Logger.debug(this, "Deleting received scores..."); for(Score score : getScores(identity)) score.deleteWithoutCommit(); if(identity instanceof OwnIdentity) { if(logDEBUG) Logger.debug(this, "Deleting given scores..."); for(Score score : getGivenScores((OwnIdentity)identity)) score.deleteWithoutCommit(); } if(logDEBUG) Logger.debug(this, "Deleting received trusts..."); for(Trust trust : getReceivedTrusts(identity)) trust.deleteWithoutCommit(); if(logDEBUG) Logger.debug(this, "Deleting given trusts..."); for(Trust givenTrust : getGivenTrusts(identity)) { givenTrust.deleteWithoutCommit(); // We call computeAllScores anyway so we do not use removeTrustWithoutCommit() } mFullScoreComputationNeeded = true; // finishTrustListImport will call computeAllScoresWithoutCommit for us. if(logDEBUG) Logger.debug(this, "Deleting associated introduction puzzles ..."); mPuzzleStore.onIdentityDeletion(identity); if(logDEBUG) Logger.debug(this, "Storing an abort-fetch-command..."); if(mFetcher != null) { // Can be null if we use this function in upgradeDB() mFetcher.storeAbortFetchCommandWithoutCommit(identity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. } if(logDEBUG) Logger.debug(this, "Deleting the identity..."); identity.deleteWithoutCommit(); if(!trustListImportWasInProgress) finishTrustListImport(); } catch(RuntimeException e) { if(!trustListImportWasInProgress) abortTrustListImport(e); Persistent.checkedRollbackAndThrow(mDB, this, e); } } /** * Gets the score of this identity in a trust tree. * Each {@link OwnIdentity} has its own trust tree. * * @param truster The owner of the trust tree * @return The {@link Score} of this Identity in the required trust tree * @throws NotInTrustTreeException if this identity is not in the required trust tree */ public synchronized Score getScore(final OwnIdentity truster, final Identity trustee) throws NotInTrustTreeException { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mID").constrain(new ScoreID(truster, trustee).toString()); final ObjectSet<Score> result = new Persistent.InitializingObjectSet<Score>(this, query); switch(result.size()) { case 1: final Score score = result.next(); assert(score.getTruster() == truster); assert(score.getTrustee() == trustee); return score; case 0: throw new NotInTrustTreeException(truster, trustee); default: throw new DuplicateScoreException(truster, trustee, result.size()); } } /** * Gets a list of all this Identity's Scores. * You have to synchronize on this WoT around the call to this function and the processing of the returned list! * * @return An {@link ObjectSet} containing all {@link Score} this Identity has. */ public ObjectSet<Score> getScores(final Identity identity) { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mTrustee").constrain(identity).identity(); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Get a list of all scores which the passed own identity has assigned to other identities. * * You have to synchronize on this WoT around the call to this function and the processing of the returned list! * @return An {@link ObjectSet} containing all {@link Score} this Identity has given. */ public ObjectSet<Score> getGivenScores(final OwnIdentity truster) { final Query query = mDB.query(); query.constrain(Score.class); query.descend("mTruster").constrain(truster).identity(); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Gets the best score this Identity has in existing trust trees. * * @return the best score this Identity has * @throws NotInTrustTreeException If the identity has no score in any trusttree. */ public synchronized int getBestScore(final Identity identity) throws NotInTrustTreeException { int bestScore = Integer.MIN_VALUE; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) throw new NotInTrustTreeException(identity); // TODO: Cache the best score of an identity as a member variable. for(final Score score : scores) bestScore = Math.max(score.getScore(), bestScore); return bestScore; } /** * Gets the best capacity this identity has in any trust tree. * @throws NotInTrustTreeException If the identity is not in any trust tree. Can be interpreted as capacity 0. */ public int getBestCapacity(final Identity identity) throws NotInTrustTreeException { int bestCapacity = 0; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) throw new NotInTrustTreeException(identity); // TODO: Cache the best score of an identity as a member variable. for(final Score score : scores) bestCapacity = Math.max(score.getCapacity(), bestCapacity); return bestCapacity; } /** * Get all scores in the database. * You have to synchronize on this WoT when calling the function and processing the returned list! */ public ObjectSet<Score> getAllScores() { final Query query = mDB.query(); query.constrain(Score.class); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Checks whether the given identity should be downloaded. * @return Returns true if the identity has any capacity > 0, any score >= 0 or if it is an own identity. */ public boolean shouldFetchIdentity(final Identity identity) { if(identity instanceof OwnIdentity) return true; int bestScore = Integer.MIN_VALUE; int bestCapacity = 0; final ObjectSet<Score> scores = getScores(identity); if(scores.size() == 0) return false; // TODO: Cache the best score of an identity as a member variable. for(Score score : scores) { bestCapacity = Math.max(score.getCapacity(), bestCapacity); bestScore = Math.max(score.getScore(), bestScore); if(bestCapacity > 0 || bestScore >= 0) return true; } return false; } /** * Gets non-own Identities matching a specified score criteria. * TODO: Rename to getNonOwnIdentitiesByScore. Or even better: Make it return own identities as well, this will speed up the database query and clients might be ok with it. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param truster The owner of the trust tree, null if you want the trusted identities of all owners. * @param select Score criteria, can be > zero, zero or negative. Greater than zero returns all identities with score >= 0, zero with score equal to 0 * and negative with score < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a trust value of 0. * @return an {@link ObjectSet} containing Scores of the identities that match the criteria */ public ObjectSet<Score> getIdentitiesByScore(final OwnIdentity truster, final int select) { final Query query = mDB.query(); query.constrain(Score.class); if(truster != null) query.descend("mTruster").constrain(truster).identity(); query.descend("mTrustee").constrain(OwnIdentity.class).not(); /* We include 0 in the list of identities with positive score because solving captchas gives no points to score */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Score>(this, query); } /** * Gets {@link Trust} from a specified truster to a specified trustee. * * @param truster The identity that gives trust to this Identity * @param trustee The identity which receives the trust * @return The trust given to the trustee by the specified truster * @throws NotTrustedException if the truster doesn't trust the trustee */ public synchronized Trust getTrust(final Identity truster, final Identity trustee) throws NotTrustedException, DuplicateTrustException { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mID").constrain(new TrustID(truster, trustee).toString()); final ObjectSet<Trust> result = new Persistent.InitializingObjectSet<Trust>(this, query); switch(result.size()) { case 1: final Trust trust = result.next(); assert(trust.getTruster() == truster); assert(trust.getTrustee() == trustee); return trust; case 0: throw new NotTrustedException(truster, trustee); default: throw new DuplicateTrustException(truster, trustee, result.size()); } } /** * Gets all trusts given by the given truster. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has given. */ public ObjectSet<Trust> getGivenTrusts(final Identity truster) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts given by the given truster. * The result is sorted descending by the time we last fetched the trusted identity. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has given. */ public ObjectSet<Trust> getGivenTrustsSortedDescendingByLastSeen(final Identity truster) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); query.descend("mTrustee").descend("mLastFetchedDate").orderDescending(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets given trust values of an identity matching a specified trust value criteria. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param truster The identity which given the trust values. * @param select Trust value criteria, can be > zero, zero or negative. Greater than zero returns all trust values >= 0, zero returns trust values equal to 0. * Negative returns trust values < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a value of 0. * @return an {@link ObjectSet} containing received trust values that match the criteria. */ public ObjectSet<Trust> getGivenTrusts(final Identity truster, final int select) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTruster").constrain(truster).identity(); /* We include 0 in the list of identities with positive trust because solving captchas gives 0 trust */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0 ) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts given by the given truster in a trust list with a different edition than the passed in one. * You have to synchronize on this WoT when calling the function and processing the returned list! */ protected ObjectSet<Trust> getGivenTrustsOfDifferentEdition(final Identity truster, final long edition) { final Query q = mDB.query(); q.constrain(Trust.class); q.descend("mTruster").constrain(truster).identity(); q.descend("mTrusterTrustListEdition").constrain(edition).not(); return new Persistent.InitializingObjectSet<Trust>(this, q); } /** * Gets all trusts received by the given trustee. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has received. */ public ObjectSet<Trust> getReceivedTrusts(final Identity trustee) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTrustee").constrain(trustee).identity(); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets received trust values of an identity matching a specified trust value criteria. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @param trustee The identity which has received the trust values. * @param select Trust value criteria, can be > zero, zero or negative. Greater than zero returns all trust values >= 0, zero returns trust values equal to 0. * Negative returns trust values < 0. Zero is included in the positive range by convention because solving an introduction puzzle gives you a value of 0. * @return an {@link ObjectSet} containing received trust values that match the criteria. */ public ObjectSet<Trust> getReceivedTrusts(final Identity trustee, final int select) { final Query query = mDB.query(); query.constrain(Trust.class); query.descend("mTrustee").constrain(trustee).identity(); /* We include 0 in the list of identities with positive trust because solving captchas gives 0 trust */ if(select > 0) query.descend("mValue").constrain(0).smaller().not(); else if(select < 0 ) query.descend("mValue").constrain(0).smaller(); else query.descend("mValue").constrain(0); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gets all trusts. * You have to synchronize on this WoT when calling the function and processing the returned list! * * @return An {@link ObjectSet} containing all {@link Trust} the passed Identity has received. */ public ObjectSet<Trust> getAllTrusts() { final Query query = mDB.query(); query.constrain(Trust.class); return new Persistent.InitializingObjectSet<Trust>(this, query); } /** * Gives some {@link Trust} to another Identity. * It creates or updates an existing Trust object and make the trustee compute its {@link Score}. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(WebOfTrust.this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... setTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}} * * @param truster The Identity that gives the trust * @param trustee The Identity that receives the trust * @param newValue Numeric value of the trust * @param newComment A comment to explain the given value * @throws InvalidParameterException if a given parameter isn't valid, see {@link Trust} for details on accepted values. */ protected void setTrustWithoutCommit(Identity truster, Identity trustee, byte newValue, String newComment) throws InvalidParameterException { try { // Check if we are updating an existing trust value final Trust trust = getTrust(truster, trustee); final Trust oldTrust = trust.clone(); trust.trusterEditionUpdated(); trust.setComment(newComment); trust.storeWithoutCommit(); if(trust.getValue() != newValue) { trust.setValue(newValue); trust.storeWithoutCommit(); if(logDEBUG) Logger.debug(this, "Updated trust value ("+ trust +"), now updating Score."); updateScoresWithoutCommit(oldTrust, trust); } } catch (NotTrustedException e) { final Trust trust = new Trust(this, truster, trustee, newValue, newComment); trust.storeWithoutCommit(); if(logDEBUG) Logger.debug(this, "New trust value ("+ trust +"), now updating Score."); updateScoresWithoutCommit(null, trust); } truster.updated(); truster.storeWithoutCommit(); } /** * Only for being used by WoT internally and by unit tests! */ synchronized void setTrust(OwnIdentity truster, Identity trustee, byte newValue, String newComment) throws InvalidParameterException { synchronized(Persistent.transactionLock(mDB)) { try { setTrustWithoutCommit(truster, trustee, newValue, newComment); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } /** * Deletes a trust object. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... removeTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}} * * @param truster * @param trustee */ protected void removeTrustWithoutCommit(OwnIdentity truster, Identity trustee) { try { try { removeTrustWithoutCommit(getTrust(truster, trustee)); } catch (NotTrustedException e) { Logger.error(this, "Cannot remove trust - there is none - from " + truster.getNickname() + " to " + trustee.getNickname()); } } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } /** * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... setTrustWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * }}} * */ protected void removeTrustWithoutCommit(Trust trust) { trust.deleteWithoutCommit(); updateScoresWithoutCommit(trust, null); } /** * Initializes this OwnIdentity's trust tree without commiting the transaction. * Meaning : It creates a Score object for this OwnIdentity in its own trust so it can give trust to other Identities. * * The score will have a rank of 0, a capacity of 100 (= 100 percent) and a score value of Integer.MAX_VALUE. * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(Persistent.transactionLock(mDB)) { * try { ... initTrustTreeWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } * } * * @throws DuplicateScoreException if there already is more than one Score for this identity (should never happen) */ private synchronized void initTrustTreeWithoutCommit(OwnIdentity identity) throws DuplicateScoreException { try { getScore(identity, identity); Logger.error(this, "initTrustTreeWithoutCommit called even though there is already one for " + identity); return; } catch (NotInTrustTreeException e) { final Score score = new Score(this, identity, identity, Integer.MAX_VALUE, 0, 100); score.storeWithoutCommit(); } } /** * Computes the trustee's Score value according to the trusts it has received and the capacity of its trusters in the specified * trust tree. * * @param truster The OwnIdentity that owns the trust tree * @param trustee The identity for which the score shall be computed. * @return The new Score of the identity. Integer.MAX_VALUE if the trustee is equal to the truster. * @throws DuplicateScoreException if there already exist more than one {@link Score} objects for the trustee (should never happen) */ private synchronized int computeScoreValue(OwnIdentity truster, Identity trustee) throws DuplicateScoreException { if(trustee == truster) return Integer.MAX_VALUE; int value = 0; try { return getTrust(truster, trustee).getValue(); } catch(NotTrustedException e) { } for(Trust trust : getReceivedTrusts(trustee)) { try { final Score trusterScore = getScore(truster, trust.getTruster()); value += ( trust.getValue() * trusterScore.getCapacity() ) / 100; } catch (NotInTrustTreeException e) {} } return value; } /** * Computes the trustees's rank in the trust tree of the truster. * It gets its best ranked non-zero-capacity truster's rank, plus one. * If it has only received negative trust values from identities which have a non-zero-capacity it gets a rank of Integer.MAX_VALUE (infinite). * If it has only received trust values from identities with rank of Integer.MAX_VALUE it gets a rank of -1. * * If the tree owner has assigned a trust value to the identity, the rank computation is only done from that value because the score decisions of the * tree owner are always absolute (if you distrust someone, the remote identities should not be allowed to overpower your decision). * * The purpose of differentiation between Integer.MAX_VALUE and -1 is: * Score objects of identities with rank Integer.MAX_VALUE are kept in the database because WoT will usually "hear" about those identities by seeing them * in the trust lists of trusted identities (with negative trust values). So it must store the trust values to those identities and have a way of telling the * user "this identity is not trusted" by keeping a score object of them. * Score objects of identities with rank -1 are deleted because they are the trustees of distrusted identities and we will not get to the point where we * hear about those identities because the only way of hearing about them is downloading a trust list of a identity with Integer.MAX_VALUE rank - and * we never download their trust lists. * * Notice that 0 is included in infinite rank to prevent identities which have only solved introduction puzzles from having a capacity. * * @param truster The OwnIdentity that owns the trust tree * @return The new Rank if this Identity * @throws DuplicateScoreException if there already exist more than one {@link Score} objects for the trustee (should never happen) */ private synchronized int computeRank(OwnIdentity truster, Identity trustee) throws DuplicateScoreException { if(trustee == truster) return 0; int rank = -1; try { Trust treeOwnerTrust = getTrust(truster, trustee); if(treeOwnerTrust.getValue() > 0) return 1; else return Integer.MAX_VALUE; } catch(NotTrustedException e) { } for(Trust trust : getReceivedTrusts(trustee)) { try { Score score = getScore(truster, trust.getTruster()); if(score.getCapacity() != 0) { // If the truster has no capacity, he can't give his rank // A truster only gives his rank to a trustee if he has assigned a strictly positive trust value if(trust.getValue() > 0 ) { // We give the rank to the trustee if it is better than its current rank or he has no rank yet. if(rank == -1 || score.getRank() < rank) rank = score.getRank(); } else { // If the trustee has no rank yet we give him an infinite rank. because he is distrusted by the truster. if(rank == -1) rank = Integer.MAX_VALUE; } } } catch (NotInTrustTreeException e) {} } if(rank == -1) return -1; else if(rank == Integer.MAX_VALUE) return Integer.MAX_VALUE; else return rank+1; } /** * Begins the import of a trust list. This sets a flag on this WoT which signals that the import of a trust list is in progress. * This speeds up setTrust/removeTrust as the score calculation is only performed when endTrustListImport is called. * * You MUST synchronize on this WoT around beginTrustListImport, abortTrustListImport and finishTrustListImport! * You MUST create a database transaction by synchronizing on Persistent.transactionLock(db). */ protected void beginTrustListImport() { if(logMINOR) Logger.minor(this, "beginTrustListImport()"); if(mTrustListImportInProgress) { abortTrustListImport(new RuntimeException("There was already a trust list import in progress!")); mFullScoreComputationNeeded = true; computeAllScoresWithoutCommit(); assert(mFullScoreComputationNeeded == false); } mTrustListImportInProgress = true; assert(!mFullScoreComputationNeeded); assert(computeAllScoresWithoutCommit()); // The database is intact before the import } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * * Aborts the import of a trust list and rolls back the current transaction. * * @param e The exception which triggered the abort. Will be logged to the Freenet log file. * @param logLevel The {@link LogLevel} to use when logging the abort to the Freenet log file. */ protected void abortTrustListImport(Exception e, LogLevel logLevel) { if(logMINOR) Logger.minor(this, "abortTrustListImport()"); assert(mTrustListImportInProgress); mTrustListImportInProgress = false; mFullScoreComputationNeeded = false; Persistent.checkedRollback(mDB, this, e, logLevel); assert(computeAllScoresWithoutCommit()); // Test rollback. } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * * Aborts the import of a trust list and rolls back the current transaction. * * @param e The exception which triggered the abort. Will be logged to the Freenet log file with log level {@link LogLevel.ERROR} */ protected void abortTrustListImport(Exception e) { abortTrustListImport(e, Logger.LogLevel.ERROR); } /** * See {@link beginTrustListImport} for an explanation of the purpose of this function. * * Finishes the import of the current trust list and clears the "trust list * * Does NOT commit the transaction, you must do this. */ protected void finishTrustListImport() { if(logMINOR) Logger.minor(this, "finishTrustListImport()"); if(!mTrustListImportInProgress) { Logger.error(this, "There was no trust list import in progress!"); return; } if(mFullScoreComputationNeeded) { computeAllScoresWithoutCommit(); assert(!mFullScoreComputationNeeded); // It properly clears the flag assert(computeAllScoresWithoutCommit()); // computeAllScoresWithoutCommit() is stable } else assert(computeAllScoresWithoutCommit()); // Verify whether updateScoresWithoutCommit worked. mTrustListImportInProgress = false; } /** * Updates all trust trees which are affected by the given modified score. * For understanding how score calculation works you should first read {@link computeAllScores * * This function does neither lock the database nor commit the transaction. You have to surround it with * synchronized(this) { * synchronized(mFetcher) { * synchronized(Persistent.transactionLock(mDB)) { * try { ... updateScoreWithoutCommit(...); Persistent.checkedCommit(mDB, this); } * catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e);; } * }}} */ private void updateScoresWithoutCommit(final Trust oldTrust, final Trust newTrust) { if(logMINOR) Logger.minor(this, "Doing an incremental computation of all Scores..."); final long beginTime = CurrentTimeUTC.getInMillis(); // We only include the time measurement if we actually do something. // If we figure out that a full score recomputation is needed just by looking at the initial parameters, the measurement won't be included. boolean includeMeasurement = false; final boolean trustWasCreated = (oldTrust == null); final boolean trustWasDeleted = (newTrust == null); final boolean trustWasModified = !trustWasCreated && !trustWasDeleted; if(trustWasCreated && trustWasDeleted) throw new NullPointerException("No old/new trust specified."); if(trustWasModified && oldTrust.getTruster() != newTrust.getTruster()) throw new IllegalArgumentException("oldTrust has different truster, oldTrust:" + oldTrust + "; newTrust: " + newTrust); if(trustWasModified && oldTrust.getTrustee() != newTrust.getTrustee()) throw new IllegalArgumentException("oldTrust has different trustee, oldTrust:" + oldTrust + "; newTrust: " + newTrust); // We cannot iteratively REMOVE an inherited rank from the trustees because we don't know whether there is a circle in the trust values // which would make the current identity get its old rank back via the circle: computeRank searches the trusters of an identity for the best // rank, if we remove the rank from an identity, all its trustees will have a better rank and if one of them trusts the original identity // then this function would run into an infinite loop. Decreasing or incrementing an existing rank is possible with this function because // the rank received from the trustees will always be higher (that is exactly 1 more) than this identities rank. if(trustWasDeleted) { mFullScoreComputationNeeded = true; } if(!mFullScoreComputationNeeded && (trustWasCreated || trustWasModified)) { includeMeasurement = true; for(OwnIdentity treeOwner : getAllOwnIdentities()) { try { // Throws to abort the update of the trustee's score: If the truster has no rank or capacity in the tree owner's view then we don't need to update the trustee's score. if(getScore(treeOwner, newTrust.getTruster()).getCapacity() == 0) continue; } catch(NotInTrustTreeException e) { continue; } // See explanation above "We cannot iteratively REMOVE an inherited rank..." if(trustWasModified && oldTrust.getValue() > 0 && newTrust.getValue() <= 0) { mFullScoreComputationNeeded = true; break; } final LinkedList<Trust> unprocessedEdges = new LinkedList<Trust>(); unprocessedEdges.add(newTrust); while(!unprocessedEdges.isEmpty()) { final Trust trust = unprocessedEdges.removeFirst(); final Identity trustee = trust.getTrustee(); if(trustee == treeOwner) continue; Score currentStoredTrusteeScore; try { currentStoredTrusteeScore = getScore(treeOwner, trustee); } catch(NotInTrustTreeException e) { currentStoredTrusteeScore = new Score(this, treeOwner, trustee, 0, -1, 0); } final Score oldScore = currentStoredTrusteeScore.clone(); boolean oldShouldFetch = shouldFetchIdentity(trustee); final int newScoreValue = computeScoreValue(treeOwner, trustee); final int newRank = computeRank(treeOwner, trustee); final int newCapacity = computeCapacity(treeOwner, trustee, newRank); final Score newScore = new Score(this, treeOwner, trustee, newScoreValue, newRank, newCapacity); // Normally we couldn't detect the following two cases due to circular trust values. However, if an own identity assigns a trust value, // the rank and capacity are always computed based on the trust value of the own identity so we must also check this here: if((oldScore.getRank() >= 0 && oldScore.getRank() < Integer.MAX_VALUE) // It had an inheritable rank && (newScore.getRank() == -1 || newScore.getRank() == Integer.MAX_VALUE)) { // It has no inheritable rank anymore mFullScoreComputationNeeded = true; break; } if(oldScore.getCapacity() > 0 && newScore.getCapacity() == 0) { mFullScoreComputationNeeded = true; break; } // We are OK to update it now. We must not update the values of the stored score object before determining whether we need // a full score computation - the full computation needs the old values of the object. currentStoredTrusteeScore.setValue(newScore.getScore()); currentStoredTrusteeScore.setRank(newScore.getRank()); currentStoredTrusteeScore.setCapacity(newScore.getCapacity()); // Identities should not get into the queue if they have no rank, see the large if() about 20 lines below assert(currentStoredTrusteeScore.getRank() >= 0); if(currentStoredTrusteeScore.getRank() >= 0) currentStoredTrusteeScore.storeWithoutCommit(); // If fetch status changed from false to true, we need to start fetching it // If the capacity changed from 0 to positive, we need to refetch the current edition: Identities with capacity 0 cannot // cause new identities to be imported from their trust list, capacity > 0 allows this. // If the fetch status changed from true to false, we need to stop fetching it if((!oldShouldFetch || (oldScore.getCapacity()== 0 && newScore.getCapacity() > 0)) && shouldFetchIdentity(trustee)) { if(!oldShouldFetch) if(logDEBUG) Logger.debug(this, "Fetch status changed from false to true, refetching " + trustee); else if(logDEBUG) Logger.debug(this, "Capacity changed from 0 to " + newScore.getCapacity() + ", refetching" + trustee); trustee.markForRefetch(); trustee.storeWithoutCommit(); mFetcher.storeStartFetchCommandWithoutCommit(trustee); } else if(oldShouldFetch && !shouldFetchIdentity(trustee)) { if(logDEBUG) Logger.debug(this, "Fetch status changed from true to false, aborting fetch of " + trustee); mFetcher.storeAbortFetchCommandWithoutCommit(trustee); } // If the rank or capacity changed then the trustees might be affected because the could have inherited theirs if(oldScore.getRank() != newScore.getRank() || oldScore.getCapacity() != newScore.getCapacity()) { // If this identity has no capacity or no rank then it cannot affect its trustees: // (- If it had none and it has none now then there is none which can be inherited, this is obvious) // - If it had one before and it was removed, this algorithm will have aborted already because a full computation is needed if(newScore.getCapacity() > 0 || (newScore.getRank() >= 0 && newScore.getRank() < Integer.MAX_VALUE)) { // We need to update the trustees of trustee for(Trust givenTrust : getGivenTrusts(trustee)) { unprocessedEdges.add(givenTrust); } } } } if(mFullScoreComputationNeeded) break; } } if(includeMeasurement) { ++mIncrementalScoreRecomputationCount; mIncrementalScoreRecomputationMilliseconds += CurrentTimeUTC.getInMillis() - beginTime; } if(logMINOR) { final String time = includeMeasurement ? ("Stats: Amount: " + mIncrementalScoreRecomputationCount + "; Avg Time:" + getAverageIncrementalScoreRecomputationTime() + "s") : ("Time not measured: Computation was aborted before doing anything."); if(!mFullScoreComputationNeeded) Logger.minor(this, "Incremental computation of all Scores finished. " + time); else Logger.minor(this, "Incremental computation of all Scores not possible, full computation is needed. " + time); } if(!mTrustListImportInProgress) { if(mFullScoreComputationNeeded) { // TODO: Optimization: This uses very much CPU and memory. Write a partial computation function... // TODO: Optimization: While we do not have a partial computation function, we could at least optimize computeAllScores to NOT // keep all objects in memory etc. computeAllScoresWithoutCommit(); assert(computeAllScoresWithoutCommit()); // computeAllScoresWithoutCommit is stable } else { assert(computeAllScoresWithoutCommit()); // This function worked correctly. } } else { // a trust list import is in progress // We not do the following here because it would cause too much CPU usage during debugging: Trust lists are large and therefore // updateScoresWithoutCommit is called often during import of a single trust list // assert(computeAllScoresWithoutCommit()); } } /* Client interface functions */ public synchronized Identity addIdentity(String requestURI) throws MalformedURLException, InvalidParameterException { try { getIdentityByURI(requestURI); throw new InvalidParameterException("We already have this identity"); } catch(UnknownIdentityException e) { final Identity identity = new Identity(this, requestURI, null, false); identity.storeAndCommit(); if(logDEBUG) Logger.debug(this, "Created identity " + identity); // The identity hasn't received a trust value. Therefore, there is no reason to fetch it and we don't notify the IdentityFetcher. // TODO: Document this function and the UI which uses is to warn the user that the identity won't be fetched without trust. return identity; } } public OwnIdentity createOwnIdentity(String nickName, boolean publishTrustList, String context) throws MalformedURLException, InvalidParameterException { FreenetURI[] keypair = getPluginRespirator().getHLSimpleClient().generateKeyPair(WOT_NAME); return createOwnIdentity(keypair[0], nickName, publishTrustList, context); } /** * @param context A context with which you want to use the identity. Null if you want to add it later. */ public synchronized OwnIdentity createOwnIdentity(FreenetURI insertURI, String nickName, boolean publishTrustList, String context) throws MalformedURLException, InvalidParameterException { synchronized(Persistent.transactionLock(mDB)) { OwnIdentity identity; try { identity = getOwnIdentityByURI(insertURI); throw new InvalidParameterException("The URI you specified is already used by the own identity " + identity.getNickname() + "."); } catch(UnknownIdentityException uie) { identity = new OwnIdentity(this, insertURI, nickName, publishTrustList); if(context != null) identity.addContext(context); if(publishTrustList) { identity.addContext(IntroductionPuzzle.INTRODUCTION_CONTEXT); /* TODO: make configureable */ identity.setProperty(IntroductionServer.PUZZLE_COUNT_PROPERTY, Integer.toString(IntroductionServer.DEFAULT_PUZZLE_COUNT)); } try { identity.storeWithoutCommit(); initTrustTreeWithoutCommit(identity); beginTrustListImport(); // Incremental score computation has proven to be very very slow when creating identities so we just schedule a full computation. mFullScoreComputationNeeded = true; for(String seedURI : SEED_IDENTITIES) { try { setTrustWithoutCommit(identity, getIdentityByURI(seedURI), (byte)100, "Automatically assigned trust to a seed identity."); } catch(UnknownIdentityException e) { Logger.error(this, "SHOULD NOT HAPPEN: Seed identity not known: " + e); } } finishTrustListImport(); Persistent.checkedCommit(mDB, this); if(mIntroductionClient != null) mIntroductionClient.nextIteration(); // This will make it fetch more introduction puzzles. if(logDEBUG) Logger.debug(this, "Successfully created a new OwnIdentity (" + identity.getNickname() + ")"); return identity; } catch(RuntimeException e) { abortTrustListImport(e); // Rolls back for us throw e; // Satisfy the compiler } } } } /** * This "deletes" an {@link OwnIdentity} by replacing it with an {@link Identity}. * * The {@link OwnIdentity} is not deleted because this would be a security issue: * If other {@link OwnIdentity}s have assigned a trust value to it, the trust value would be gone if there is no {@link Identity} object to be the target * * @param id The {@link Identity.IdentityID} of the identity. * @throws UnknownIdentityException If there is no {@link OwnIdentity} with the given ID. Also thrown if a non-own identity exists with the given ID. */ public synchronized void deleteOwnIdentity(String id) throws UnknownIdentityException { Logger.normal(this, "deleteOwnIdentity(): Starting... "); synchronized(mPuzzleStore) { synchronized(mFetcher) { synchronized(Persistent.transactionLock(mDB)) { final OwnIdentity oldIdentity = getOwnIdentityByID(id); try { Logger.normal(this, "Deleting an OwnIdentity by converting it to a non-own Identity: " + oldIdentity); // We don't need any score computations to happen (explanation will follow below) so we don't need the following: /* beginTrustListImport(); */ // This function messes with the score graph manually so it is a good idea to check whether it is intact before and afterwards. assert(computeAllScoresWithoutCommit()); final Identity newIdentity; try { newIdentity = new Identity(this, oldIdentity.getRequestURI(), oldIdentity.getNickname(), oldIdentity.doesPublishTrustList()); } catch(MalformedURLException e) { // The data was taken from the OwnIdentity so this shouldn't happen throw new RuntimeException(e); } catch (InvalidParameterException e) { // The data was taken from the OwnIdentity so this shouldn't happen throw new RuntimeException(e); } newIdentity.setContexts(oldIdentity.getContexts()); newIdentity.setProperties(oldIdentity.getProperties()); try { newIdentity.setEdition(oldIdentity.getEdition()); } catch (InvalidParameterException e) { // The data was taken from old identity so this shouldn't happen throw new RuntimeException(e); } // In theory we do not need to re-fetch the current trust list edition: // The trust list of an own identity is always stored completely in the database, i.e. all trustees exist. // HOWEVER if the user had used the restoreOwnIdentity feature and then used this function, it might be the case that // the current edition of the old OwndIdentity was not fetched yet. // So we set the fetch state to FetchState.Fetched if the oldIdentity's fetch state was like that as well. if(oldIdentity.getCurrentEditionFetchState() == FetchState.Fetched) { newIdentity.onFetched(oldIdentity.getLastFetchedDate()); } // An else to set the fetch state to FetchState.NotFetched is not necessary, newIdentity.setEdition() did that already. newIdentity.storeWithoutCommit(); // Copy all received trusts. // We don't have to modify them because they are user-assigned values and the assignment // of the user does not change just because the type of the identity changes. for(Trust oldReceivedTrust : getReceivedTrusts(oldIdentity)) { Trust newReceivedTrust; try { newReceivedTrust = new Trust(this, oldReceivedTrust.getTruster(), newIdentity, oldReceivedTrust.getValue(), oldReceivedTrust.getComment()); } catch (InvalidParameterException e) { // The data was taken from the old Trust so this shouldn't happen throw new RuntimeException(e); } // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newReceivedTrust.equals(oldReceivedTrust)); */ oldReceivedTrust.deleteWithoutCommit(); newReceivedTrust.storeWithoutCommit(); } assert(getReceivedTrusts(oldIdentity).size() == 0); // Copy all received scores. // We don't have to modify them because the rating of the identity from the perspective of a // different own identity should NOT be dependent upon whether it is an own identity or not. for(Score oldScore : getScores(oldIdentity)) { Score newScore = new Score(this, oldScore.getTruster(), newIdentity, oldScore.getScore(), oldScore.getRank(), oldScore.getCapacity()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newScore.equals(oldScore)); */ oldScore.deleteWithoutCommit(); newScore.storeWithoutCommit(); } assert(getScores(oldIdentity).size() == 0); // Delete all given scores: // Non-own identities do not assign scores to other identities so we can just delete them. for(Score oldScore : getGivenScores(oldIdentity)) { final Identity trustee = oldScore.getTrustee(); final boolean oldShouldFetchTrustee = shouldFetchIdentity(trustee); oldScore.deleteWithoutCommit(); // If the OwnIdentity which we are converting was the only source of trust to the trustee // of this Score value, the should-fetch state of the trustee might change to false. if(oldShouldFetchTrustee && shouldFetchIdentity(trustee) == false) { mFetcher.storeAbortFetchCommandWithoutCommit(trustee); } } assert(getGivenScores(oldIdentity).size() == 0); // Copy all given trusts: // We don't have to use the removeTrust/setTrust functions because the score graph does not need updating: // - To the rating of the converted identity in the score graphs of other own identities it is irrelevant // whether it is an own identity or not. The rating should never depend on whether it is an own identity! // - Non-own identities do not have a score graph. So the score graph of the converted identity is deleted // completely and therefore it does not need to be updated. for(Trust oldGivenTrust : getGivenTrusts(oldIdentity)) { Trust newGivenTrust; try { newGivenTrust = new Trust(this, newIdentity, oldGivenTrust.getTrustee(), oldGivenTrust.getValue(), oldGivenTrust.getComment()); } catch (InvalidParameterException e) { // The data was taken from the old Trust so this shouldn't happen throw new RuntimeException(e); } // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newGivenTrust.equals(oldGivenTrust)); */ oldGivenTrust.deleteWithoutCommit(); newGivenTrust.storeWithoutCommit(); } mPuzzleStore.onIdentityDeletion(oldIdentity); mFetcher.storeAbortFetchCommandWithoutCommit(oldIdentity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. oldIdentity.deleteWithoutCommit(); mFetcher.storeStartFetchCommandWithoutCommit(newIdentity); // This function messes with the score graph manually so it is a good idea to check whether it is intact before and afterwards. assert(computeAllScoresWithoutCommit()); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } Logger.normal(this, "deleteOwnIdentity(): Finished."); } /** * NOTICE: When changing this function, please also take care of {@link OwnIdentity.isRestoreInProgress()} */ public synchronized void restoreOwnIdentity(FreenetURI insertFreenetURI) throws MalformedURLException, InvalidParameterException { Logger.normal(this, "restoreOwnIdentity(): Starting... "); OwnIdentity identity; synchronized(mPuzzleStore) { synchronized(mFetcher) { synchronized(Persistent.transactionLock(mDB)) { try { long edition = 0; try { edition = Math.max(edition, insertFreenetURI.getEdition()); } catch(IllegalStateException e) { // The user supplied URI did not have an edition specified } try { // Try replacing an existing non-own version of the identity with an OwnIdentity Identity oldIdentity = getIdentityByURI(insertFreenetURI); if(oldIdentity instanceof OwnIdentity) throw new InvalidParameterException("There is already an own identity with the given URI pair."); Logger.normal(this, "Restoring an already known identity from Freenet: " + oldIdentity); // Normally, one would expect beginTrustListImport() to happen close to the actual trust list changes later on in this function. // But beginTrustListImport() contains an assert(computeAllScoresWithoutCommit()) and that call to the score computation reference // implementation will fail if two identities with the same ID exist. // This would be the case later on - we cannot delete the non-own version of the OwnIdentity before we modified the trust graph // but we must also store the own version to be able to modify the trust graph. beginTrustListImport(); // We already have fetched this identity as a stranger's one. We need to update the database. identity = new OwnIdentity(this, insertFreenetURI, oldIdentity.getNickname(), oldIdentity.doesPublishTrustList()); /* We re-fetch the most recent edition to make sure all trustees are imported */ edition = Math.max(edition, oldIdentity.getEdition()); identity.restoreEdition(edition, oldIdentity.getLastFetchedDate()); identity.setContexts(oldIdentity.getContexts()); identity.setProperties(oldIdentity.getProperties()); identity.storeWithoutCommit(); initTrustTreeWithoutCommit(identity); // Copy all received trusts. // We don't have to modify them because they are user-assigned values and the assignment // of the user does not change just because the type of the identity changes. for(Trust oldReceivedTrust : getReceivedTrusts(oldIdentity)) { Trust newReceivedTrust = new Trust(this, oldReceivedTrust.getTruster(), identity, oldReceivedTrust.getValue(), oldReceivedTrust.getComment()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newReceivedTrust.equals(oldReceivedTrust)); */ oldReceivedTrust.deleteWithoutCommit(); newReceivedTrust.storeWithoutCommit(); } assert(getReceivedTrusts(oldIdentity).size() == 0); // Copy all received scores. // We don't have to modify them because the rating of the identity from the perspective of a // different own identity should NOT be dependent upon whether it is an own identity or not. for(Score oldScore : getScores(oldIdentity)) { Score newScore = new Score(this, oldScore.getTruster(), identity, oldScore.getScore(), oldScore.getRank(), oldScore.getCapacity()); // The following assert() cannot be added because it would always fail: // It would implicitly trigger oldIdentity.equals(identity) which is not the case: // Certain member values such as the edition might not be equal. /* assert(newScore.equals(oldScore)); */ oldScore.deleteWithoutCommit(); newScore.storeWithoutCommit(); } assert(getScores(oldIdentity).size() == 0); // What we do NOT have to deal with is the given scores of the old identity: // Given scores do NOT exist for non-own identities, so there are no old ones to update. // Of cause there WILL be scores because it is an own identity now. // They will be created automatically when updating the given trusts // - so thats what we will do now. // Update all given trusts for(Trust givenTrust : getGivenTrusts(oldIdentity)) { // TODO: Instead of using the regular removeTrustWithoutCommit on all trust values, we could: // - manually delete the old Trust objects from the database // - manually store the new trust objects // - Realize that only the trust graph of the restored identity needs to be updated and write an optimized version // of setTrustWithoutCommit which deals with that. // But before we do that, we should first do the existing possible optimization of removeTrustWithoutCommit: // To get rid of removeTrustWithoutCommit always triggering a FULL score recomputation and instead make // it only update the parts of the trust graph which are affected. // Maybe the optimized version is fast enough that we don't have to do the optimization which this TODO suggests. removeTrustWithoutCommit(givenTrust); setTrustWithoutCommit(identity, givenTrust.getTrustee(), givenTrust.getValue(), givenTrust.getComment()); } // We do not call finishTrustListImport() now: It might trigger execution of computeAllScoresWithoutCommit // which would re-create scores of the old identity. We later call it AFTER deleting the old identity. /* finishTrustListImport(); */ mPuzzleStore.onIdentityDeletion(oldIdentity); mFetcher.storeAbortFetchCommandWithoutCommit(oldIdentity); // NOTICE: // If the fetcher did store a db4o object reference to the identity, we would have to trigger command processing // now to prevent leakage of the identity object. // But the fetcher does NOT store a db4o object reference to the given identity. It stores its ID as String only. // Therefore, it is OK that the fetcher does not immediately process the commands now. oldIdentity.deleteWithoutCommit(); finishTrustListImport(); } catch (UnknownIdentityException e) { // The identity did NOT exist as non-own identity yet so we can just create an OwnIdentity and store it. identity = new OwnIdentity(this, insertFreenetURI, null, false); Logger.normal(this, "Restoring not-yet-known identity from Freenet: " + identity); identity.restoreEdition(edition, null); // Store the new identity identity.storeWithoutCommit(); initTrustTreeWithoutCommit(identity); } mFetcher.storeStartFetchCommandWithoutCommit(identity); // This function messes with the trust graph manually so it is a good idea to check whether it is intact afterwards. assert(computeAllScoresWithoutCommit()); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { abortTrustListImport(e); Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } Logger.normal(this, "restoreOwnIdentity(): Finished."); } public synchronized void setTrust(String ownTrusterID, String trusteeID, byte value, String comment) throws UnknownIdentityException, NumberFormatException, InvalidParameterException { final OwnIdentity truster = getOwnIdentityByID(ownTrusterID); Identity trustee = getIdentityByID(trusteeID); setTrust(truster, trustee, value, comment); } public synchronized void removeTrust(String ownTrusterID, String trusteeID) throws UnknownIdentityException { final OwnIdentity truster = getOwnIdentityByID(ownTrusterID); final Identity trustee = getIdentityByID(trusteeID); synchronized(mFetcher) { synchronized(Persistent.transactionLock(mDB)) { try { removeTrustWithoutCommit(truster, trustee); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } public synchronized void addContext(String ownIdentityID, String newContext) throws UnknownIdentityException, InvalidParameterException { final Identity identity = getOwnIdentityByID(ownIdentityID); identity.addContext(newContext); identity.storeAndCommit(); if(logDEBUG) Logger.debug(this, "Added context '" + newContext + "' to identity '" + identity.getNickname() + "'"); } public synchronized void removeContext(String ownIdentityID, String context) throws UnknownIdentityException, InvalidParameterException { final Identity identity = getOwnIdentityByID(ownIdentityID); identity.removeContext(context); identity.storeAndCommit(); if(logDEBUG) Logger.debug(this, "Removed context '" + context + "' from identity '" + identity.getNickname() + "'"); } public synchronized String getProperty(String identityID, String property) throws InvalidParameterException, UnknownIdentityException { return getIdentityByID(identityID).getProperty(property); } public synchronized void setProperty(String ownIdentityID, String property, String value) throws UnknownIdentityException, InvalidParameterException { Identity identity = getOwnIdentityByID(ownIdentityID); identity.setProperty(property, value); identity.storeAndCommit(); if(logDEBUG) Logger.debug(this, "Added property '" + property + "=" + value + "' to identity '" + identity.getNickname() + "'"); } public synchronized void removeProperty(String ownIdentityID, String property) throws UnknownIdentityException, InvalidParameterException { final Identity identity = getOwnIdentityByID(ownIdentityID); identity.removeProperty(property); identity.storeAndCommit(); if(logDEBUG) Logger.debug(this, "Removed property '" + property + "' from identity '" + identity.getNickname() + "'"); } public String getVersion() { return Version.getMarketingVersion(); } public long getRealVersion() { return Version.getRealVersion(); } public String getString(String key) { return getBaseL10n().getString(key); } public void setLanguage(LANGUAGE newLanguage) { WebOfTrust.l10n = new PluginL10n(this, newLanguage); if(logDEBUG) Logger.debug(this, "Set LANGUAGE to: " + newLanguage.isoCode); } public PluginRespirator getPluginRespirator() { return mPR; } public ExtObjectContainer getDatabase() { return mDB; } public Configuration getConfig() { return mConfig; } public IdentityFetcher getIdentityFetcher() { return mFetcher; } public XMLTransformer getXMLTransformer() { return mXMLTransformer; } public IntroductionPuzzleStore getIntroductionPuzzleStore() { return mPuzzleStore; } public IntroductionClient getIntroductionClient() { return mIntroductionClient; } public RequestClient getRequestClient() { return mRequestClient; } /** * This is where our L10n files are stored. * @return Path of our L10n files. */ public String getL10nFilesBasePath() { return "plugins/WebOfTrust/l10n/"; } /** * This is the mask of our L10n files : lang_en.l10n, lang_de.10n, ... * @return Mask of the L10n files. */ public String getL10nFilesMask() { return "lang_${lang}.l10n"; } /** * Override L10n files are stored on the disk, their names should be explicit * we put here the plugin name, and the "override" indication. Plugin L10n * override is not implemented in the node yet. * @return Mask of the override L10n files. */ public String getL10nOverrideFilesMask() { return "WebOfTrust_lang_${lang}.override.l10n"; } /** * Get the ClassLoader of this plugin. This is necessary when getting * resources inside the plugin's Jar, for example L10n files. * @return ClassLoader object */ public ClassLoader getPluginClassLoader() { return WebOfTrust.class.getClassLoader(); } /** * Access to the current L10n data. * * @return L10n object. */ public BaseL10n getBaseL10n() { return WebOfTrust.l10n.getBase(); } public int getNumberOfFullScoreRecomputations() { return mFullScoreRecomputationCount; } public synchronized double getAverageFullScoreRecomputationTime() { return (double)mFullScoreRecomputationMilliseconds / ((mFullScoreRecomputationCount!= 0 ? mFullScoreRecomputationCount : 1) * 1000); } public int getNumberOfIncrementalScoreRecomputations() { return mIncrementalScoreRecomputationCount; } public synchronized double getAverageIncrementalScoreRecomputationTime() { return (double)mIncrementalScoreRecomputationMilliseconds / ((mIncrementalScoreRecomputationCount!= 0 ? mIncrementalScoreRecomputationCount : 1) * 1000); } /** * Tests whether two WoT are equal. * This is a complex operation in terms of execution time and memory usage and only intended for being used in unit tests. */ public synchronized boolean equals(Object obj) { if(obj == this) return true; if(!(obj instanceof WebOfTrust)) return false; WebOfTrust other = (WebOfTrust)obj; synchronized(other) { { // Compare own identities final ObjectSet<OwnIdentity> allIdentities = getAllOwnIdentities(); if(allIdentities.size() != other.getAllOwnIdentities().size()) return false; for(OwnIdentity identity : allIdentities) { try { if(!identity.equals(other.getOwnIdentityByID(identity.getID()))) return false; } catch(UnknownIdentityException e) { return false; } } } { // Compare identities final ObjectSet<Identity> allIdentities = getAllIdentities(); if(allIdentities.size() != other.getAllIdentities().size()) return false; for(Identity identity : allIdentities) { try { if(!identity.equals(other.getIdentityByID(identity.getID()))) return false; } catch(UnknownIdentityException e) { return false; } } } { // Compare trusts final ObjectSet<Trust> allTrusts = getAllTrusts(); if(allTrusts.size() != other.getAllTrusts().size()) return false; for(Trust trust : allTrusts) { try { Identity otherTruster = other.getIdentityByID(trust.getTruster().getID()); Identity otherTrustee = other.getIdentityByID(trust.getTrustee().getID()); if(!trust.equals(other.getTrust(otherTruster, otherTrustee))) return false; } catch(UnknownIdentityException e) { return false; } catch(NotTrustedException e) { return false; } } } { // Compare scores final ObjectSet<Score> allScores = getAllScores(); if(allScores.size() != other.getAllScores().size()) return false; for(Score score : allScores) { try { OwnIdentity otherTruster = other.getOwnIdentityByID(score.getTruster().getID()); Identity otherTrustee = other.getIdentityByID(score.getTrustee().getID()); if(!score.equals(other.getScore(otherTruster, otherTrustee))) return false; } catch(UnknownIdentityException e) { return false; } catch(NotInTrustTreeException e) { return false; } } } } return true; } }
diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/sync/compare/SyncInfoCompareInput.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/sync/compare/SyncInfoCompareInput.java index fa5f1d597..6be461569 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/sync/compare/SyncInfoCompareInput.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/sync/compare/SyncInfoCompareInput.java @@ -1,244 +1,244 @@ /******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.team.internal.ui.sync.compare; import java.lang.reflect.InvocationTargetException; import org.eclipse.compare.CompareConfiguration; import org.eclipse.compare.CompareEditorInput; import org.eclipse.compare.IContentChangeListener; import org.eclipse.compare.IContentChangeNotifier; import org.eclipse.compare.ITypedElement; import org.eclipse.compare.structuremergeviewer.DiffNode; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.swt.graphics.Image; import org.eclipse.team.core.TeamException; import org.eclipse.team.core.subscribers.SyncInfo; import org.eclipse.team.core.sync.IRemoteResource; import org.eclipse.team.internal.ui.Policy; import org.eclipse.team.internal.ui.TeamUIPlugin; import org.eclipse.team.ui.ISharedImages; public class SyncInfoCompareInput extends CompareEditorInput { private SyncInfo sync; private SyncInfoDiffNode node; private static Image titleImage; /* protected */ SyncInfoCompareInput() { super(new CompareConfiguration()); } public SyncInfoCompareInput(SyncInfo sync) { super(new CompareConfiguration()); this.sync = sync; ITypedElement elements[] = SyncInfoDiffNode.getTypedElements(sync); this.node = new SyncInfoDiffNode(elements[0] /* base */, elements[1] /* local */, elements[2] /* remote */, sync.getKind()); initializeContentChangeListeners(); } private void initializeContentChangeListeners() { ITypedElement te = node.getLeft(); if(te instanceof IContentChangeNotifier) { ((IContentChangeNotifier)te).addContentChangeListener(new IContentChangeListener() { public void contentChanged(IContentChangeNotifier source) { try { saveChanges(new NullProgressMonitor()); } catch (CoreException e) { } } }); } } /* (non-Javadoc) * @see org.eclipse.compare.CompareEditorInput#getTitleImage() */ public Image getTitleImage() { if(titleImage == null) { titleImage = TeamUIPlugin.getImageDescriptor(ISharedImages.IMG_SYNC_VIEW).createImage(); TeamUIPlugin.disposeOnShutdown(titleImage); } return titleImage; } /* (non-Javadoc) * @see org.eclipse.compare.CompareEditorInput#prepareInput(org.eclipse.core.runtime.IProgressMonitor) */ protected Object prepareInput(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { // update the title now that the remote revision number as been fetched from the server setTitle(getTitle()); updateLabels(); return node; } /* (non-Javadoc) * @see org.eclipse.compare.CompareEditorInput#getTitle() */ public String getTitle() { return Policy.bind("SyncInfoCompareInput.title", sync.getSubscriber().getName(), node.getName()); //$NON-NLS-1$ } protected void updateLabels() { CompareConfiguration config = getCompareConfiguration(); IRemoteResource remote = sync.getRemote(); IRemoteResource base = sync.getRemote(); config.setLeftLabel(Policy.bind("SyncInfoCompareInput.localLabel")); //$NON-NLS-1$ if(remote != null) { try { config.setRightLabel(Policy.bind("SyncInfoCompareInput.remoteLabelExists", remote.getContentIdentifier(), remote.getCreatorDisplayName(), flattenText(remote.getComment()))); //$NON-NLS-1$ } catch (TeamException e) { config.setRightLabel(Policy.bind("SyncInfoCompareInput.remoteLabel")); //$NON-NLS-1$ } } else { config.setRightLabel(Policy.bind("SyncInfoCompareInput.remoteLabel")); //$NON-NLS-1$ } if(base != null) { try { config.setAncestorLabel(Policy.bind("SyncInfoCompareInput.baseLabelExists", base.getContentIdentifier(), base.getCreatorDisplayName(), flattenText(base.getComment()))); //$NON-NLS-1$ } catch (TeamException e) { config.setAncestorLabel(Policy.bind("SyncInfoCompareInput.baseLabel")); //$NON-NLS-1$ } } else { config.setAncestorLabel(Policy.bind("SyncInfoCompareInput.baseLabel")); //$NON-NLS-1$ } } /* * Flatten the text in the multiline comment * @param string * @return String */ private String flattenText(String string) { StringBuffer buffer = new StringBuffer(string.length() + 20); boolean skipAdjacentLineSeparator = true; for (int i = 0; i < string.length(); i++) { char c = string.charAt(i); if (c == '\r' || c == '\n') { if (!skipAdjacentLineSeparator) buffer.append("/"); //$NON-NLS-1$ skipAdjacentLineSeparator = true; } else { buffer.append(c); skipAdjacentLineSeparator = false; } } return buffer.toString(); } /* (non-Javadoc) * @see org.eclipse.ui.IEditorInput#getImageDescriptor() */ public ImageDescriptor getImageDescriptor() { return TeamUIPlugin.getImageDescriptor(ISharedImages.IMG_SYNC_MODE_FREE); } /* (non-Javadoc) * @see org.eclipse.ui.IEditorInput#getToolTipText() */ public String getToolTipText() { return Policy.bind("SyncInfoCompareInput.tooltip", sync.getSubscriber().getName(), node.getName()); //$NON-NLS-1$ } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object other) { if(other == this) return true; if(other instanceof SyncInfoCompareInput) { return equalDiffNodes(node, (SyncInfoDiffNode)((SyncInfoCompareInput)other).getCompareResult()); } else if(other instanceof SyncInfoCompareInputFinder) { return true; } return false; } private boolean equalDiffNodes(SyncInfoDiffNode node1, SyncInfoDiffNode node2) { if(node1 == null || node2 == null) { return false; } // First, ensure the local resources are equals IResource local1 = null; if (node1.getLeft() != null) local1 = ((LocalResourceTypedElement)node1.getLeft()).getResource(); IResource local2 = null; if (node2.getLeft() != null) local2 = ((LocalResourceTypedElement)node2.getLeft()).getResource(); if (!equalObjects(local1, local2)) return false; // Next, ensure the remote resources are equal IRemoteResource remote1 = null; if (node1.getRight() != null) remote1 = ((RemoteResourceTypedElement)node1.getRight()).getRemote(); IRemoteResource remote2 = null; if (node2.getRight() != null) remote2 = ((RemoteResourceTypedElement)node2.getRight()).getRemote(); if (!equalObjects(remote1, remote2)) return false; // Finally, ensure the base resources are equal IRemoteResource base1 = null; - if (node1.getRight() != null) + if (node1.getAncestor() != null) base1 = ((RemoteResourceTypedElement)node1.getAncestor()).getRemote(); IRemoteResource base2 = null; - if (node2.getRight() != null) + if (node2.getAncestor() != null) base2 = ((RemoteResourceTypedElement)node2.getAncestor()).getRemote(); if (!equalObjects(base1, base2)) return false; return true; } private boolean equalObjects(Object o1, Object o2) { if (o1 == null && o2 == null) return true; if (o1 == null || o2 == null) return false; return o1.equals(o2); } /* (non-Javadoc) * @see CompareEditorInput#saveChanges(org.eclipse.core.runtime.IProgressMonitor) */ public void saveChanges(IProgressMonitor pm) throws CoreException { super.saveChanges(pm); if (node instanceof DiffNode) { try { commit(pm, (DiffNode) node); } finally { setDirty(false); } } } /* * Recursively walks the diff tree and commits all changes. */ private static void commit(IProgressMonitor pm, DiffNode node) throws CoreException { ITypedElement left= node.getLeft(); if (left instanceof LocalResourceTypedElement) ((LocalResourceTypedElement) left).commit(pm); ITypedElement right= node.getRight(); if (right instanceof LocalResourceTypedElement) ((LocalResourceTypedElement) right).commit(pm); } public SyncInfo getSyncInfo() { return sync; } }
false
true
private boolean equalDiffNodes(SyncInfoDiffNode node1, SyncInfoDiffNode node2) { if(node1 == null || node2 == null) { return false; } // First, ensure the local resources are equals IResource local1 = null; if (node1.getLeft() != null) local1 = ((LocalResourceTypedElement)node1.getLeft()).getResource(); IResource local2 = null; if (node2.getLeft() != null) local2 = ((LocalResourceTypedElement)node2.getLeft()).getResource(); if (!equalObjects(local1, local2)) return false; // Next, ensure the remote resources are equal IRemoteResource remote1 = null; if (node1.getRight() != null) remote1 = ((RemoteResourceTypedElement)node1.getRight()).getRemote(); IRemoteResource remote2 = null; if (node2.getRight() != null) remote2 = ((RemoteResourceTypedElement)node2.getRight()).getRemote(); if (!equalObjects(remote1, remote2)) return false; // Finally, ensure the base resources are equal IRemoteResource base1 = null; if (node1.getRight() != null) base1 = ((RemoteResourceTypedElement)node1.getAncestor()).getRemote(); IRemoteResource base2 = null; if (node2.getRight() != null) base2 = ((RemoteResourceTypedElement)node2.getAncestor()).getRemote(); if (!equalObjects(base1, base2)) return false; return true; }
private boolean equalDiffNodes(SyncInfoDiffNode node1, SyncInfoDiffNode node2) { if(node1 == null || node2 == null) { return false; } // First, ensure the local resources are equals IResource local1 = null; if (node1.getLeft() != null) local1 = ((LocalResourceTypedElement)node1.getLeft()).getResource(); IResource local2 = null; if (node2.getLeft() != null) local2 = ((LocalResourceTypedElement)node2.getLeft()).getResource(); if (!equalObjects(local1, local2)) return false; // Next, ensure the remote resources are equal IRemoteResource remote1 = null; if (node1.getRight() != null) remote1 = ((RemoteResourceTypedElement)node1.getRight()).getRemote(); IRemoteResource remote2 = null; if (node2.getRight() != null) remote2 = ((RemoteResourceTypedElement)node2.getRight()).getRemote(); if (!equalObjects(remote1, remote2)) return false; // Finally, ensure the base resources are equal IRemoteResource base1 = null; if (node1.getAncestor() != null) base1 = ((RemoteResourceTypedElement)node1.getAncestor()).getRemote(); IRemoteResource base2 = null; if (node2.getAncestor() != null) base2 = ((RemoteResourceTypedElement)node2.getAncestor()).getRemote(); if (!equalObjects(base1, base2)) return false; return true; }
diff --git a/src/java/org/apache/nutch/parse/ParseUtil.java b/src/java/org/apache/nutch/parse/ParseUtil.java index ef0df5d2..7a6644b2 100644 --- a/src/java/org/apache/nutch/parse/ParseUtil.java +++ b/src/java/org/apache/nutch/parse/ParseUtil.java @@ -1,121 +1,122 @@ /** * Copyright 2005 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.nutch.parse; // JDK imports import java.util.logging.Logger; // Nutch Imports import org.apache.nutch.protocol.Content; import org.apache.nutch.util.LogFormatter; /** * A Utility class containing methods to simply perform parsing utilities such * as iterating through a preferred list of {@link Parser}s to obtain * {@link Parse} objects. * * @author mattmann * @author J&eacute;r&ocirc;me Charron * @author S&eacute;bastien Le Callonnec */ public class ParseUtil { /* our log stream */ public static final Logger LOG = LogFormatter.getLogger(ParseUtil.class .getName()); /** No public constructor */ private ParseUtil() { } /** * Performs a parse by iterating through a List of preferred {@Parser}s * until a successful parse is performed and a {@link Parse} object is * returned. If the parse is unsuccessful, a message is logged to the * <code>WARNING</code> level, and an empty parse is returned. * * @param content The content to try and parse. * @return A {@link Parse} object containing the parsed data. * @throws ParseException If no suitable parser is found to perform the parse. */ public final static Parse parse(Content content) throws ParseException { Parser[] parsers = null; try { parsers = ParserFactory.getParsers(content.getContentType(), ""); } catch (ParserNotFound e) { LOG.warning("No suitable parser found when trying to parse content " + content); throw new ParseException(e.getMessage()); } Parse parse = null; for (int i=0; i<parsers.length; i++) { - LOG.info("Parsing [" + content.getUrl() + "] with [" + parsers[i] + "]"); + LOG.fine("Parsing [" + content.getUrl() + "] with [" + parsers[i] + "]"); parse = parsers[i].getParse(content); if ((parse != null) && (parse.getData().getStatus().isSuccess())) { return parse; } } LOG.warning("Unable to successfully parse content " + content.getUrl() + " of type " + content.getContentType()); - return new ParseStatus().getEmptyParse(); + ParseStatus ps = (parse.getData() != null) ? parse.getData().getStatus() : null; + return (ps == null) ? new ParseStatus().getEmptyParse() : ps.getEmptyParse(); } /** * Method parses a {@link Content} object using the {@link Parser} specified * by the parameter <code>parserId</code>. If a suitable {@link Parser} is not * found, then a <code>WARNING</code> level message is logged, and a * ParseException is thrown. * If the parse is uncessful for any other reason, then a <code>WARNING</code> * level message is logged, and a <code>ParseStatus.getEmptyParse() is * returned. * * @param parserId The ID of the {@link Parser} to use to parse the specified * content. * @param content The content to parse. * @return A {@link Parse} object if the parse is successful, otherwise, * a <code>ParseStatus.getEmptyParse()</code>. * @throws ParseException If there is no suitable {@link Parser} found * to perform the parse. */ public final static Parse parseByParserId(String parserId, Content content) throws ParseException { Parse parse = null; Parser p = null; try { p = ParserFactory.getParserById(parserId); } catch (ParserNotFound e) { LOG.warning("No suitable parser found when trying to parse content " + content); throw new ParseException(e.getMessage()); } parse = p.getParse(content); if (parse != null && parse.getData().getStatus().isSuccess()) { return parse; } else { LOG.warning("Unable to successfully parse content " + content.getUrl() + " of type " + content.getContentType()); return new ParseStatus().getEmptyParse(); } } }
false
true
public final static Parse parse(Content content) throws ParseException { Parser[] parsers = null; try { parsers = ParserFactory.getParsers(content.getContentType(), ""); } catch (ParserNotFound e) { LOG.warning("No suitable parser found when trying to parse content " + content); throw new ParseException(e.getMessage()); } Parse parse = null; for (int i=0; i<parsers.length; i++) { LOG.info("Parsing [" + content.getUrl() + "] with [" + parsers[i] + "]"); parse = parsers[i].getParse(content); if ((parse != null) && (parse.getData().getStatus().isSuccess())) { return parse; } } LOG.warning("Unable to successfully parse content " + content.getUrl() + " of type " + content.getContentType()); return new ParseStatus().getEmptyParse(); }
public final static Parse parse(Content content) throws ParseException { Parser[] parsers = null; try { parsers = ParserFactory.getParsers(content.getContentType(), ""); } catch (ParserNotFound e) { LOG.warning("No suitable parser found when trying to parse content " + content); throw new ParseException(e.getMessage()); } Parse parse = null; for (int i=0; i<parsers.length; i++) { LOG.fine("Parsing [" + content.getUrl() + "] with [" + parsers[i] + "]"); parse = parsers[i].getParse(content); if ((parse != null) && (parse.getData().getStatus().isSuccess())) { return parse; } } LOG.warning("Unable to successfully parse content " + content.getUrl() + " of type " + content.getContentType()); ParseStatus ps = (parse.getData() != null) ? parse.getData().getStatus() : null; return (ps == null) ? new ParseStatus().getEmptyParse() : ps.getEmptyParse(); }
diff --git a/src/com/semaphore/sm/Commander.java b/src/com/semaphore/sm/Commander.java index aad56c2..4894738 100644 --- a/src/com/semaphore/sm/Commander.java +++ b/src/com/semaphore/sm/Commander.java @@ -1,314 +1,314 @@ /* Semaphore Manager * * Copyright (c) 2012 Stratos Karafotis ([email protected]) * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ package com.semaphore.sm; import android.util.Log; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; public class Commander { private static Commander instance = null; private List<String> errResult; private List<String> outResult; private List<String> kmsg; private Process p; OutputStreamWriter osw; OutputStreamWriter oswk; OutputStreamWriter oswl; // BufferedReader err; // BufferedReader out; protected Commander() { errResult = new ArrayList<String>(); outResult = new ArrayList<String>(); kmsg = new ArrayList<String>(); } public static Commander getInstance() { if (instance == null) { synchronized (Commander.class) { if (instance == null) { instance = new Commander(); } } } return instance; } public List<String> getErrResult() { return errResult; } public List<String> getOutResult() { return outResult; } public List<String> getKmsg() { return kmsg; } public void openShell() { ProcessBuilder pb = new ProcessBuilder("su", "-c", "/system/bin/sh"); try { p = pb.start(); OutputStream os = p.getOutputStream(); osw = new OutputStreamWriter(os); // err = new BufferedReader(new InputStreamReader(p.getErrorStream())); // out = new BufferedReader(new InputStreamReader(p.getInputStream())); // Preform su to get root privledges //p = Runtime.getRuntime().exec("su"); // Attempt to write a file to a root-only } catch (IOException ex) { } } public void closeShell() { try { // Close the terminal osw.write("\nexit\n"); osw.close(); } catch (IOException ex) { } } public boolean needSU(String path) { File f = new File(path); if (f.exists() && f.isFile() && f.canWrite()) { return false; } return true; } public int readFile(String path) { int result = 1; outResult.clear(); File f = new File(path); if (f.exists() && f.isFile() && f.canRead()) { try { BufferedReader br = new BufferedReader(new FileReader(f), 512); String line; try { while ((line = br.readLine()) != null) { outResult.add(line); } if (!outResult.isEmpty()) { result = 0; } br.close(); } catch (IOException ex) { Logger.getLogger(Commander.class.getName()).log(Level.SEVERE, null, ex); } } catch (FileNotFoundException ex) { Log.e(Commander.class.getName(), "Error reading file: ".concat(path)); } } return result; } public int writeFile(String path, String value) { try { File file = new File(path); if (!file.exists() || !file.canWrite()) { return 1; } FileWriter fw = new FileWriter(file.getAbsoluteFile()); fw.write(value); // BufferedWriter bw = new BufferedWriter(fw); // bw.write(value); fw.close(); return 0; } catch (IOException e) { Log.e(Commander.class.getName(), "Error writing file: ".concat(path)); return 1; } } public int runSuBatch(List<String> cmds) { int result = 0; int exitValue = -99; ProcessBuilder pb = new ProcessBuilder("su", "-c", "/system/bin/sh"); try { p = pb.start(); OutputStream os = p.getOutputStream(); osw = new OutputStreamWriter(os); for (String s : cmds) { osw.write(s + "\n"); } osw.write("\nexit\n"); osw.flush(); osw.close(); errResult.clear(); outResult.clear(); Thread errt = new streamReader(p.getErrorStream(), errResult); Thread outt = new streamReader(p.getInputStream(), outResult); errt.start(); outt.start(); try { exitValue = p.waitFor(); try { errt.join(); outt.join(); } catch (InterruptedException ex) { } if (exitValue == 0) { if (errResult.isEmpty()) { result = 0; } else { result = 1; } } else { result = 1; } } catch (InterruptedException e) { result = 1; } } catch (IOException e) { result = 1; } return result; } public int run(String cmd, boolean su) { int result = 0; ProcessBuilder pb; if (su) { pb = new ProcessBuilder("su", "-c", "/system/bin/sh"); } else { pb = new ProcessBuilder("/system/bin/sh"); } try { p = pb.start(); OutputStream os = p.getOutputStream(); osw = new OutputStreamWriter(os); osw.write(cmd); osw.write("\nexit\n"); osw.flush(); osw.close(); errResult.clear(); outResult.clear(); Thread errt = new streamReader(p.getErrorStream(), errResult); Thread outt = new streamReader(p.getInputStream(), outResult); errt.start(); outt.start(); try { - p.waitFor(); + int exitVal = p.waitFor(); try { errt.join(); outt.join(); } catch (InterruptedException ex) { } - if (p.exitValue() == 0) { + if (exitVal == 0) { if (errResult.isEmpty()) { result = 0; } else { result = 1; } } else { result = 1; } } catch (InterruptedException e) { result = 1; } } catch (IOException e) { result = 1; } return result; } public int readKmsg() { int result = 0; ProcessBuilder pb = new ProcessBuilder("su", "-c", "/system/bin/sh"); try { p = pb.start(); OutputStream os = p.getOutputStream(); oswk = new OutputStreamWriter(os); oswk.write("cat /proc/kmsg\n"); oswk.flush(); oswk.close(); kmsg.clear(); Thread outt = new streamReader(p.getInputStream(), kmsg); outt.start(); } catch (IOException e) { } return result; } public void clearKmsg() { kmsg.clear(); } private class streamReader extends Thread { InputStream inputStream; List<String> result; streamReader(InputStream inputStrem, List<String> result) { this.inputStream = inputStrem; this.result = result; } @Override public void run() { try { BufferedReader out = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = out.readLine()) != null) { result.add(line); } } catch (java.io.IOException e) { } } public List<String> getResult() { return result; } } }
false
true
public int run(String cmd, boolean su) { int result = 0; ProcessBuilder pb; if (su) { pb = new ProcessBuilder("su", "-c", "/system/bin/sh"); } else { pb = new ProcessBuilder("/system/bin/sh"); } try { p = pb.start(); OutputStream os = p.getOutputStream(); osw = new OutputStreamWriter(os); osw.write(cmd); osw.write("\nexit\n"); osw.flush(); osw.close(); errResult.clear(); outResult.clear(); Thread errt = new streamReader(p.getErrorStream(), errResult); Thread outt = new streamReader(p.getInputStream(), outResult); errt.start(); outt.start(); try { p.waitFor(); try { errt.join(); outt.join(); } catch (InterruptedException ex) { } if (p.exitValue() == 0) { if (errResult.isEmpty()) { result = 0; } else { result = 1; } } else { result = 1; } } catch (InterruptedException e) { result = 1; } } catch (IOException e) { result = 1; } return result; }
public int run(String cmd, boolean su) { int result = 0; ProcessBuilder pb; if (su) { pb = new ProcessBuilder("su", "-c", "/system/bin/sh"); } else { pb = new ProcessBuilder("/system/bin/sh"); } try { p = pb.start(); OutputStream os = p.getOutputStream(); osw = new OutputStreamWriter(os); osw.write(cmd); osw.write("\nexit\n"); osw.flush(); osw.close(); errResult.clear(); outResult.clear(); Thread errt = new streamReader(p.getErrorStream(), errResult); Thread outt = new streamReader(p.getInputStream(), outResult); errt.start(); outt.start(); try { int exitVal = p.waitFor(); try { errt.join(); outt.join(); } catch (InterruptedException ex) { } if (exitVal == 0) { if (errResult.isEmpty()) { result = 0; } else { result = 1; } } else { result = 1; } } catch (InterruptedException e) { result = 1; } } catch (IOException e) { result = 1; } return result; }
diff --git a/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/repository/tree/command/RemoveCommand.java b/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/repository/tree/command/RemoveCommand.java index 35b5f01d..2ab197c9 100644 --- a/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/repository/tree/command/RemoveCommand.java +++ b/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/repository/tree/command/RemoveCommand.java @@ -1,202 +1,205 @@ /******************************************************************************* * Copyright (c) 2010 SAP AG. * 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: * Mathias Kinzler (SAP AG) - initial implementation *******************************************************************************/ package org.eclipse.egit.ui.internal.repository.tree.command; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.commands.IHandler; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.IWorkspaceRunnable; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.egit.ui.Activator; import org.eclipse.egit.ui.UIText; import org.eclipse.egit.ui.internal.repository.tree.RepositoryNode; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.util.FileUtils; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IWorkbenchSite; import org.eclipse.ui.handlers.HandlerUtil; import org.eclipse.ui.progress.IWorkbenchSiteProgressService; /** * "Removes" one or several nodes */ public class RemoveCommand extends RepositoriesViewCommandHandler<RepositoryNode> implements IHandler { public Object execute(final ExecutionEvent event) throws ExecutionException { removeRepository(event, false); return null; } /** * Remove or delete the repository * * @param event * @param delete * if <code>true</code>, the repository will be deleted from disk */ protected void removeRepository(final ExecutionEvent event, final boolean delete) { IWorkbenchSite activeSite = HandlerUtil.getActiveSite(event); IWorkbenchSiteProgressService service = (IWorkbenchSiteProgressService) activeSite .getService(IWorkbenchSiteProgressService.class); // get selected nodes final List<RepositoryNode> selectedNodes; try { selectedNodes = getSelectedNodes(event); } catch (ExecutionException e) { Activator.handleError(e.getMessage(), e, true); return; } if (delete) { String title = UIText.RemoveCommand_DeleteConfirmTitle; if (selectedNodes.size() > 1) { String message = NLS.bind( UIText.RemoveCommand_DeleteConfirmSingleMessage, Integer.valueOf(selectedNodes.size())); if (!MessageDialog.openConfirm(getShell(event), title, message)) return; } else if (selectedNodes.size() == 1) { String name = org.eclipse.egit.core.Activator.getDefault() .getRepositoryUtil() .getRepositoryName(selectedNodes.get(0).getObject()); String message = NLS.bind( UIText.RemoveCommand_DeleteConfirmMultiMessage, name); if (!MessageDialog.openConfirm(getShell(event), title, message)) return; } } Job job = new Job("Remove Repositories Job") { //$NON-NLS-1$ @Override protected IStatus run(IProgressMonitor monitor) { final List<IProject> projectsToDelete = new ArrayList<IProject>(); monitor .setTaskName(UIText.RepositoriesView_DeleteRepoDeterminProjectsMessage); for (RepositoryNode node : selectedNodes) { if (node.getRepository().isBare()) continue; File workDir = node.getRepository().getWorkTree(); final IPath wdPath = new Path(workDir.getAbsolutePath()); for (IProject prj : ResourcesPlugin.getWorkspace() .getRoot().getProjects()) { if (monitor.isCanceled()) return Status.OK_STATUS; if (wdPath.isPrefixOf(prj.getLocation())) { projectsToDelete.add(prj); } } } final boolean[] confirmedCanceled = new boolean[] { false, false }; if (!projectsToDelete.isEmpty()) { Display.getDefault().syncExec(new Runnable() { public void run() { try { confirmedCanceled[0] = confirmProjectDeletion( projectsToDelete, event); } catch (OperationCanceledException e) { confirmedCanceled[1] = true; } } }); } if (confirmedCanceled[1]) { // canceled: return return Status.OK_STATUS; } if (confirmedCanceled[0]) { // confirmed deletion IWorkspaceRunnable wsr = new IWorkspaceRunnable() { public void run(IProgressMonitor actMonitor) throws CoreException { for (IProject prj : projectsToDelete) prj.delete(false, false, actMonitor); } }; try { ResourcesPlugin.getWorkspace().run(wsr, ResourcesPlugin.getWorkspace().getRoot(), IWorkspace.AVOID_UPDATE, monitor); } catch (CoreException e1) { Activator.logError(e1.getMessage(), e1); } } for (RepositoryNode node : selectedNodes) { util.removeDir(node.getRepository().getDirectory()); } if (delete) { try { for (RepositoryNode node : selectedNodes) { Repository repo = node.getRepository(); if (!repo.isBare()) - FileUtils.delete(repo.getWorkTree(), FileUtils.RECURSIVE | FileUtils.RETRY); - FileUtils.delete(repo.getDirectory(), FileUtils.RECURSIVE | FileUtils.RETRY); + FileUtils.delete(repo.getWorkTree(), + FileUtils.RECURSIVE | FileUtils.RETRY); + FileUtils.delete(repo.getDirectory(), + FileUtils.RECURSIVE | FileUtils.RETRY + | FileUtils.SKIP_MISSING); } } catch (IOException e) { return Activator.createErrorStatus(e.getMessage(), e); } } return Status.OK_STATUS; } }; service.schedule(job); } @SuppressWarnings("boxing") private boolean confirmProjectDeletion(List<IProject> projectsToDelete, ExecutionEvent event) throws OperationCanceledException { String message = NLS.bind( UIText.RepositoriesView_ConfirmProjectDeletion_Question, projectsToDelete.size()); MessageDialog dlg = new MessageDialog(getShell(event), UIText.RepositoriesView_ConfirmProjectDeletion_WindowTitle, null, message, MessageDialog.INFORMATION, new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL }, 0); int index = dlg.open(); if (index == 2) throw new OperationCanceledException(); return index == 0; } }
true
true
protected void removeRepository(final ExecutionEvent event, final boolean delete) { IWorkbenchSite activeSite = HandlerUtil.getActiveSite(event); IWorkbenchSiteProgressService service = (IWorkbenchSiteProgressService) activeSite .getService(IWorkbenchSiteProgressService.class); // get selected nodes final List<RepositoryNode> selectedNodes; try { selectedNodes = getSelectedNodes(event); } catch (ExecutionException e) { Activator.handleError(e.getMessage(), e, true); return; } if (delete) { String title = UIText.RemoveCommand_DeleteConfirmTitle; if (selectedNodes.size() > 1) { String message = NLS.bind( UIText.RemoveCommand_DeleteConfirmSingleMessage, Integer.valueOf(selectedNodes.size())); if (!MessageDialog.openConfirm(getShell(event), title, message)) return; } else if (selectedNodes.size() == 1) { String name = org.eclipse.egit.core.Activator.getDefault() .getRepositoryUtil() .getRepositoryName(selectedNodes.get(0).getObject()); String message = NLS.bind( UIText.RemoveCommand_DeleteConfirmMultiMessage, name); if (!MessageDialog.openConfirm(getShell(event), title, message)) return; } } Job job = new Job("Remove Repositories Job") { //$NON-NLS-1$ @Override protected IStatus run(IProgressMonitor monitor) { final List<IProject> projectsToDelete = new ArrayList<IProject>(); monitor .setTaskName(UIText.RepositoriesView_DeleteRepoDeterminProjectsMessage); for (RepositoryNode node : selectedNodes) { if (node.getRepository().isBare()) continue; File workDir = node.getRepository().getWorkTree(); final IPath wdPath = new Path(workDir.getAbsolutePath()); for (IProject prj : ResourcesPlugin.getWorkspace() .getRoot().getProjects()) { if (monitor.isCanceled()) return Status.OK_STATUS; if (wdPath.isPrefixOf(prj.getLocation())) { projectsToDelete.add(prj); } } } final boolean[] confirmedCanceled = new boolean[] { false, false }; if (!projectsToDelete.isEmpty()) { Display.getDefault().syncExec(new Runnable() { public void run() { try { confirmedCanceled[0] = confirmProjectDeletion( projectsToDelete, event); } catch (OperationCanceledException e) { confirmedCanceled[1] = true; } } }); } if (confirmedCanceled[1]) { // canceled: return return Status.OK_STATUS; } if (confirmedCanceled[0]) { // confirmed deletion IWorkspaceRunnable wsr = new IWorkspaceRunnable() { public void run(IProgressMonitor actMonitor) throws CoreException { for (IProject prj : projectsToDelete) prj.delete(false, false, actMonitor); } }; try { ResourcesPlugin.getWorkspace().run(wsr, ResourcesPlugin.getWorkspace().getRoot(), IWorkspace.AVOID_UPDATE, monitor); } catch (CoreException e1) { Activator.logError(e1.getMessage(), e1); } } for (RepositoryNode node : selectedNodes) { util.removeDir(node.getRepository().getDirectory()); } if (delete) { try { for (RepositoryNode node : selectedNodes) { Repository repo = node.getRepository(); if (!repo.isBare()) FileUtils.delete(repo.getWorkTree(), FileUtils.RECURSIVE | FileUtils.RETRY); FileUtils.delete(repo.getDirectory(), FileUtils.RECURSIVE | FileUtils.RETRY); } } catch (IOException e) { return Activator.createErrorStatus(e.getMessage(), e); } } return Status.OK_STATUS; } }; service.schedule(job); }
protected void removeRepository(final ExecutionEvent event, final boolean delete) { IWorkbenchSite activeSite = HandlerUtil.getActiveSite(event); IWorkbenchSiteProgressService service = (IWorkbenchSiteProgressService) activeSite .getService(IWorkbenchSiteProgressService.class); // get selected nodes final List<RepositoryNode> selectedNodes; try { selectedNodes = getSelectedNodes(event); } catch (ExecutionException e) { Activator.handleError(e.getMessage(), e, true); return; } if (delete) { String title = UIText.RemoveCommand_DeleteConfirmTitle; if (selectedNodes.size() > 1) { String message = NLS.bind( UIText.RemoveCommand_DeleteConfirmSingleMessage, Integer.valueOf(selectedNodes.size())); if (!MessageDialog.openConfirm(getShell(event), title, message)) return; } else if (selectedNodes.size() == 1) { String name = org.eclipse.egit.core.Activator.getDefault() .getRepositoryUtil() .getRepositoryName(selectedNodes.get(0).getObject()); String message = NLS.bind( UIText.RemoveCommand_DeleteConfirmMultiMessage, name); if (!MessageDialog.openConfirm(getShell(event), title, message)) return; } } Job job = new Job("Remove Repositories Job") { //$NON-NLS-1$ @Override protected IStatus run(IProgressMonitor monitor) { final List<IProject> projectsToDelete = new ArrayList<IProject>(); monitor .setTaskName(UIText.RepositoriesView_DeleteRepoDeterminProjectsMessage); for (RepositoryNode node : selectedNodes) { if (node.getRepository().isBare()) continue; File workDir = node.getRepository().getWorkTree(); final IPath wdPath = new Path(workDir.getAbsolutePath()); for (IProject prj : ResourcesPlugin.getWorkspace() .getRoot().getProjects()) { if (monitor.isCanceled()) return Status.OK_STATUS; if (wdPath.isPrefixOf(prj.getLocation())) { projectsToDelete.add(prj); } } } final boolean[] confirmedCanceled = new boolean[] { false, false }; if (!projectsToDelete.isEmpty()) { Display.getDefault().syncExec(new Runnable() { public void run() { try { confirmedCanceled[0] = confirmProjectDeletion( projectsToDelete, event); } catch (OperationCanceledException e) { confirmedCanceled[1] = true; } } }); } if (confirmedCanceled[1]) { // canceled: return return Status.OK_STATUS; } if (confirmedCanceled[0]) { // confirmed deletion IWorkspaceRunnable wsr = new IWorkspaceRunnable() { public void run(IProgressMonitor actMonitor) throws CoreException { for (IProject prj : projectsToDelete) prj.delete(false, false, actMonitor); } }; try { ResourcesPlugin.getWorkspace().run(wsr, ResourcesPlugin.getWorkspace().getRoot(), IWorkspace.AVOID_UPDATE, monitor); } catch (CoreException e1) { Activator.logError(e1.getMessage(), e1); } } for (RepositoryNode node : selectedNodes) { util.removeDir(node.getRepository().getDirectory()); } if (delete) { try { for (RepositoryNode node : selectedNodes) { Repository repo = node.getRepository(); if (!repo.isBare()) FileUtils.delete(repo.getWorkTree(), FileUtils.RECURSIVE | FileUtils.RETRY); FileUtils.delete(repo.getDirectory(), FileUtils.RECURSIVE | FileUtils.RETRY | FileUtils.SKIP_MISSING); } } catch (IOException e) { return Activator.createErrorStatus(e.getMessage(), e); } } return Status.OK_STATUS; } }; service.schedule(job); }
diff --git a/src/main/java/cd/semantic/ti/GlobalConstraintGeneratorContext.java b/src/main/java/cd/semantic/ti/GlobalConstraintGeneratorContext.java index bdc0f09..f205ed5 100644 --- a/src/main/java/cd/semantic/ti/GlobalConstraintGeneratorContext.java +++ b/src/main/java/cd/semantic/ti/GlobalConstraintGeneratorContext.java @@ -1,77 +1,77 @@ package cd.semantic.ti; import java.util.Collections; import java.util.HashMap; import java.util.Map; import cd.ir.symbols.ClassSymbol; import cd.ir.symbols.MethodSymbol; import cd.ir.symbols.VariableSymbol; import cd.semantic.TypeSymbolTable; import cd.semantic.ti.constraintSolving.TypeVariable; /** * Context used for constraint generation in global type inference. * * Most importantly, it provides a static construction method * {@code #of(TypeSymbolTable)} that initializes the context. * * Secondly, it holds all type variables for the return value of each method. */ public final class GlobalConstraintGeneratorContext extends ConstraintGeneratorContext { private final Map<MethodSymbol, TypeVariable> returnTypeSets; private GlobalConstraintGeneratorContext(TypeSymbolTable typeSymbols) { super(typeSymbols); this.returnTypeSets = new HashMap<>(); } /** * Constructs a new constraint generation context containing <b>all</b> * variable symbols in the whole type symbol table. * * @param typeSymbols * @return the newly constructed context */ public static GlobalConstraintGeneratorContext of( TypeSymbolTable typeSymbols) { GlobalConstraintGeneratorContext result = new GlobalConstraintGeneratorContext( typeSymbols); for (ClassSymbol classSymbol : typeSymbols.getClassSymbols()) { String prefix = classSymbol.getName() + "_"; for (MethodSymbol methodSymbol : classSymbol.getDeclaredMethods()) { String methodPrefix = prefix + methodSymbol.getName() + "_"; for (VariableSymbol variable : methodSymbol .getLocalsAndParameters()) { - String desc = prefix + variable.getName(); + String desc = methodPrefix + variable.getName(); result.addVariableTypeSet(variable, desc); } TypeVariable returnTypeVariable = result.getConstraintSystem() .addTypeVariable(methodPrefix + "return"); result.returnTypeSets.put(methodSymbol, returnTypeVariable); } for (VariableSymbol field : classSymbol.getDeclaredFields()) { String desc = prefix + field.getName(); result.addVariableTypeSet(field, desc); } } return result; } public Map<MethodSymbol, TypeVariable> getReturnTypeSets() { return Collections.unmodifiableMap(returnTypeSets); } @Override public TypeVariable getReturnTypeSet(MethodSymbol method) { return returnTypeSets.get(method); } }
true
true
public static GlobalConstraintGeneratorContext of( TypeSymbolTable typeSymbols) { GlobalConstraintGeneratorContext result = new GlobalConstraintGeneratorContext( typeSymbols); for (ClassSymbol classSymbol : typeSymbols.getClassSymbols()) { String prefix = classSymbol.getName() + "_"; for (MethodSymbol methodSymbol : classSymbol.getDeclaredMethods()) { String methodPrefix = prefix + methodSymbol.getName() + "_"; for (VariableSymbol variable : methodSymbol .getLocalsAndParameters()) { String desc = prefix + variable.getName(); result.addVariableTypeSet(variable, desc); } TypeVariable returnTypeVariable = result.getConstraintSystem() .addTypeVariable(methodPrefix + "return"); result.returnTypeSets.put(methodSymbol, returnTypeVariable); } for (VariableSymbol field : classSymbol.getDeclaredFields()) { String desc = prefix + field.getName(); result.addVariableTypeSet(field, desc); } } return result; }
public static GlobalConstraintGeneratorContext of( TypeSymbolTable typeSymbols) { GlobalConstraintGeneratorContext result = new GlobalConstraintGeneratorContext( typeSymbols); for (ClassSymbol classSymbol : typeSymbols.getClassSymbols()) { String prefix = classSymbol.getName() + "_"; for (MethodSymbol methodSymbol : classSymbol.getDeclaredMethods()) { String methodPrefix = prefix + methodSymbol.getName() + "_"; for (VariableSymbol variable : methodSymbol .getLocalsAndParameters()) { String desc = methodPrefix + variable.getName(); result.addVariableTypeSet(variable, desc); } TypeVariable returnTypeVariable = result.getConstraintSystem() .addTypeVariable(methodPrefix + "return"); result.returnTypeSets.put(methodSymbol, returnTypeVariable); } for (VariableSymbol field : classSymbol.getDeclaredFields()) { String desc = prefix + field.getName(); result.addVariableTypeSet(field, desc); } } return result; }
diff --git a/src/main/java/org/basex/server/QueryListener.java b/src/main/java/org/basex/server/QueryListener.java index 230cd4601..fc7ac6f7a 100644 --- a/src/main/java/org/basex/server/QueryListener.java +++ b/src/main/java/org/basex/server/QueryListener.java @@ -1,147 +1,144 @@ package org.basex.server; import static org.basex.core.Text.*; import static org.basex.io.serial.SerializerProp.*; import java.io.IOException; import java.io.OutputStream; import org.basex.core.BaseXException; import org.basex.core.Context; import org.basex.core.Progress; import org.basex.io.out.EncodingOutput; import org.basex.io.out.PrintOutput; import org.basex.io.serial.Serializer; import org.basex.io.serial.SerializerProp; import org.basex.query.QueryException; import org.basex.query.QueryProcessor; import org.basex.query.item.Item; import org.basex.query.iter.Iter; import org.basex.util.Performance; import org.basex.util.TokenBuilder; /** * Server-side query session in the client-server architecture. * * @author BaseX Team 2005-11, BSD License * @author Andreas Weiler * @author Christian Gruen */ final class QueryListener extends Progress { /** Performance. */ private final Performance perf = new Performance(); /** Query processor. */ private final QueryProcessor qp; /** Database context. */ private final Context ctx; /** Query info. */ private String info = ""; /** Serialization options. */ private String options = ""; /** * Constructor. * @param qu query string * @param c database context */ QueryListener(final String qu, final Context c) { qp = new QueryProcessor(qu, c); ctx = c; } /** * Binds an object to a global variable. * @param n name of variable * @param o object to be bound * @param t type * @throws IOException query exception */ void bind(final String n, final Object o, final String t) throws IOException { try { qp.bind(n, o, t); } catch(final QueryException ex) { throw new BaseXException(ex); } } /** * Returns the query info. * @return query info */ String info() { return info; } /** * Returns the serialization options. * @return serialization options */ String options() { return options; } /** * Executes the query. * @param iter iterative evaluation * @param out output stream * @param enc encode stream * @throws IOException Exception */ void execute(final boolean iter, final OutputStream out, final boolean enc) throws IOException { boolean mon = false; try { qp.parse(); ctx.register(qp.ctx.updating); mon = true; // create serializer final Iter ir = qp.iter(); final SerializerProp sprop = qp.ctx.serProp(false); final boolean wrap = !sprop.get(S_WRAP_PREFIX).isEmpty(); options = qp.ctx.serProp(false).toString(); // iterate through results final PrintOutput po = PrintOutput.get(enc ? new EncodingOutput(out) : out); if(iter && wrap) po.write(1); final Serializer ser = Serializer.get(po, sprop); int c = 0; for(Item it; (it = ir.next()) != null;) { if(iter && !wrap) { po.write(1); ser.reset(); } ser.openResult(); it.serialize(ser); ser.closeResult(); if(iter && !wrap) { po.flush(); out.write(0); } c++; } ser.close(); - if(iter) { - if(wrap) out.write(0); - out.write(0); - } + if(iter && wrap) out.write(0); // generate query info final int up = qp.updates(); final TokenBuilder tb = new TokenBuilder(); tb.addExt(QUERYHITS + "% %" + NL, c, c == 1 ? VALHIT : VALHITS); tb.addExt(QUERYUPDATED + "% %" + NL, up, up == 1 ? VALHIT : VALHITS); tb.addExt(QUERYTOTAL + "%", perf); info = tb.toString(); } catch(final QueryException ex) { throw new BaseXException(ex); } finally { try { qp.close(); } catch(final IOException ex) { } if(mon) ctx.unregister(qp.ctx.updating); } } }
true
true
void execute(final boolean iter, final OutputStream out, final boolean enc) throws IOException { boolean mon = false; try { qp.parse(); ctx.register(qp.ctx.updating); mon = true; // create serializer final Iter ir = qp.iter(); final SerializerProp sprop = qp.ctx.serProp(false); final boolean wrap = !sprop.get(S_WRAP_PREFIX).isEmpty(); options = qp.ctx.serProp(false).toString(); // iterate through results final PrintOutput po = PrintOutput.get(enc ? new EncodingOutput(out) : out); if(iter && wrap) po.write(1); final Serializer ser = Serializer.get(po, sprop); int c = 0; for(Item it; (it = ir.next()) != null;) { if(iter && !wrap) { po.write(1); ser.reset(); } ser.openResult(); it.serialize(ser); ser.closeResult(); if(iter && !wrap) { po.flush(); out.write(0); } c++; } ser.close(); if(iter) { if(wrap) out.write(0); out.write(0); } // generate query info final int up = qp.updates(); final TokenBuilder tb = new TokenBuilder(); tb.addExt(QUERYHITS + "% %" + NL, c, c == 1 ? VALHIT : VALHITS); tb.addExt(QUERYUPDATED + "% %" + NL, up, up == 1 ? VALHIT : VALHITS); tb.addExt(QUERYTOTAL + "%", perf); info = tb.toString(); } catch(final QueryException ex) { throw new BaseXException(ex); } finally { try { qp.close(); } catch(final IOException ex) { } if(mon) ctx.unregister(qp.ctx.updating); } }
void execute(final boolean iter, final OutputStream out, final boolean enc) throws IOException { boolean mon = false; try { qp.parse(); ctx.register(qp.ctx.updating); mon = true; // create serializer final Iter ir = qp.iter(); final SerializerProp sprop = qp.ctx.serProp(false); final boolean wrap = !sprop.get(S_WRAP_PREFIX).isEmpty(); options = qp.ctx.serProp(false).toString(); // iterate through results final PrintOutput po = PrintOutput.get(enc ? new EncodingOutput(out) : out); if(iter && wrap) po.write(1); final Serializer ser = Serializer.get(po, sprop); int c = 0; for(Item it; (it = ir.next()) != null;) { if(iter && !wrap) { po.write(1); ser.reset(); } ser.openResult(); it.serialize(ser); ser.closeResult(); if(iter && !wrap) { po.flush(); out.write(0); } c++; } ser.close(); if(iter && wrap) out.write(0); // generate query info final int up = qp.updates(); final TokenBuilder tb = new TokenBuilder(); tb.addExt(QUERYHITS + "% %" + NL, c, c == 1 ? VALHIT : VALHITS); tb.addExt(QUERYUPDATED + "% %" + NL, up, up == 1 ? VALHIT : VALHITS); tb.addExt(QUERYTOTAL + "%", perf); info = tb.toString(); } catch(final QueryException ex) { throw new BaseXException(ex); } finally { try { qp.close(); } catch(final IOException ex) { } if(mon) ctx.unregister(qp.ctx.updating); } }
diff --git a/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/TimeGraphCombo.java b/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/TimeGraphCombo.java index 5eec1e566..7ba43cde6 100644 --- a/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/TimeGraphCombo.java +++ b/lttng/org.eclipse.linuxtools.tmf.ui/src/org/eclipse/linuxtools/tmf/ui/widgets/timegraph/TimeGraphCombo.java @@ -1,992 +1,1002 @@ /******************************************************************************* * Copyright (c) 2012, 2013 Ericsson, 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: * Patrick Tasse - Initial API and implementation * François Rajotte - Filter implementation *******************************************************************************/ package org.eclipse.linuxtools.tmf.ui.widgets.timegraph; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.eclipse.jface.action.Action; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.ITreeViewerListener; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TreeExpansionEvent; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.linuxtools.internal.tmf.ui.Activator; import org.eclipse.linuxtools.internal.tmf.ui.ITmfImageConstants; import org.eclipse.linuxtools.internal.tmf.ui.Messages; import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.dialogs.TimeGraphFilterDialog; import org.eclipse.linuxtools.tmf.ui.widgets.timegraph.model.ITimeGraphEntry; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.events.ControlAdapter; import org.eclipse.swt.events.ControlEvent; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseTrackAdapter; import org.eclipse.swt.events.MouseWheelListener; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Slider; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeColumn; import org.eclipse.swt.widgets.TreeItem; /** * Time graph "combo" view (with the list/tree on the left and the gantt chart * on the right) * * @version 1.0 * @author Patrick Tasse */ public class TimeGraphCombo extends Composite { // ------------------------------------------------------------------------ // Constants // ------------------------------------------------------------------------ private static final Object FILLER = new Object(); // ------------------------------------------------------------------------ // Fields // ------------------------------------------------------------------------ // The tree viewer private TreeViewer fTreeViewer; // The time viewer private TimeGraphViewer fTimeGraphViewer; // The top-level input (children excluded) private List<? extends ITimeGraphEntry> fTopInput; // The selection listener map private final Map<ITimeGraphSelectionListener, SelectionListenerWrapper> fSelectionListenerMap = new HashMap<ITimeGraphSelectionListener, SelectionListenerWrapper>(); // The map of viewer filters private final Map<ViewerFilter, ViewerFilter> fViewerFilterMap = new HashMap<ViewerFilter, ViewerFilter>(); // Flag to block the tree selection changed listener when triggered by the time graph combo private boolean fInhibitTreeSelection = false; // Number of filler rows used by the tree content provider private int fNumFillerRows; // Calculated item height for Linux workaround private int fLinuxItemHeight = 0; // The button that opens the filter dialog private Action showFilterAction; // The filter dialog private TimeGraphFilterDialog fFilterDialog; // The filter generated from the filter dialog private RawViewerFilter fFilter; // ------------------------------------------------------------------------ // Classes // ------------------------------------------------------------------------ /** * The TreeContentProviderWrapper is used to insert filler items after * the elements of the tree's real content provider. */ private class TreeContentProviderWrapper implements ITreeContentProvider { private final ITreeContentProvider contentProvider; public TreeContentProviderWrapper(ITreeContentProvider contentProvider) { this.contentProvider = contentProvider; } @Override public void dispose() { contentProvider.dispose(); } @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { contentProvider.inputChanged(viewer, oldInput, newInput); } @Override public Object[] getElements(Object inputElement) { Object[] elements = contentProvider.getElements(inputElement); // add filler elements to ensure alignment with time analysis viewer Object[] oElements = Arrays.copyOf(elements, elements.length + fNumFillerRows, Object[].class); for (int i = 0; i < fNumFillerRows; i++) { oElements[elements.length + i] = FILLER; } return oElements; } @Override public Object[] getChildren(Object parentElement) { if (parentElement instanceof ITimeGraphEntry) { return contentProvider.getChildren(parentElement); } return new Object[0]; } @Override public Object getParent(Object element) { if (element instanceof ITimeGraphEntry) { return contentProvider.getParent(element); } return null; } @Override public boolean hasChildren(Object element) { if (element instanceof ITimeGraphEntry) { return contentProvider.hasChildren(element); } return false; } } /** * The TreeLabelProviderWrapper is used to intercept the filler items * from the calls to the tree's real label provider. */ private class TreeLabelProviderWrapper implements ITableLabelProvider { private final ITableLabelProvider labelProvider; public TreeLabelProviderWrapper(ITableLabelProvider labelProvider) { this.labelProvider = labelProvider; } @Override public void addListener(ILabelProviderListener listener) { labelProvider.addListener(listener); } @Override public void dispose() { labelProvider.dispose(); } @Override public boolean isLabelProperty(Object element, String property) { if (element instanceof ITimeGraphEntry) { return labelProvider.isLabelProperty(element, property); } return false; } @Override public void removeListener(ILabelProviderListener listener) { labelProvider.removeListener(listener); } @Override public Image getColumnImage(Object element, int columnIndex) { if (element instanceof ITimeGraphEntry) { return labelProvider.getColumnImage(element, columnIndex); } return null; } @Override public String getColumnText(Object element, int columnIndex) { if (element instanceof ITimeGraphEntry) { return labelProvider.getColumnText(element, columnIndex); } return null; } } /** * The SelectionListenerWrapper is used to intercept the filler items from * the time graph combo's real selection listener, and to prevent double * notifications from being sent when selection changes in both tree and * time graph at the same time. */ private class SelectionListenerWrapper implements ISelectionChangedListener, ITimeGraphSelectionListener { private final ITimeGraphSelectionListener listener; private ITimeGraphEntry selection = null; public SelectionListenerWrapper(ITimeGraphSelectionListener listener) { this.listener = listener; } @Override public void selectionChanged(SelectionChangedEvent event) { if (fInhibitTreeSelection) { return; } Object element = ((IStructuredSelection) event.getSelection()).getFirstElement(); if (element instanceof ITimeGraphEntry) { ITimeGraphEntry entry = (ITimeGraphEntry) element; if (entry != selection) { selection = entry; listener.selectionChanged(new TimeGraphSelectionEvent(event.getSource(), selection)); } } } @Override public void selectionChanged(TimeGraphSelectionEvent event) { ITimeGraphEntry entry = event.getSelection(); if (entry != selection) { selection = entry; listener.selectionChanged(new TimeGraphSelectionEvent(event.getSource(), selection)); } } } /** * The ViewerFilterWrapper is used to intercept the filler items from * the time graph combo's real ViewerFilters. These filler items should * always be visible. */ private class ViewerFilterWrapper extends ViewerFilter { private ViewerFilter fWrappedFilter; ViewerFilterWrapper(ViewerFilter filter) { super(); this.fWrappedFilter = filter; } @Override public boolean select(Viewer viewer, Object parentElement, Object element) { if (element instanceof ITimeGraphEntry) { return fWrappedFilter.select(viewer, parentElement, element); } return true; } } /** * This filter simply keeps a list of elements that should be filtered out. * All the other elements will be shown. * By default and when the list is set to null, all elements are shown. */ private class RawViewerFilter extends ViewerFilter { private List<Object> fFiltered = null; public void setFiltered(List<Object> objects) { fFiltered = objects; } public List<Object> getFiltered() { return fFiltered; } @Override public boolean select(Viewer viewer, Object parentElement, Object element) { if (fFiltered == null) { return true; } return !fFiltered.contains(element); } } // ------------------------------------------------------------------------ // Constructors // ------------------------------------------------------------------------ /** * Constructs a new instance of this class given its parent * and a style value describing its behavior and appearance. * * @param parent a widget which will be the parent of the new instance (cannot be null) * @param style the style of widget to construct */ public TimeGraphCombo(Composite parent, int style) { super(parent, style); setLayout(new FillLayout()); final SashForm sash = new SashForm(this, SWT.NONE); fTreeViewer = new TreeViewer(sash, SWT.FULL_SELECTION | SWT.H_SCROLL); final Tree tree = fTreeViewer.getTree(); tree.setHeaderVisible(true); tree.setLinesVisible(true); fTimeGraphViewer = new TimeGraphViewer(sash, SWT.NONE); fTimeGraphViewer.setItemHeight(getItemHeight(tree)); fTimeGraphViewer.setHeaderHeight(tree.getHeaderHeight()); fTimeGraphViewer.setBorderWidth(tree.getBorderWidth()); fTimeGraphViewer.setNameWidthPref(0); fFilter = new RawViewerFilter(); addFilter(fFilter); fFilterDialog = new TimeGraphFilterDialog(getShell()); // Feature in Windows. The tree vertical bar reappears when // the control is resized so we need to hide it again. // Bug in Linux. The tree header height is 0 in constructor, // so we need to reset it later when the control is resized. tree.addControlListener(new ControlAdapter() { private int depth = 0; @Override public void controlResized(ControlEvent e) { if (depth == 0) { depth++; tree.getVerticalBar().setEnabled(false); // this can trigger controlResized recursively tree.getVerticalBar().setVisible(false); depth--; } fTimeGraphViewer.setHeaderHeight(tree.getHeaderHeight()); } }); // ensure synchronization of expanded items between tree and time graph fTreeViewer.addTreeListener(new ITreeViewerListener() { @Override public void treeCollapsed(TreeExpansionEvent event) { fTimeGraphViewer.setExpandedState((ITimeGraphEntry) event.getElement(), false); List<TreeItem> treeItems = getVisibleExpandedItems(tree); if (treeItems.size() == 0) { return; } TreeItem treeItem = treeItems.get(fTimeGraphViewer.getTopIndex()); tree.setTopItem(treeItem); } @Override public void treeExpanded(TreeExpansionEvent event) { - fTimeGraphViewer.setExpandedState((ITimeGraphEntry) event.getElement(), true); + ITimeGraphEntry entry = (ITimeGraphEntry) event.getElement(); + fTimeGraphViewer.setExpandedState(entry, true); + for (ITimeGraphEntry child : entry.getChildren()) { + boolean expanded = fTreeViewer.getExpandedState(child); + fTimeGraphViewer.setExpandedState(child, expanded); + } List<TreeItem> treeItems = getVisibleExpandedItems(tree); if (treeItems.size() == 0) { return; } final TreeItem treeItem = treeItems.get(fTimeGraphViewer.getTopIndex()); // queue the top item update because the tree can change its top item // autonomously immediately after the listeners have been notified getDisplay().asyncExec(new Runnable() { @Override public void run() { tree.setTopItem(treeItem); }}); } }); // ensure synchronization of expanded items between tree and time graph fTimeGraphViewer.addTreeListener(new ITimeGraphTreeListener() { @Override public void treeCollapsed(TimeGraphTreeExpansionEvent event) { fTreeViewer.setExpandedState(event.getEntry(), false); } @Override public void treeExpanded(TimeGraphTreeExpansionEvent event) { - fTreeViewer.setExpandedState(event.getEntry(), true); + ITimeGraphEntry entry = event.getEntry(); + fTreeViewer.setExpandedState(entry, true); + for (ITimeGraphEntry child : entry.getChildren()) { + boolean expanded = fTreeViewer.getExpandedState(child); + fTimeGraphViewer.setExpandedState(child, expanded); + } } }); // prevent mouse button from selecting a filler tree item tree.addListener(SWT.MouseDown, new Listener() { @Override public void handleEvent(Event event) { TreeItem treeItem = tree.getItem(new Point(event.x, event.y)); if (treeItem == null || treeItem.getData() == FILLER) { event.doit = false; List<TreeItem> treeItems = getVisibleExpandedItems(tree); if (treeItems.size() == 0) { fTreeViewer.setSelection(new StructuredSelection()); fTimeGraphViewer.setSelection(null); return; } // this prevents from scrolling up when selecting // the partially visible tree item at the bottom tree.select(treeItems.get(treeItems.size() - 1)); fTreeViewer.setSelection(new StructuredSelection()); fTimeGraphViewer.setSelection(null); } } }); // prevent mouse wheel from scrolling down into filler tree items tree.addListener(SWT.MouseWheel, new Listener() { @Override public void handleEvent(Event event) { event.doit = false; Slider scrollBar = fTimeGraphViewer.getVerticalBar(); fTimeGraphViewer.setTopIndex(scrollBar.getSelection() - event.count); List<TreeItem> treeItems = getVisibleExpandedItems(tree); if (treeItems.size() == 0) { return; } TreeItem treeItem = treeItems.get(fTimeGraphViewer.getTopIndex()); tree.setTopItem(treeItem); } }); // prevent key stroke from selecting a filler tree item tree.addListener(SWT.KeyDown, new Listener() { @Override public void handleEvent(Event event) { List<TreeItem> treeItems = getVisibleExpandedItems(tree); if (treeItems.size() == 0) { fTreeViewer.setSelection(new StructuredSelection()); event.doit = false; return; } if (event.keyCode == SWT.ARROW_DOWN) { int index = Math.min(fTimeGraphViewer.getSelectionIndex() + 1, treeItems.size() - 1); fTimeGraphViewer.setSelection((ITimeGraphEntry) treeItems.get(index).getData()); event.doit = false; } else if (event.keyCode == SWT.PAGE_DOWN) { int height = tree.getSize().y - tree.getHeaderHeight() - tree.getHorizontalBar().getSize().y; int countPerPage = height / getItemHeight(tree); int index = Math.min(fTimeGraphViewer.getSelectionIndex() + countPerPage - 1, treeItems.size() - 1); fTimeGraphViewer.setSelection((ITimeGraphEntry) treeItems.get(index).getData()); event.doit = false; } else if (event.keyCode == SWT.END) { fTimeGraphViewer.setSelection((ITimeGraphEntry) treeItems.get(treeItems.size() - 1).getData()); event.doit = false; } TreeItem treeItem = treeItems.get(fTimeGraphViewer.getTopIndex()); tree.setTopItem(treeItem); if (fTimeGraphViewer.getSelectionIndex() >= 0) { fTreeViewer.setSelection(new StructuredSelection(fTimeGraphViewer.getSelection())); } else { fTreeViewer.setSelection(new StructuredSelection()); } } }); // ensure alignment of top item between tree and time graph fTimeGraphViewer.getTimeGraphControl().addControlListener(new ControlAdapter() { @Override public void controlResized(ControlEvent e) { List<TreeItem> treeItems = getVisibleExpandedItems(tree); if (treeItems.size() == 0) { return; } TreeItem treeItem = treeItems.get(fTimeGraphViewer.getTopIndex()); tree.setTopItem(treeItem); } }); // ensure synchronization of selected item between tree and time graph fTreeViewer.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent event) { if (fInhibitTreeSelection) { return; } if (event.getSelection() instanceof IStructuredSelection) { Object selection = ((IStructuredSelection) event.getSelection()).getFirstElement(); if (selection instanceof ITimeGraphEntry) { fTimeGraphViewer.setSelection((ITimeGraphEntry) selection); } List<TreeItem> treeItems = getVisibleExpandedItems(tree); if (treeItems.size() == 0) { return; } TreeItem treeItem = treeItems.get(fTimeGraphViewer.getTopIndex()); tree.setTopItem(treeItem); } } }); // ensure synchronization of selected item between tree and time graph fTimeGraphViewer.addSelectionListener(new ITimeGraphSelectionListener() { @Override public void selectionChanged(TimeGraphSelectionEvent event) { ITimeGraphEntry entry = fTimeGraphViewer.getSelection(); fInhibitTreeSelection = true; // block the tree selection changed listener if (entry != null) { StructuredSelection selection = new StructuredSelection(entry); fTreeViewer.setSelection(selection); } else { fTreeViewer.setSelection(new StructuredSelection()); } fInhibitTreeSelection = false; List<TreeItem> treeItems = getVisibleExpandedItems(tree); if (treeItems.size() == 0) { return; } TreeItem treeItem = treeItems.get(fTimeGraphViewer.getTopIndex()); tree.setTopItem(treeItem); } }); // ensure alignment of top item between tree and time graph fTimeGraphViewer.getVerticalBar().addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { List<TreeItem> treeItems = getVisibleExpandedItems(tree); if (treeItems.size() == 0) { return; } TreeItem treeItem = treeItems.get(fTimeGraphViewer.getTopIndex()); tree.setTopItem(treeItem); } }); // ensure alignment of top item between tree and time graph fTimeGraphViewer.getTimeGraphControl().addMouseWheelListener(new MouseWheelListener() { @Override public void mouseScrolled(MouseEvent e) { List<TreeItem> treeItems = getVisibleExpandedItems(tree); if (treeItems.size() == 0) { return; } TreeItem treeItem = treeItems.get(fTimeGraphViewer.getTopIndex()); tree.setTopItem(treeItem); } }); // ensure the tree has focus control when mouse is over it if the time graph had control fTreeViewer.getControl().addMouseTrackListener(new MouseTrackAdapter() { @Override public void mouseEnter(MouseEvent e) { if (fTimeGraphViewer.getTimeGraphControl().isFocusControl()) { fTreeViewer.getControl().setFocus(); } } }); // ensure the time graph has focus control when mouse is over it if the tree had control fTimeGraphViewer.getTimeGraphControl().addMouseTrackListener(new MouseTrackAdapter() { @Override public void mouseEnter(MouseEvent e) { if (fTreeViewer.getControl().isFocusControl()) { fTimeGraphViewer.getTimeGraphControl().setFocus(); } } }); fTimeGraphViewer.getTimeGraphScale().addMouseTrackListener(new MouseTrackAdapter() { @Override public void mouseEnter(MouseEvent e) { if (fTreeViewer.getControl().isFocusControl()) { fTimeGraphViewer.getTimeGraphControl().setFocus(); } } }); // The filler rows are required to ensure alignment when the tree does not have a // visible horizontal scroll bar. The tree does not allow its top item to be set // to a value that would cause blank space to be drawn at the bottom of the tree. fNumFillerRows = Display.getDefault().getBounds().height / getItemHeight(tree); sash.setWeights(new int[] { 1, 1 }); } // ------------------------------------------------------------------------ // Accessors // ------------------------------------------------------------------------ /** * Returns this time graph combo's tree viewer. * * @return the tree viewer */ public TreeViewer getTreeViewer() { return fTreeViewer; } /** * Returns this time graph combo's time graph viewer. * * @return the time graph viewer */ public TimeGraphViewer getTimeGraphViewer() { return fTimeGraphViewer; } /** * Callback for the show filter action * * @since 2.0 */ public void showFilterDialog() { if(fTopInput != null) { List<? extends ITimeGraphEntry> allElements = listAllInputs(fTopInput); fFilterDialog.setInput(fTopInput.toArray(new ITimeGraphEntry[0])); fFilterDialog.setTitle(Messages.TmfTimeFilterDialog_WINDOW_TITLE); fFilterDialog.setMessage(Messages.TmfTimeFilterDialog_MESSAGE); fFilterDialog.setExpandedElements(allElements.toArray()); if (fFilter.getFiltered() != null) { ArrayList<? extends ITimeGraphEntry> nonFilteredElements = new ArrayList<ITimeGraphEntry>(allElements); nonFilteredElements.removeAll(fFilter.getFiltered()); fFilterDialog.setInitialElementSelections(nonFilteredElements); } else { fFilterDialog.setInitialElementSelections(allElements); } fFilterDialog.create(); fFilterDialog.open(); // Process selected elements if (fFilterDialog.getResult() != null) { fInhibitTreeSelection = true; if (fFilterDialog.getResult().length != allElements.size()) { ArrayList<Object> filteredElements = new ArrayList<Object>(allElements); filteredElements.removeAll(Arrays.asList(fFilterDialog.getResult())); fFilter.setFiltered(filteredElements); } else { fFilter.setFiltered(null); } fTreeViewer.refresh(); fTreeViewer.expandAll(); fTimeGraphViewer.refresh(); fInhibitTreeSelection = false; // Reset selection to first entry if (fFilterDialog.getResult().length > 0) { setSelection((ITimeGraphEntry) fFilterDialog.getResult()[0]); } } } } /** * Get the show filter action. * * @return The Action object * @since 2.0 */ public Action getShowFilterAction() { if (showFilterAction == null) { // showFilter showFilterAction = new Action() { @Override public void run() { showFilterDialog(); } }; showFilterAction.setText(Messages.TmfTimeGraphCombo_FilterActionNameText); showFilterAction.setToolTipText(Messages.TmfTimeGraphCombo_FilterActionToolTipText); // TODO find a nice, distinctive icon showFilterAction.setImageDescriptor(Activator.getDefault().getImageDescripterFromPath(ITmfImageConstants.IMG_UI_FILTERS)); } return showFilterAction; } // ------------------------------------------------------------------------ // Control // ------------------------------------------------------------------------ @Override public void redraw() { fTimeGraphViewer.getControl().redraw(); super.redraw(); } // ------------------------------------------------------------------------ // Operations // ------------------------------------------------------------------------ /** * Sets the tree content provider used by this time graph combo. * * @param contentProvider the tree content provider */ public void setTreeContentProvider(ITreeContentProvider contentProvider) { fTreeViewer.setContentProvider(new TreeContentProviderWrapper(contentProvider)); } /** * Sets the tree label provider used by this time graph combo. * * @param labelProvider the tree label provider */ public void setTreeLabelProvider(ITableLabelProvider labelProvider) { fTreeViewer.setLabelProvider(new TreeLabelProviderWrapper(labelProvider)); } /** * Sets the tree content provider used by the filter dialog * * @param contentProvider the tree content provider * @since 2.0 */ public void setFilterContentProvider(ITreeContentProvider contentProvider) { fFilterDialog.setContentProvider(contentProvider); } /** * Sets the tree label provider used by the filter dialog * * @param labelProvider the tree label provider * @since 2.0 */ public void setFilterLabelProvider(ITableLabelProvider labelProvider) { fFilterDialog.setLabelProvider(labelProvider); } /** * Sets the tree columns for this time graph combo. * * @param columnNames the tree column names */ public void setTreeColumns(String[] columnNames) { final Tree tree = fTreeViewer.getTree(); for (String columnName : columnNames) { TreeColumn column = new TreeColumn(tree, SWT.LEFT); column.setText(columnName); column.pack(); } } /** * Sets the tree columns for this time graph combo's filter dialog. * * @param columnNames the tree column names * @since 2.0 */ public void setFilterColumns(String[] columnNames) { fFilterDialog.setColumnNames(columnNames); } /** * Sets the time graph provider used by this time graph combo. * * @param timeGraphProvider the time graph provider */ public void setTimeGraphProvider(ITimeGraphPresentationProvider timeGraphProvider) { fTimeGraphViewer.setTimeGraphProvider(timeGraphProvider); } /** * Sets or clears the input for this time graph combo. * The input array should only contain top-level elements. * * @param input the input of this time graph combo, or <code>null</code> if none */ public void setInput(ITimeGraphEntry[] input) { fTopInput = new ArrayList<ITimeGraphEntry>(Arrays.asList(input)); fFilter.setFiltered(null); fInhibitTreeSelection = true; fTreeViewer.setInput(input); for (SelectionListenerWrapper listenerWrapper : fSelectionListenerMap.values()) { listenerWrapper.selection = null; } fInhibitTreeSelection = false; fTreeViewer.expandAll(); fTreeViewer.getTree().getVerticalBar().setEnabled(false); fTreeViewer.getTree().getVerticalBar().setVisible(false); fTimeGraphViewer.setItemHeight(getItemHeight(fTreeViewer.getTree())); fTimeGraphViewer.setInput(input); } /** * @param filter The filter object to be attached to the view * @since 2.0 */ public void addFilter(ViewerFilter filter) { ViewerFilter wrapper = new ViewerFilterWrapper(filter); fTreeViewer.addFilter(wrapper); fTimeGraphViewer.addFilter(wrapper); fViewerFilterMap.put(filter, wrapper); } /** * @param filter The filter object to be removed from the view * @since 2.0 */ public void removeFilter(ViewerFilter filter) { ViewerFilter wrapper = fViewerFilterMap.get(filter); fTreeViewer.removeFilter(wrapper); fTimeGraphViewer.removeFilter(wrapper); fViewerFilterMap.remove(filter); } /** * Refreshes this time graph completely with information freshly obtained from its model. */ public void refresh() { fInhibitTreeSelection = true; fTreeViewer.refresh(); fTimeGraphViewer.refresh(); fInhibitTreeSelection = false; } /** * Adds a listener for selection changes in this time graph combo. * * @param listener a selection listener */ public void addSelectionListener(ITimeGraphSelectionListener listener) { SelectionListenerWrapper listenerWrapper = new SelectionListenerWrapper(listener); fTreeViewer.addSelectionChangedListener(listenerWrapper); fSelectionListenerMap.put(listener, listenerWrapper); fTimeGraphViewer.addSelectionListener(listenerWrapper); } /** * Removes the given selection listener from this time graph combo. * * @param listener a selection changed listener */ public void removeSelectionListener(ITimeGraphSelectionListener listener) { SelectionListenerWrapper listenerWrapper = fSelectionListenerMap.remove(listener); fTreeViewer.removeSelectionChangedListener(listenerWrapper); fTimeGraphViewer.removeSelectionListener(listenerWrapper); } /** * Sets the current selection for this time graph combo. * * @param selection the new selection */ public void setSelection(ITimeGraphEntry selection) { fTimeGraphViewer.setSelection(selection); fInhibitTreeSelection = true; // block the tree selection changed listener if (selection != null) { StructuredSelection structuredSelection = new StructuredSelection(selection); fTreeViewer.setSelection(structuredSelection); } else { fTreeViewer.setSelection(new StructuredSelection()); } fInhibitTreeSelection = false; List<TreeItem> treeItems = getVisibleExpandedItems(fTreeViewer.getTree()); if (treeItems.size() == 0) { return; } TreeItem treeItem = treeItems.get(fTimeGraphViewer.getTopIndex()); fTreeViewer.getTree().setTopItem(treeItem); } /** * Set the expanded state of an entry * * @param entry * The entry to expand/collapse * @param expanded * True for expanded, false for collapsed * * @since 2.0 */ public void setExpandedState(ITimeGraphEntry entry, boolean expanded) { fTimeGraphViewer.setExpandedState(entry, expanded); fTreeViewer.setExpandedState(entry, expanded); } /** * Collapses all nodes of the viewer's tree, starting with the root. * * @since 2.0 */ public void collapseAll() { fTimeGraphViewer.collapseAll(); fTreeViewer.collapseAll(); } /** * Expands all nodes of the viewer's tree, starting with the root. * * @since 2.0 */ public void expandAll() { fTimeGraphViewer.expandAll(); fTreeViewer.expandAll(); } // ------------------------------------------------------------------------ // Internal // ------------------------------------------------------------------------ private List<TreeItem> getVisibleExpandedItems(Tree tree) { ArrayList<TreeItem> items = new ArrayList<TreeItem>(); for (TreeItem item : tree.getItems()) { if (item.getData() == FILLER) { break; } items.add(item); if (item.getExpanded()) { items.addAll(getVisibleExpandedItems(item)); } } return items; } private List<TreeItem> getVisibleExpandedItems(TreeItem treeItem) { ArrayList<TreeItem> items = new ArrayList<TreeItem>(); for (TreeItem item : treeItem.getItems()) { items.add(item); if (item.getExpanded()) { items.addAll(getVisibleExpandedItems(item)); } } return items; } /** * Explores the list of top-level inputs and returns all the inputs * * @param inputs The top-level inputs * @return All the inputs */ private List<? extends ITimeGraphEntry> listAllInputs(List<? extends ITimeGraphEntry> inputs) { ArrayList<ITimeGraphEntry> items = new ArrayList<ITimeGraphEntry>(); for (ITimeGraphEntry entry : inputs) { items.add(entry); if (entry.hasChildren()) { items.addAll(listAllInputs(entry.getChildren())); } } return items; } private int getItemHeight(final Tree tree) { /* * Bug in Linux. The method getItemHeight doesn't always return the correct value. */ if (fLinuxItemHeight >= 0 && System.getProperty("os.name").contains("Linux")) { //$NON-NLS-1$ //$NON-NLS-2$ if (fLinuxItemHeight != 0) { return fLinuxItemHeight; } List<TreeItem> treeItems = getVisibleExpandedItems(tree); if (treeItems.size() > 1) { final TreeItem treeItem0 = treeItems.get(0); final TreeItem treeItem1 = treeItems.get(1); PaintListener paintListener = new PaintListener() { @Override public void paintControl(PaintEvent e) { tree.removePaintListener(this); int y0 = treeItem0.getBounds().y; int y1 = treeItem1.getBounds().y; int itemHeight = y1 - y0; if (itemHeight > 0) { fLinuxItemHeight = itemHeight; fTimeGraphViewer.setItemHeight(itemHeight); } } }; tree.addPaintListener(paintListener); } } else { fLinuxItemHeight = -1; // Not Linux, don't perform os.name check anymore } return tree.getItemHeight(); } }
false
true
public TimeGraphCombo(Composite parent, int style) { super(parent, style); setLayout(new FillLayout()); final SashForm sash = new SashForm(this, SWT.NONE); fTreeViewer = new TreeViewer(sash, SWT.FULL_SELECTION | SWT.H_SCROLL); final Tree tree = fTreeViewer.getTree(); tree.setHeaderVisible(true); tree.setLinesVisible(true); fTimeGraphViewer = new TimeGraphViewer(sash, SWT.NONE); fTimeGraphViewer.setItemHeight(getItemHeight(tree)); fTimeGraphViewer.setHeaderHeight(tree.getHeaderHeight()); fTimeGraphViewer.setBorderWidth(tree.getBorderWidth()); fTimeGraphViewer.setNameWidthPref(0); fFilter = new RawViewerFilter(); addFilter(fFilter); fFilterDialog = new TimeGraphFilterDialog(getShell()); // Feature in Windows. The tree vertical bar reappears when // the control is resized so we need to hide it again. // Bug in Linux. The tree header height is 0 in constructor, // so we need to reset it later when the control is resized. tree.addControlListener(new ControlAdapter() { private int depth = 0; @Override public void controlResized(ControlEvent e) { if (depth == 0) { depth++; tree.getVerticalBar().setEnabled(false); // this can trigger controlResized recursively tree.getVerticalBar().setVisible(false); depth--; } fTimeGraphViewer.setHeaderHeight(tree.getHeaderHeight()); } }); // ensure synchronization of expanded items between tree and time graph fTreeViewer.addTreeListener(new ITreeViewerListener() { @Override public void treeCollapsed(TreeExpansionEvent event) { fTimeGraphViewer.setExpandedState((ITimeGraphEntry) event.getElement(), false); List<TreeItem> treeItems = getVisibleExpandedItems(tree); if (treeItems.size() == 0) { return; } TreeItem treeItem = treeItems.get(fTimeGraphViewer.getTopIndex()); tree.setTopItem(treeItem); } @Override public void treeExpanded(TreeExpansionEvent event) { fTimeGraphViewer.setExpandedState((ITimeGraphEntry) event.getElement(), true); List<TreeItem> treeItems = getVisibleExpandedItems(tree); if (treeItems.size() == 0) { return; } final TreeItem treeItem = treeItems.get(fTimeGraphViewer.getTopIndex()); // queue the top item update because the tree can change its top item // autonomously immediately after the listeners have been notified getDisplay().asyncExec(new Runnable() { @Override public void run() { tree.setTopItem(treeItem); }}); } }); // ensure synchronization of expanded items between tree and time graph fTimeGraphViewer.addTreeListener(new ITimeGraphTreeListener() { @Override public void treeCollapsed(TimeGraphTreeExpansionEvent event) { fTreeViewer.setExpandedState(event.getEntry(), false); } @Override public void treeExpanded(TimeGraphTreeExpansionEvent event) { fTreeViewer.setExpandedState(event.getEntry(), true); } }); // prevent mouse button from selecting a filler tree item tree.addListener(SWT.MouseDown, new Listener() { @Override public void handleEvent(Event event) { TreeItem treeItem = tree.getItem(new Point(event.x, event.y)); if (treeItem == null || treeItem.getData() == FILLER) { event.doit = false; List<TreeItem> treeItems = getVisibleExpandedItems(tree); if (treeItems.size() == 0) { fTreeViewer.setSelection(new StructuredSelection()); fTimeGraphViewer.setSelection(null); return; } // this prevents from scrolling up when selecting // the partially visible tree item at the bottom tree.select(treeItems.get(treeItems.size() - 1)); fTreeViewer.setSelection(new StructuredSelection()); fTimeGraphViewer.setSelection(null); } } }); // prevent mouse wheel from scrolling down into filler tree items tree.addListener(SWT.MouseWheel, new Listener() { @Override public void handleEvent(Event event) { event.doit = false; Slider scrollBar = fTimeGraphViewer.getVerticalBar(); fTimeGraphViewer.setTopIndex(scrollBar.getSelection() - event.count); List<TreeItem> treeItems = getVisibleExpandedItems(tree); if (treeItems.size() == 0) { return; } TreeItem treeItem = treeItems.get(fTimeGraphViewer.getTopIndex()); tree.setTopItem(treeItem); } }); // prevent key stroke from selecting a filler tree item tree.addListener(SWT.KeyDown, new Listener() { @Override public void handleEvent(Event event) { List<TreeItem> treeItems = getVisibleExpandedItems(tree); if (treeItems.size() == 0) { fTreeViewer.setSelection(new StructuredSelection()); event.doit = false; return; } if (event.keyCode == SWT.ARROW_DOWN) { int index = Math.min(fTimeGraphViewer.getSelectionIndex() + 1, treeItems.size() - 1); fTimeGraphViewer.setSelection((ITimeGraphEntry) treeItems.get(index).getData()); event.doit = false; } else if (event.keyCode == SWT.PAGE_DOWN) { int height = tree.getSize().y - tree.getHeaderHeight() - tree.getHorizontalBar().getSize().y; int countPerPage = height / getItemHeight(tree); int index = Math.min(fTimeGraphViewer.getSelectionIndex() + countPerPage - 1, treeItems.size() - 1); fTimeGraphViewer.setSelection((ITimeGraphEntry) treeItems.get(index).getData()); event.doit = false; } else if (event.keyCode == SWT.END) { fTimeGraphViewer.setSelection((ITimeGraphEntry) treeItems.get(treeItems.size() - 1).getData()); event.doit = false; } TreeItem treeItem = treeItems.get(fTimeGraphViewer.getTopIndex()); tree.setTopItem(treeItem); if (fTimeGraphViewer.getSelectionIndex() >= 0) { fTreeViewer.setSelection(new StructuredSelection(fTimeGraphViewer.getSelection())); } else { fTreeViewer.setSelection(new StructuredSelection()); } } }); // ensure alignment of top item between tree and time graph fTimeGraphViewer.getTimeGraphControl().addControlListener(new ControlAdapter() { @Override public void controlResized(ControlEvent e) { List<TreeItem> treeItems = getVisibleExpandedItems(tree); if (treeItems.size() == 0) { return; } TreeItem treeItem = treeItems.get(fTimeGraphViewer.getTopIndex()); tree.setTopItem(treeItem); } }); // ensure synchronization of selected item between tree and time graph fTreeViewer.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent event) { if (fInhibitTreeSelection) { return; } if (event.getSelection() instanceof IStructuredSelection) { Object selection = ((IStructuredSelection) event.getSelection()).getFirstElement(); if (selection instanceof ITimeGraphEntry) { fTimeGraphViewer.setSelection((ITimeGraphEntry) selection); } List<TreeItem> treeItems = getVisibleExpandedItems(tree); if (treeItems.size() == 0) { return; } TreeItem treeItem = treeItems.get(fTimeGraphViewer.getTopIndex()); tree.setTopItem(treeItem); } } }); // ensure synchronization of selected item between tree and time graph fTimeGraphViewer.addSelectionListener(new ITimeGraphSelectionListener() { @Override public void selectionChanged(TimeGraphSelectionEvent event) { ITimeGraphEntry entry = fTimeGraphViewer.getSelection(); fInhibitTreeSelection = true; // block the tree selection changed listener if (entry != null) { StructuredSelection selection = new StructuredSelection(entry); fTreeViewer.setSelection(selection); } else { fTreeViewer.setSelection(new StructuredSelection()); } fInhibitTreeSelection = false; List<TreeItem> treeItems = getVisibleExpandedItems(tree); if (treeItems.size() == 0) { return; } TreeItem treeItem = treeItems.get(fTimeGraphViewer.getTopIndex()); tree.setTopItem(treeItem); } }); // ensure alignment of top item between tree and time graph fTimeGraphViewer.getVerticalBar().addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { List<TreeItem> treeItems = getVisibleExpandedItems(tree); if (treeItems.size() == 0) { return; } TreeItem treeItem = treeItems.get(fTimeGraphViewer.getTopIndex()); tree.setTopItem(treeItem); } }); // ensure alignment of top item between tree and time graph fTimeGraphViewer.getTimeGraphControl().addMouseWheelListener(new MouseWheelListener() { @Override public void mouseScrolled(MouseEvent e) { List<TreeItem> treeItems = getVisibleExpandedItems(tree); if (treeItems.size() == 0) { return; } TreeItem treeItem = treeItems.get(fTimeGraphViewer.getTopIndex()); tree.setTopItem(treeItem); } }); // ensure the tree has focus control when mouse is over it if the time graph had control fTreeViewer.getControl().addMouseTrackListener(new MouseTrackAdapter() { @Override public void mouseEnter(MouseEvent e) { if (fTimeGraphViewer.getTimeGraphControl().isFocusControl()) { fTreeViewer.getControl().setFocus(); } } }); // ensure the time graph has focus control when mouse is over it if the tree had control fTimeGraphViewer.getTimeGraphControl().addMouseTrackListener(new MouseTrackAdapter() { @Override public void mouseEnter(MouseEvent e) { if (fTreeViewer.getControl().isFocusControl()) { fTimeGraphViewer.getTimeGraphControl().setFocus(); } } }); fTimeGraphViewer.getTimeGraphScale().addMouseTrackListener(new MouseTrackAdapter() { @Override public void mouseEnter(MouseEvent e) { if (fTreeViewer.getControl().isFocusControl()) { fTimeGraphViewer.getTimeGraphControl().setFocus(); } } }); // The filler rows are required to ensure alignment when the tree does not have a // visible horizontal scroll bar. The tree does not allow its top item to be set // to a value that would cause blank space to be drawn at the bottom of the tree. fNumFillerRows = Display.getDefault().getBounds().height / getItemHeight(tree); sash.setWeights(new int[] { 1, 1 }); }
public TimeGraphCombo(Composite parent, int style) { super(parent, style); setLayout(new FillLayout()); final SashForm sash = new SashForm(this, SWT.NONE); fTreeViewer = new TreeViewer(sash, SWT.FULL_SELECTION | SWT.H_SCROLL); final Tree tree = fTreeViewer.getTree(); tree.setHeaderVisible(true); tree.setLinesVisible(true); fTimeGraphViewer = new TimeGraphViewer(sash, SWT.NONE); fTimeGraphViewer.setItemHeight(getItemHeight(tree)); fTimeGraphViewer.setHeaderHeight(tree.getHeaderHeight()); fTimeGraphViewer.setBorderWidth(tree.getBorderWidth()); fTimeGraphViewer.setNameWidthPref(0); fFilter = new RawViewerFilter(); addFilter(fFilter); fFilterDialog = new TimeGraphFilterDialog(getShell()); // Feature in Windows. The tree vertical bar reappears when // the control is resized so we need to hide it again. // Bug in Linux. The tree header height is 0 in constructor, // so we need to reset it later when the control is resized. tree.addControlListener(new ControlAdapter() { private int depth = 0; @Override public void controlResized(ControlEvent e) { if (depth == 0) { depth++; tree.getVerticalBar().setEnabled(false); // this can trigger controlResized recursively tree.getVerticalBar().setVisible(false); depth--; } fTimeGraphViewer.setHeaderHeight(tree.getHeaderHeight()); } }); // ensure synchronization of expanded items between tree and time graph fTreeViewer.addTreeListener(new ITreeViewerListener() { @Override public void treeCollapsed(TreeExpansionEvent event) { fTimeGraphViewer.setExpandedState((ITimeGraphEntry) event.getElement(), false); List<TreeItem> treeItems = getVisibleExpandedItems(tree); if (treeItems.size() == 0) { return; } TreeItem treeItem = treeItems.get(fTimeGraphViewer.getTopIndex()); tree.setTopItem(treeItem); } @Override public void treeExpanded(TreeExpansionEvent event) { ITimeGraphEntry entry = (ITimeGraphEntry) event.getElement(); fTimeGraphViewer.setExpandedState(entry, true); for (ITimeGraphEntry child : entry.getChildren()) { boolean expanded = fTreeViewer.getExpandedState(child); fTimeGraphViewer.setExpandedState(child, expanded); } List<TreeItem> treeItems = getVisibleExpandedItems(tree); if (treeItems.size() == 0) { return; } final TreeItem treeItem = treeItems.get(fTimeGraphViewer.getTopIndex()); // queue the top item update because the tree can change its top item // autonomously immediately after the listeners have been notified getDisplay().asyncExec(new Runnable() { @Override public void run() { tree.setTopItem(treeItem); }}); } }); // ensure synchronization of expanded items between tree and time graph fTimeGraphViewer.addTreeListener(new ITimeGraphTreeListener() { @Override public void treeCollapsed(TimeGraphTreeExpansionEvent event) { fTreeViewer.setExpandedState(event.getEntry(), false); } @Override public void treeExpanded(TimeGraphTreeExpansionEvent event) { ITimeGraphEntry entry = event.getEntry(); fTreeViewer.setExpandedState(entry, true); for (ITimeGraphEntry child : entry.getChildren()) { boolean expanded = fTreeViewer.getExpandedState(child); fTimeGraphViewer.setExpandedState(child, expanded); } } }); // prevent mouse button from selecting a filler tree item tree.addListener(SWT.MouseDown, new Listener() { @Override public void handleEvent(Event event) { TreeItem treeItem = tree.getItem(new Point(event.x, event.y)); if (treeItem == null || treeItem.getData() == FILLER) { event.doit = false; List<TreeItem> treeItems = getVisibleExpandedItems(tree); if (treeItems.size() == 0) { fTreeViewer.setSelection(new StructuredSelection()); fTimeGraphViewer.setSelection(null); return; } // this prevents from scrolling up when selecting // the partially visible tree item at the bottom tree.select(treeItems.get(treeItems.size() - 1)); fTreeViewer.setSelection(new StructuredSelection()); fTimeGraphViewer.setSelection(null); } } }); // prevent mouse wheel from scrolling down into filler tree items tree.addListener(SWT.MouseWheel, new Listener() { @Override public void handleEvent(Event event) { event.doit = false; Slider scrollBar = fTimeGraphViewer.getVerticalBar(); fTimeGraphViewer.setTopIndex(scrollBar.getSelection() - event.count); List<TreeItem> treeItems = getVisibleExpandedItems(tree); if (treeItems.size() == 0) { return; } TreeItem treeItem = treeItems.get(fTimeGraphViewer.getTopIndex()); tree.setTopItem(treeItem); } }); // prevent key stroke from selecting a filler tree item tree.addListener(SWT.KeyDown, new Listener() { @Override public void handleEvent(Event event) { List<TreeItem> treeItems = getVisibleExpandedItems(tree); if (treeItems.size() == 0) { fTreeViewer.setSelection(new StructuredSelection()); event.doit = false; return; } if (event.keyCode == SWT.ARROW_DOWN) { int index = Math.min(fTimeGraphViewer.getSelectionIndex() + 1, treeItems.size() - 1); fTimeGraphViewer.setSelection((ITimeGraphEntry) treeItems.get(index).getData()); event.doit = false; } else if (event.keyCode == SWT.PAGE_DOWN) { int height = tree.getSize().y - tree.getHeaderHeight() - tree.getHorizontalBar().getSize().y; int countPerPage = height / getItemHeight(tree); int index = Math.min(fTimeGraphViewer.getSelectionIndex() + countPerPage - 1, treeItems.size() - 1); fTimeGraphViewer.setSelection((ITimeGraphEntry) treeItems.get(index).getData()); event.doit = false; } else if (event.keyCode == SWT.END) { fTimeGraphViewer.setSelection((ITimeGraphEntry) treeItems.get(treeItems.size() - 1).getData()); event.doit = false; } TreeItem treeItem = treeItems.get(fTimeGraphViewer.getTopIndex()); tree.setTopItem(treeItem); if (fTimeGraphViewer.getSelectionIndex() >= 0) { fTreeViewer.setSelection(new StructuredSelection(fTimeGraphViewer.getSelection())); } else { fTreeViewer.setSelection(new StructuredSelection()); } } }); // ensure alignment of top item between tree and time graph fTimeGraphViewer.getTimeGraphControl().addControlListener(new ControlAdapter() { @Override public void controlResized(ControlEvent e) { List<TreeItem> treeItems = getVisibleExpandedItems(tree); if (treeItems.size() == 0) { return; } TreeItem treeItem = treeItems.get(fTimeGraphViewer.getTopIndex()); tree.setTopItem(treeItem); } }); // ensure synchronization of selected item between tree and time graph fTreeViewer.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent event) { if (fInhibitTreeSelection) { return; } if (event.getSelection() instanceof IStructuredSelection) { Object selection = ((IStructuredSelection) event.getSelection()).getFirstElement(); if (selection instanceof ITimeGraphEntry) { fTimeGraphViewer.setSelection((ITimeGraphEntry) selection); } List<TreeItem> treeItems = getVisibleExpandedItems(tree); if (treeItems.size() == 0) { return; } TreeItem treeItem = treeItems.get(fTimeGraphViewer.getTopIndex()); tree.setTopItem(treeItem); } } }); // ensure synchronization of selected item between tree and time graph fTimeGraphViewer.addSelectionListener(new ITimeGraphSelectionListener() { @Override public void selectionChanged(TimeGraphSelectionEvent event) { ITimeGraphEntry entry = fTimeGraphViewer.getSelection(); fInhibitTreeSelection = true; // block the tree selection changed listener if (entry != null) { StructuredSelection selection = new StructuredSelection(entry); fTreeViewer.setSelection(selection); } else { fTreeViewer.setSelection(new StructuredSelection()); } fInhibitTreeSelection = false; List<TreeItem> treeItems = getVisibleExpandedItems(tree); if (treeItems.size() == 0) { return; } TreeItem treeItem = treeItems.get(fTimeGraphViewer.getTopIndex()); tree.setTopItem(treeItem); } }); // ensure alignment of top item between tree and time graph fTimeGraphViewer.getVerticalBar().addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { List<TreeItem> treeItems = getVisibleExpandedItems(tree); if (treeItems.size() == 0) { return; } TreeItem treeItem = treeItems.get(fTimeGraphViewer.getTopIndex()); tree.setTopItem(treeItem); } }); // ensure alignment of top item between tree and time graph fTimeGraphViewer.getTimeGraphControl().addMouseWheelListener(new MouseWheelListener() { @Override public void mouseScrolled(MouseEvent e) { List<TreeItem> treeItems = getVisibleExpandedItems(tree); if (treeItems.size() == 0) { return; } TreeItem treeItem = treeItems.get(fTimeGraphViewer.getTopIndex()); tree.setTopItem(treeItem); } }); // ensure the tree has focus control when mouse is over it if the time graph had control fTreeViewer.getControl().addMouseTrackListener(new MouseTrackAdapter() { @Override public void mouseEnter(MouseEvent e) { if (fTimeGraphViewer.getTimeGraphControl().isFocusControl()) { fTreeViewer.getControl().setFocus(); } } }); // ensure the time graph has focus control when mouse is over it if the tree had control fTimeGraphViewer.getTimeGraphControl().addMouseTrackListener(new MouseTrackAdapter() { @Override public void mouseEnter(MouseEvent e) { if (fTreeViewer.getControl().isFocusControl()) { fTimeGraphViewer.getTimeGraphControl().setFocus(); } } }); fTimeGraphViewer.getTimeGraphScale().addMouseTrackListener(new MouseTrackAdapter() { @Override public void mouseEnter(MouseEvent e) { if (fTreeViewer.getControl().isFocusControl()) { fTimeGraphViewer.getTimeGraphControl().setFocus(); } } }); // The filler rows are required to ensure alignment when the tree does not have a // visible horizontal scroll bar. The tree does not allow its top item to be set // to a value that would cause blank space to be drawn at the bottom of the tree. fNumFillerRows = Display.getDefault().getBounds().height / getItemHeight(tree); sash.setWeights(new int[] { 1, 1 }); }
diff --git a/newsletter-core/src/main/java/com/rcs/newsletter/core/service/NewsletterMailingServiceImpl.java b/newsletter-core/src/main/java/com/rcs/newsletter/core/service/NewsletterMailingServiceImpl.java index c40743b..367ce6b 100644 --- a/newsletter-core/src/main/java/com/rcs/newsletter/core/service/NewsletterMailingServiceImpl.java +++ b/newsletter-core/src/main/java/com/rcs/newsletter/core/service/NewsletterMailingServiceImpl.java @@ -1,151 +1,151 @@ package com.rcs.newsletter.core.service; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.exception.SystemException; import com.liferay.portal.kernel.mail.MailMessage; import com.liferay.portal.theme.ThemeDisplay; import com.rcs.newsletter.core.model.NewsletterMailing; import com.rcs.newsletter.core.model.NewsletterSubscription; import com.rcs.newsletter.core.model.NewsletterSubscriptor; import com.rcs.newsletter.core.model.enums.SubscriptionStatus; import com.rcs.newsletter.core.service.util.LiferayMailingUtil; import com.rcs.newsletter.core.service.util.EmailFormat; import java.util.logging.Level; import java.util.logging.Logger; import javax.mail.internet.InternetAddress; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import static com.rcs.newsletter.NewsletterConstants.*; /** * * @author juan */ @Service @Transactional class NewsletterMailingServiceImpl extends CRUDServiceImpl<NewsletterMailing> implements NewsletterMailingService { private static Log logger = LogFactoryUtil.getLog(NewsletterMailingServiceImpl.class); @Autowired private LiferayMailingUtil mailingUtil; @Value("${newsletter.mail.from}") private String fromEmailAddress; @Value("${newsletter.admin.name}") private String fromName; @Async @Override public void sendTestMailing(Long mailingId, String testEmail, ThemeDisplay themeDisplay) { try { NewsletterMailing mailing = findById(mailingId).getPayload(); String content = EmailFormat.getEmailFromTemplate(mailing, themeDisplay); content = content.replace(LIST_NAME_TOKEN, mailing.getName()); //Add full path to images content = EmailFormat.fixImagesPath(content, themeDisplay); //Replace User Info content = EmailFormat.replaceUserInfo(content, null, themeDisplay); String title = mailing.getName(); InternetAddress fromIA = new InternetAddress(mailing.getList().getFromEmail()); InternetAddress toIA = new InternetAddress(testEmail); MailMessage message = EmailFormat.getMailMessageWithAttachedImages(fromIA, toIA, title, content); mailingUtil.sendEmail(message); //mailingUtil.sendArticleByEmail(mailing.getArticleId(), themeDisplay, testEmail, fromEmailAddress); } catch (PortalException ex) { logger.error("Error while trying to read article", ex); } catch (SystemException ex) { logger.error("Error while trying to read article", ex); } catch (Exception ex) { logger.error("Error while trying to read article", ex); } } @Async @Override public void sendMailing(Long mailingId, ThemeDisplay themeDisplay, Long archiveId) { try { NewsletterMailing mailing = findById(mailingId).getPayload(); String content = EmailFormat.getEmailFromTemplate(mailing, themeDisplay); //Add full path to images content = EmailFormat.fixImagesPath(content, themeDisplay); String title = mailing.getName(); - InternetAddress fromIA = new InternetAddress(fromEmailAddress, fromName); + InternetAddress fromIA = new InternetAddress(mailing.getList().getFromEmail(), fromName); InternetAddress toIA = new InternetAddress(); MailMessage message = EmailFormat.getMailMessageWithAttachedImages(fromIA, toIA, title, content); String bodyContent = message.getBody(); for (NewsletterSubscription newsletterSubscription : mailing.getList().getSubscriptions()) { if(newsletterSubscription.getStatus().equals(SubscriptionStatus.ACTIVE)) { NewsletterSubscriptor subscriptor = newsletterSubscription.getSubscriptor(); String name = subscriptor.getFirstName() + " " + subscriptor.getLastName(); MailMessage personalMessage = message; toIA = new InternetAddress(subscriptor.getEmail(), name); logger.error("Sending to " + name + "<" + subscriptor.getEmail() + ">"); personalMessage.setTo(toIA); //Replace User Info String tmpContent = EmailFormat.replaceUserInfo(bodyContent, newsletterSubscription, themeDisplay, archiveId); personalMessage.setBody(tmpContent); mailingUtil.sendEmail(personalMessage); } } logger.error("End Sending personalizable conent"); } catch (Exception ex) { logger.error("Error while trying to read article", ex); } } /** * * @param mailingId * @param themeDisplay * @return */ @Override public String getEmailFromTemplate(Long mailingId, ThemeDisplay themeDisplay){ String content = ""; try { NewsletterMailing mailing = findById(mailingId).getPayload(); content = EmailFormat.getEmailFromTemplate(mailing, themeDisplay); } catch (Exception ex) { Logger.getLogger(NewsletterMailingServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } return content; } /** * Validates the template format * @param mailingId * @return */ @Override public boolean validateTemplateFormat(Long mailingId) { boolean result = true; NewsletterMailing mailing = findById(mailingId).getPayload(); String templateContent = mailing.getTemplate().getTemplate(); String content = EmailFormat.validateTemplateFormat(templateContent); if (content == null || content.isEmpty()) { result = false; } return result; } }
true
true
public void sendMailing(Long mailingId, ThemeDisplay themeDisplay, Long archiveId) { try { NewsletterMailing mailing = findById(mailingId).getPayload(); String content = EmailFormat.getEmailFromTemplate(mailing, themeDisplay); //Add full path to images content = EmailFormat.fixImagesPath(content, themeDisplay); String title = mailing.getName(); InternetAddress fromIA = new InternetAddress(fromEmailAddress, fromName); InternetAddress toIA = new InternetAddress(); MailMessage message = EmailFormat.getMailMessageWithAttachedImages(fromIA, toIA, title, content); String bodyContent = message.getBody(); for (NewsletterSubscription newsletterSubscription : mailing.getList().getSubscriptions()) { if(newsletterSubscription.getStatus().equals(SubscriptionStatus.ACTIVE)) { NewsletterSubscriptor subscriptor = newsletterSubscription.getSubscriptor(); String name = subscriptor.getFirstName() + " " + subscriptor.getLastName(); MailMessage personalMessage = message; toIA = new InternetAddress(subscriptor.getEmail(), name); logger.error("Sending to " + name + "<" + subscriptor.getEmail() + ">"); personalMessage.setTo(toIA); //Replace User Info String tmpContent = EmailFormat.replaceUserInfo(bodyContent, newsletterSubscription, themeDisplay, archiveId); personalMessage.setBody(tmpContent); mailingUtil.sendEmail(personalMessage); } } logger.error("End Sending personalizable conent"); } catch (Exception ex) { logger.error("Error while trying to read article", ex); } }
public void sendMailing(Long mailingId, ThemeDisplay themeDisplay, Long archiveId) { try { NewsletterMailing mailing = findById(mailingId).getPayload(); String content = EmailFormat.getEmailFromTemplate(mailing, themeDisplay); //Add full path to images content = EmailFormat.fixImagesPath(content, themeDisplay); String title = mailing.getName(); InternetAddress fromIA = new InternetAddress(mailing.getList().getFromEmail(), fromName); InternetAddress toIA = new InternetAddress(); MailMessage message = EmailFormat.getMailMessageWithAttachedImages(fromIA, toIA, title, content); String bodyContent = message.getBody(); for (NewsletterSubscription newsletterSubscription : mailing.getList().getSubscriptions()) { if(newsletterSubscription.getStatus().equals(SubscriptionStatus.ACTIVE)) { NewsletterSubscriptor subscriptor = newsletterSubscription.getSubscriptor(); String name = subscriptor.getFirstName() + " " + subscriptor.getLastName(); MailMessage personalMessage = message; toIA = new InternetAddress(subscriptor.getEmail(), name); logger.error("Sending to " + name + "<" + subscriptor.getEmail() + ">"); personalMessage.setTo(toIA); //Replace User Info String tmpContent = EmailFormat.replaceUserInfo(bodyContent, newsletterSubscription, themeDisplay, archiveId); personalMessage.setBody(tmpContent); mailingUtil.sendEmail(personalMessage); } } logger.error("End Sending personalizable conent"); } catch (Exception ex) { logger.error("Error while trying to read article", ex); } }
diff --git a/src/de/typology/predictors/GLMMySQLSearcher.java b/src/de/typology/predictors/GLMMySQLSearcher.java index 99b2af43..c8222579 100755 --- a/src/de/typology/predictors/GLMMySQLSearcher.java +++ b/src/de/typology/predictors/GLMMySQLSearcher.java @@ -1,124 +1,123 @@ package de.typology.predictors; import de.typology.splitter.BinarySearch; import de.typology.splitter.IndexBuilder; import de.typology.utils.Config; import de.typology.utils.IOHelper; public class GLMMySQLSearcher extends NewMySQLSearcher { /** * @param args */ public static void main(String[] args) { IndexBuilder ib = new IndexBuilder(); String databaseName = Config.get().trainedOnDataSet + "_" + Config.get().trainedOnLang; String indexPath = Config.get().outputDirectory + "/" + Config.get().trainedOnDataSet + "/" + Config.get().trainedOnLang + "/index.txt"; String[] wordIndex = ib.deserializeIndex(indexPath); // k is used in prepareQuery int k = 2; GLMMySQLSearcher glmmss = new GLMMySQLSearcher(databaseName, k); // Config.get().weight = "no"; // for (int i = 5; i > 1; i--) { // IOHelper.strongLog("google ngrams tested on wiki typology model parameter: " // + i); // tmss.run(i, 100000, Config.get().weight); // } // Config.get().weight = "pic"; for (int i = 5; i > 1; i--) { IOHelper.strongLog("model parameter: " + i); glmmss.run(i, Config.get().numberOfQueries, Config.get().weight, wordIndex); } } public GLMMySQLSearcher(String databaseName, int k) { // general: super(databaseName, k); } @Override protected String prepareQuery(String[] words, int sequence, int pfl, String[] wordIndex) { int l = words.length; String target = words[l - 1]; String source; int leadingZeros = 0; if (sequence == 1) { source = "true"; + // TODO:remove this: + return null; } else { - // TODO: remove this: - if (sequence == 1) { - return null; - } if (sequence % 2 == 0) { // no target in sequence (e.g. 110) return null; } if (Integer.bitCount(sequence) == this.k || Integer.bitCount(sequence) == Integer.toBinaryString( sequence).length() && Integer.bitCount(sequence) <= this.k) { source = ""; String sequenceBinary = Integer.toBinaryString(sequence); while (sequenceBinary.length() < Config.get().modelLength) { sequenceBinary = "0" + sequenceBinary; leadingZeros++; } // convert binary sequence type into char[] for iteration char[] sequenceChars = sequenceBinary.toCharArray(); // sequencePointer points at sequenceCut // length - 1 to leave out target for (int i = 0; i < sequenceChars.length - 1; i++) { if (Character.getNumericValue(sequenceChars[i]) == 1) { if (source.length() == 0) { source += "source" + (i - leadingZeros) + " =\"" + words[i] + "\""; } else { source += " and source" + (i - leadingZeros) + " =\"" + words[i] + "\""; } } } } else { return null; } } if (pfl > target.length()) { System.out.println("target: '" + target + "' to short for prefixlength: " + pfl); return null; } String prefix = target.substring(0, pfl) + "%"; if (target.equals("-%")) { System.out.println("deteced hyphen"); return null; } String tableName; if (sequence == 1) { tableName = "1_all"; } else { tableName = Integer.toBinaryString(sequence) + "_" + BinarySearch.rank(words[leadingZeros], wordIndex); } String query = ""; if (pfl > 0) { query = "select * from " + tableName + " where " + source + " and target like \"" + prefix + "\" order by score desc limit " + this.joinLength; } else { query = "select * from " + tableName + " where " + source + " order by score desc limit " + this.joinLength; } + System.out.println(query); return query; } }
false
true
protected String prepareQuery(String[] words, int sequence, int pfl, String[] wordIndex) { int l = words.length; String target = words[l - 1]; String source; int leadingZeros = 0; if (sequence == 1) { source = "true"; } else { // TODO: remove this: if (sequence == 1) { return null; } if (sequence % 2 == 0) { // no target in sequence (e.g. 110) return null; } if (Integer.bitCount(sequence) == this.k || Integer.bitCount(sequence) == Integer.toBinaryString( sequence).length() && Integer.bitCount(sequence) <= this.k) { source = ""; String sequenceBinary = Integer.toBinaryString(sequence); while (sequenceBinary.length() < Config.get().modelLength) { sequenceBinary = "0" + sequenceBinary; leadingZeros++; } // convert binary sequence type into char[] for iteration char[] sequenceChars = sequenceBinary.toCharArray(); // sequencePointer points at sequenceCut // length - 1 to leave out target for (int i = 0; i < sequenceChars.length - 1; i++) { if (Character.getNumericValue(sequenceChars[i]) == 1) { if (source.length() == 0) { source += "source" + (i - leadingZeros) + " =\"" + words[i] + "\""; } else { source += " and source" + (i - leadingZeros) + " =\"" + words[i] + "\""; } } } } else { return null; } } if (pfl > target.length()) { System.out.println("target: '" + target + "' to short for prefixlength: " + pfl); return null; } String prefix = target.substring(0, pfl) + "%"; if (target.equals("-%")) { System.out.println("deteced hyphen"); return null; } String tableName; if (sequence == 1) { tableName = "1_all"; } else { tableName = Integer.toBinaryString(sequence) + "_" + BinarySearch.rank(words[leadingZeros], wordIndex); } String query = ""; if (pfl > 0) { query = "select * from " + tableName + " where " + source + " and target like \"" + prefix + "\" order by score desc limit " + this.joinLength; } else { query = "select * from " + tableName + " where " + source + " order by score desc limit " + this.joinLength; } return query; }
protected String prepareQuery(String[] words, int sequence, int pfl, String[] wordIndex) { int l = words.length; String target = words[l - 1]; String source; int leadingZeros = 0; if (sequence == 1) { source = "true"; // TODO:remove this: return null; } else { if (sequence % 2 == 0) { // no target in sequence (e.g. 110) return null; } if (Integer.bitCount(sequence) == this.k || Integer.bitCount(sequence) == Integer.toBinaryString( sequence).length() && Integer.bitCount(sequence) <= this.k) { source = ""; String sequenceBinary = Integer.toBinaryString(sequence); while (sequenceBinary.length() < Config.get().modelLength) { sequenceBinary = "0" + sequenceBinary; leadingZeros++; } // convert binary sequence type into char[] for iteration char[] sequenceChars = sequenceBinary.toCharArray(); // sequencePointer points at sequenceCut // length - 1 to leave out target for (int i = 0; i < sequenceChars.length - 1; i++) { if (Character.getNumericValue(sequenceChars[i]) == 1) { if (source.length() == 0) { source += "source" + (i - leadingZeros) + " =\"" + words[i] + "\""; } else { source += " and source" + (i - leadingZeros) + " =\"" + words[i] + "\""; } } } } else { return null; } } if (pfl > target.length()) { System.out.println("target: '" + target + "' to short for prefixlength: " + pfl); return null; } String prefix = target.substring(0, pfl) + "%"; if (target.equals("-%")) { System.out.println("deteced hyphen"); return null; } String tableName; if (sequence == 1) { tableName = "1_all"; } else { tableName = Integer.toBinaryString(sequence) + "_" + BinarySearch.rank(words[leadingZeros], wordIndex); } String query = ""; if (pfl > 0) { query = "select * from " + tableName + " where " + source + " and target like \"" + prefix + "\" order by score desc limit " + this.joinLength; } else { query = "select * from " + tableName + " where " + source + " order by score desc limit " + this.joinLength; } System.out.println(query); return query; }
diff --git a/src/devedroid/opensurveyor/ButtonUIFragment.java b/src/devedroid/opensurveyor/ButtonUIFragment.java index e84f2b5..2f16bc2 100644 --- a/src/devedroid/opensurveyor/ButtonUIFragment.java +++ b/src/devedroid/opensurveyor/ButtonUIFragment.java @@ -1,224 +1,224 @@ package devedroid.opensurveyor; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apmem.tools.layouts.FlowLayout; import android.app.Activity; import android.os.Bundle; import android.view.Display; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import com.actionbarsherlock.app.SherlockFragment; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import com.actionbarsherlock.view.MenuItem.OnMenuItemClickListener; import devedroid.opensurveyor.PresetManager.PresetSet; import devedroid.opensurveyor.data.Marker; import devedroid.opensurveyor.data.POI; public class ButtonUIFragment extends SherlockFragment { private MainActivity parent; private View root; private FlowLayout flow; private ListView lvHist; private PropertyWindow propsWin; // private List<String> lhist; private ArrayAdapter<Marker> histAdapter; private List<PresetManager.PresetSet> presetSets; private PresetSet selPresetSet; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment root = inflater.inflate(R.layout.frag_buttons, container, false); flow = (FlowLayout) root.findViewById(R.id.flow); propsWin = (PropertyWindow) root.findViewById(R.id.props); propsWin.setParent(this); lvHist = (ListView) root.findViewById(R.id.l_history); List<Marker> lhist = new ArrayList<Marker>(); histAdapter = new ArrayAdapter<Marker>(root.getContext(), R.layout.item_poi, lhist) { private SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = View.inflate(parent.getContext(), R.layout.item_poi, null); } Marker item = getItem(position); - TextView tw = (TextView) convertView.findViewById(R.id.text1); + TextView tw = (TextView) convertView.findViewById(android.R.id.text1); tw.setText("" + sdf.format(new Date(item.getTimestamp()))); - TextView tw2 = (TextView) convertView.findViewById(R.id.text2); + TextView tw2 = (TextView) convertView.findViewById(android.R.id.text2); tw2.setText(item.getDesc() ); View tw3 = (View) convertView.findViewById(R.id.location); if(item.hasLocation()) tw3.setVisibility( View.VISIBLE ); //tw3.setText(item.hasLocation()?"gps":""); return convertView; } }; lvHist.setAdapter(histAdapter); Utils.logd("ButtonUIFragment", "parent=" + parent); for (Marker m : parent.getMarkers()) { histAdapter.add(m); } lvHist.setSelection(histAdapter.getCount() - 1); TextView empty = (TextView) root.findViewById(android.R.id.empty); lvHist.setEmptyView(empty); PresetManager loader = new PresetManager(); presetSets = loader.loadPresetSets(root.getContext()); selPresetSet = presetSets.get(0); setHasOptionsMenu(true); root.post(new Runnable() { public void run() { addButtons(); } }); return root; } /** Should be called when flow width and height is known */ private void addButtons() { Display display = getSherlockActivity().getWindowManager() .getDefaultDisplay(); flow.removeAllViews(); int width = flow.getWidth(); int height = flow.getHeight(); width = Math.min(width, height) * 33 / 100; height = width; List<BasePreset> preset = new ArrayList<BasePreset>( selPresetSet.getPresets()); preset.add(0, new TextPreset()); Utils.logd("ButtonUIFragment", String.format("w/h=%d/%d; " + "dis w/h=%d/%d; " + "act w/h=%d/%d; " + "hist h=%d; " + " flow w/h=%d/%d", width, height, display.getWidth(), display.getHeight(), root.getRight(), root.getBottom(), lvHist.getHeight(), flow.getWidth(), flow.getHeight())); for (BasePreset p : preset) { Button bt = p.createButton(root.getContext(), parent); bt.setWidth(width); bt.setHeight(height); // bt.setId(1000+i); // bt.setTag(Integer.valueOf(i)); flow.addView(bt);// , lp); } } @Override public void onAttach(Activity a) { super.onAttach(a); parent = (MainActivity) a; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.menu_buttons_ui, menu); MenuItem miPresets = menu.findItem(R.id.mi_presets); OnMenuItemClickListener ll = new OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { selPresetSet = presetSets.get(item.getItemId()); addButtons(); parent.invalidateOptionsMenu(); return false; } }; int i = 0; for (PresetSet p : presetSets) { MenuItem sitem = miPresets.getSubMenu().add(0, i, i, p.getName()); sitem.setCheckable(true); sitem.setOnMenuItemClickListener(ll); //if (p == selPresetSet) sitem.setChecked(true); i++; } } @Override public void onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); MenuItem miPresets = menu.findItem(R.id.mi_presets); for (int i = 0; i < miPresets.getSubMenu().size(); i++) { MenuItem sitem = miPresets.getSubMenu().getItem(i); sitem.setChecked(presetSets.get(i) == selPresetSet); } } public void onNewSession() { } public void onFinishSession() { } public void onPoiAdded(Marker m) { histAdapter.add(m); if (propsWin.getVisibility() == View.VISIBLE) hideEditPropWin(); if (parent.getCurrentFragment() == this) { if ((m instanceof POI && "end".equals(((POI) m) .getProperty("linear"))) || (m.getPreset().getProperties().size() == 0)) return; showEditPropWin(m); } } public void showEditPropWin(Marker m) { // lvHist.setVisibility(View.GONE); propsWin.setVisibility(View.VISIBLE); propsWin.setMarker(m); propsWin.rearmTimeoutTimer(); } public void hideEditPropWin() { // Utils.logd(this, "hideEditPropWin"); propsWin.saveProps(); propsWin.cancelTimeoutTimer(); parent.runOnUiThread(new Runnable() { @Override public void run() { propsWin.setVisibility(View.GONE); histAdapter.notifyDataSetChanged(); // lvHist.setVisibility(View.VISIBLE); } }); } void runOnUiThread(Runnable r) { parent.runOnUiThread(r); } }
false
true
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment root = inflater.inflate(R.layout.frag_buttons, container, false); flow = (FlowLayout) root.findViewById(R.id.flow); propsWin = (PropertyWindow) root.findViewById(R.id.props); propsWin.setParent(this); lvHist = (ListView) root.findViewById(R.id.l_history); List<Marker> lhist = new ArrayList<Marker>(); histAdapter = new ArrayAdapter<Marker>(root.getContext(), R.layout.item_poi, lhist) { private SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = View.inflate(parent.getContext(), R.layout.item_poi, null); } Marker item = getItem(position); TextView tw = (TextView) convertView.findViewById(R.id.text1); tw.setText("" + sdf.format(new Date(item.getTimestamp()))); TextView tw2 = (TextView) convertView.findViewById(R.id.text2); tw2.setText(item.getDesc() ); View tw3 = (View) convertView.findViewById(R.id.location); if(item.hasLocation()) tw3.setVisibility( View.VISIBLE ); //tw3.setText(item.hasLocation()?"gps":""); return convertView; } }; lvHist.setAdapter(histAdapter); Utils.logd("ButtonUIFragment", "parent=" + parent); for (Marker m : parent.getMarkers()) { histAdapter.add(m); } lvHist.setSelection(histAdapter.getCount() - 1); TextView empty = (TextView) root.findViewById(android.R.id.empty); lvHist.setEmptyView(empty); PresetManager loader = new PresetManager(); presetSets = loader.loadPresetSets(root.getContext()); selPresetSet = presetSets.get(0); setHasOptionsMenu(true); root.post(new Runnable() { public void run() { addButtons(); } }); return root; }
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment root = inflater.inflate(R.layout.frag_buttons, container, false); flow = (FlowLayout) root.findViewById(R.id.flow); propsWin = (PropertyWindow) root.findViewById(R.id.props); propsWin.setParent(this); lvHist = (ListView) root.findViewById(R.id.l_history); List<Marker> lhist = new ArrayList<Marker>(); histAdapter = new ArrayAdapter<Marker>(root.getContext(), R.layout.item_poi, lhist) { private SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = View.inflate(parent.getContext(), R.layout.item_poi, null); } Marker item = getItem(position); TextView tw = (TextView) convertView.findViewById(android.R.id.text1); tw.setText("" + sdf.format(new Date(item.getTimestamp()))); TextView tw2 = (TextView) convertView.findViewById(android.R.id.text2); tw2.setText(item.getDesc() ); View tw3 = (View) convertView.findViewById(R.id.location); if(item.hasLocation()) tw3.setVisibility( View.VISIBLE ); //tw3.setText(item.hasLocation()?"gps":""); return convertView; } }; lvHist.setAdapter(histAdapter); Utils.logd("ButtonUIFragment", "parent=" + parent); for (Marker m : parent.getMarkers()) { histAdapter.add(m); } lvHist.setSelection(histAdapter.getCount() - 1); TextView empty = (TextView) root.findViewById(android.R.id.empty); lvHist.setEmptyView(empty); PresetManager loader = new PresetManager(); presetSets = loader.loadPresetSets(root.getContext()); selPresetSet = presetSets.get(0); setHasOptionsMenu(true); root.post(new Runnable() { public void run() { addButtons(); } }); return root; }
diff --git a/src/core/java/com/dataiku/dip/input/formats/SmartRegexpFormatExtractor.java b/src/core/java/com/dataiku/dip/input/formats/SmartRegexpFormatExtractor.java index f5abc4c..5d2777c 100644 --- a/src/core/java/com/dataiku/dip/input/formats/SmartRegexpFormatExtractor.java +++ b/src/core/java/com/dataiku/dip/input/formats/SmartRegexpFormatExtractor.java @@ -1,102 +1,102 @@ package com.dataiku.dip.input.formats; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import com.dataiku.dip.datalayer.Column; import com.dataiku.dip.datalayer.ColumnFactory; import com.dataiku.dip.datalayer.ProcessorOutput; import com.dataiku.dip.datalayer.Row; import com.dataiku.dip.datalayer.RowFactory; import com.dataiku.dip.input.StreamInputSplitProgressListener; import com.dataiku.dip.input.stream.EnrichedInputStream; import com.dataiku.dip.input.stream.StreamsInputSplit; import com.dataiku.dip.utils.RegexpFieldsBuilder; import com.google.common.io.CountingInputStream; public class SmartRegexpFormatExtractor extends AbstractFormatExtractor { private RegexpFieldsBuilder regexpFieldsBuilder; public SmartRegexpFormatExtractor(RegexpFieldsBuilder regexpFieldsBuilder) { this.regexpFieldsBuilder = regexpFieldsBuilder; } @Override public boolean run(StreamsInputSplit in, ProcessorOutput out, ProcessorOutput err, ColumnFactory cf, RowFactory rf, StreamInputSplitProgressListener listener, ExtractionLimit limit) throws Exception { List<Column> columns = new ArrayList<Column>(); for (String columnName : regexpFieldsBuilder.getColumnNames()) { columns.add(cf.column(columnName)); } long totalRecords = 0; while (true) { - if (limit.maxRecords > 0 && limit.maxRecords <= totalRecords) return false; + if (limit != null && limit.maxRecords > 0 && limit.maxRecords <= totalRecords) return false; EnrichedInputStream stream = in.nextStream(); if (stream == null) break; InputStream is = stream.stream(); CountingInputStream cis = new CountingInputStream(is); // TODO CHARSET BufferedReader br = new BufferedReader(new InputStreamReader(cis, "utf8")); try { long nlines = 0; while (true) { - if (limit.maxRecords > 0 && limit.maxRecords <= totalRecords) return false; + if (limit != null && limit.maxRecords > 0 && limit.maxRecords <= totalRecords) return false; String line = br.readLine(); if (line == null) { break; } line = line.trim(); List<String> values = regexpFieldsBuilder.exec(line); if (values == null) { System.err.println("Did not parse " + line); Row r = rf.row(); r.put(cf.column("reject"), line); if (err != null) err.emitRow(r); } else { Row r = rf.row(); for (int i = 0 ; i < values.size(); i++) { r.put(columns.get(i), values.get(i)); } out.emitRow(r); } totalRecords++; if (listener != null && nlines++ % 50 == 0) { synchronized (listener) { listener.setErrorRecords(0); listener.setReadBytes(cis.getCount()); listener.setReadRecords(nlines); } } } /* Set the final listener data */ if (listener != null) { synchronized (listener) { listener.setErrorRecords(0); listener.setReadBytes(cis.getCount()); listener.setReadRecords(nlines); } } } finally { br.close(); } // TODO: properly close streams } out.lastRowEmitted(); return true; } // private Logger logger = Logger.getLogger("csv"); }
false
true
public boolean run(StreamsInputSplit in, ProcessorOutput out, ProcessorOutput err, ColumnFactory cf, RowFactory rf, StreamInputSplitProgressListener listener, ExtractionLimit limit) throws Exception { List<Column> columns = new ArrayList<Column>(); for (String columnName : regexpFieldsBuilder.getColumnNames()) { columns.add(cf.column(columnName)); } long totalRecords = 0; while (true) { if (limit.maxRecords > 0 && limit.maxRecords <= totalRecords) return false; EnrichedInputStream stream = in.nextStream(); if (stream == null) break; InputStream is = stream.stream(); CountingInputStream cis = new CountingInputStream(is); // TODO CHARSET BufferedReader br = new BufferedReader(new InputStreamReader(cis, "utf8")); try { long nlines = 0; while (true) { if (limit.maxRecords > 0 && limit.maxRecords <= totalRecords) return false; String line = br.readLine(); if (line == null) { break; } line = line.trim(); List<String> values = regexpFieldsBuilder.exec(line); if (values == null) { System.err.println("Did not parse " + line); Row r = rf.row(); r.put(cf.column("reject"), line); if (err != null) err.emitRow(r); } else { Row r = rf.row(); for (int i = 0 ; i < values.size(); i++) { r.put(columns.get(i), values.get(i)); } out.emitRow(r); } totalRecords++; if (listener != null && nlines++ % 50 == 0) { synchronized (listener) { listener.setErrorRecords(0); listener.setReadBytes(cis.getCount()); listener.setReadRecords(nlines); } } } /* Set the final listener data */ if (listener != null) { synchronized (listener) { listener.setErrorRecords(0); listener.setReadBytes(cis.getCount()); listener.setReadRecords(nlines); } } } finally { br.close(); } // TODO: properly close streams } out.lastRowEmitted(); return true; }
public boolean run(StreamsInputSplit in, ProcessorOutput out, ProcessorOutput err, ColumnFactory cf, RowFactory rf, StreamInputSplitProgressListener listener, ExtractionLimit limit) throws Exception { List<Column> columns = new ArrayList<Column>(); for (String columnName : regexpFieldsBuilder.getColumnNames()) { columns.add(cf.column(columnName)); } long totalRecords = 0; while (true) { if (limit != null && limit.maxRecords > 0 && limit.maxRecords <= totalRecords) return false; EnrichedInputStream stream = in.nextStream(); if (stream == null) break; InputStream is = stream.stream(); CountingInputStream cis = new CountingInputStream(is); // TODO CHARSET BufferedReader br = new BufferedReader(new InputStreamReader(cis, "utf8")); try { long nlines = 0; while (true) { if (limit != null && limit.maxRecords > 0 && limit.maxRecords <= totalRecords) return false; String line = br.readLine(); if (line == null) { break; } line = line.trim(); List<String> values = regexpFieldsBuilder.exec(line); if (values == null) { System.err.println("Did not parse " + line); Row r = rf.row(); r.put(cf.column("reject"), line); if (err != null) err.emitRow(r); } else { Row r = rf.row(); for (int i = 0 ; i < values.size(); i++) { r.put(columns.get(i), values.get(i)); } out.emitRow(r); } totalRecords++; if (listener != null && nlines++ % 50 == 0) { synchronized (listener) { listener.setErrorRecords(0); listener.setReadBytes(cis.getCount()); listener.setReadRecords(nlines); } } } /* Set the final listener data */ if (listener != null) { synchronized (listener) { listener.setErrorRecords(0); listener.setReadBytes(cis.getCount()); listener.setReadRecords(nlines); } } } finally { br.close(); } // TODO: properly close streams } out.lastRowEmitted(); return true; }
diff --git a/src/com/chuckanutbay/webapp/common/server/TimeClockServiceImpl.java b/src/com/chuckanutbay/webapp/common/server/TimeClockServiceImpl.java index 2c4f6da..c33aab7 100644 --- a/src/com/chuckanutbay/webapp/common/server/TimeClockServiceImpl.java +++ b/src/com/chuckanutbay/webapp/common/server/TimeClockServiceImpl.java @@ -1,299 +1,299 @@ package com.chuckanutbay.webapp.common.server; import static com.chuckanutbay.webapp.common.server.DtoUtils.fromEmployeeDtoFunction; import static com.google.common.collect.Lists.newArrayList; import static java.util.Collections.sort; import java.util.ArrayList; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import org.joda.time.DateMidnight; import org.joda.time.DateTime; import org.joda.time.Period; import org.joda.time.PeriodType; import com.chuckanutbay.businessobjects.Employee; import com.chuckanutbay.businessobjects.EmployeeWorkInterval; import com.chuckanutbay.businessobjects.EmployeeWorkIntervalActivityPercentage; import com.chuckanutbay.businessobjects.dao.ActivityDao; import com.chuckanutbay.businessobjects.dao.ActivityHibernateDao; import com.chuckanutbay.businessobjects.dao.EmployeeDao; import com.chuckanutbay.businessobjects.dao.EmployeeHibernateDao; import com.chuckanutbay.businessobjects.dao.EmployeeWorkIntervalActivityPercentageDao; import com.chuckanutbay.businessobjects.dao.EmployeeWorkIntervalActivityPercentageHibernateDao; import com.chuckanutbay.businessobjects.dao.EmployeeWorkIntervalDao; import com.chuckanutbay.businessobjects.dao.EmployeeWorkIntervalHibernateDao; import com.chuckanutbay.webapp.common.client.TimeClockService; import com.chuckanutbay.webapp.common.shared.ActivityDto; import com.chuckanutbay.webapp.common.shared.DayReportData; import com.chuckanutbay.webapp.common.shared.EmployeeDto; import com.chuckanutbay.webapp.common.shared.EmployeeWorkIntervalActivityPercentageDto; import com.chuckanutbay.webapp.common.shared.EmployeeWorkIntervalDto; import com.chuckanutbay.webapp.common.shared.IntervalDto; import com.chuckanutbay.webapp.common.shared.PayPeriodReportData; import com.chuckanutbay.webapp.common.shared.WeekReportData; import com.google.gwt.user.server.rpc.RemoteServiceServlet; public class TimeClockServiceImpl extends RemoteServiceServlet implements TimeClockService { private static final long serialVersionUID = 1L; @Override public EmployeeDto clockIn(Integer barcode) { EmployeeDao employeeDao = new EmployeeHibernateDao(); EmployeeWorkIntervalDao intervalDao = new EmployeeWorkIntervalHibernateDao(); //Find employee from barcode Employee employee = employeeDao.findEmployeeWithBarcodeNumber(barcode); if (employee == null) { System.out.println("No Employees had the barcode number"); return null; } System.out.println("The employee with the barcode number is: " + employee.getFirstName()); if (intervalDao.findOpenEmployeeWorkInterval(employee) == null) { //Start a new employee work interval EmployeeWorkInterval newInterval = new EmployeeWorkInterval(); newInterval.setEmployee(employee); newInterval.setStartDateTime(new Date()); intervalDao.makePersistent(newInterval); System.out.println("The new interval was persisted"); //Return a complete EmployeeDto return completeToEmployeeDto(employee); } else { return null; } } @Override public void clockOut(EmployeeDto employeeDto) { EmployeeWorkIntervalDao intervalDao = new EmployeeWorkIntervalHibernateDao(); EmployeeWorkIntervalActivityPercentageDao percentageDao = new EmployeeWorkIntervalActivityPercentageHibernateDao(); EmployeeWorkInterval interval = intervalDao.findOpenEmployeeWorkInterval(DtoUtils.fromEmployeeDtoFunction.apply(employeeDto)); interval.setEndDateTime(new Date()); interval.setComment(employeeDto.getComment()); intervalDao.makePersistent(interval); System.out.println("Persisted Interval"); List<EmployeeWorkIntervalActivityPercentage> percentages = DtoUtils.transform(employeeDto.getEmployeeWorkIntervalPercentages(), DtoUtils.fromEmployeeWorkIntervalActivityPercentageDtoFunction); for (EmployeeWorkIntervalActivityPercentage percentage : percentages) { percentage.setEmployeeWorkInterval(interval); System.out.println("Percentage: ActivityId(" + percentage.getActivity().getId() + ") IntervalId(" + percentage.getEmployeeWorkInterval().getId() + ") Percentage(" + percentage.getPercentage() + ") of " + percentages.size()); percentageDao.makePersistent(percentage); } System.out.println("Persisted Percentages"); } @Override public SortedSet<EmployeeDto> getClockedInEmployees() { EmployeeWorkIntervalDao dao = new EmployeeWorkIntervalHibernateDao(); SortedSet<EmployeeDto> employees = new TreeSet<EmployeeDto>(); for (EmployeeWorkInterval interval : dao.findOpenEmployeeWorkIntervals()) { employees.add(completeToEmployeeDto(interval.getEmployee())); } return employees; } @Override public void cancelClockIn(Integer barcode) { EmployeeDao employeeDao = new EmployeeHibernateDao(); Employee employee = employeeDao.findEmployeeWithBarcodeNumber(barcode); EmployeeWorkIntervalDao intervalDao = new EmployeeWorkIntervalHibernateDao(); EmployeeWorkInterval interval = intervalDao.findOpenEmployeeWorkInterval(employee); intervalDao.makeTransient(interval); } @Override public SortedSet<ActivityDto> getActivities() { ActivityDao dao = new ActivityHibernateDao(); return new TreeSet<ActivityDto>(DtoUtils.transform(dao.findAll(), DtoUtils.toActivityDtoFunction)); } private static EmployeeDto completeToEmployeeDto(Employee employee) { EmployeeWorkIntervalDao dao = new EmployeeWorkIntervalHibernateDao(); //Do an incomplete conversion form Employee to EmployeeDto EmployeeDto employeeDto = DtoUtils.toEmployeeDtoFunction.apply(employee); calculateMinutesWorkedThisWeek(employeeDto); //Set the percentages to be what they were for the most recently closed interval Set<EmployeeWorkIntervalActivityPercentage> lastEnteredPercentages = dao.findLastEnteredPercentages(employee); List<EmployeeWorkIntervalActivityPercentageDto> percentageDtos; if (lastEnteredPercentages == null) { percentageDtos = new ArrayList<EmployeeWorkIntervalActivityPercentageDto>(); } else { percentageDtos = DtoUtils.transform(lastEnteredPercentages, DtoUtils.toEmployeeWorkIntervalActivityPercentageDtoFunction); } employeeDto.setEmployeeWorkIntervalPercentages(percentageDtos); return employeeDto; } private static void calculateMinutesWorkedThisWeek(EmployeeDto employeeDto) { EmployeeWorkIntervalDao dao = new EmployeeWorkIntervalHibernateDao(); //Find last Sunday at the start of the day DateTime lastSunday = new DateMidnight().minusDays(new DateMidnight().getDayOfWeek()).toDateTime(); employeeDto.setMinsWorkedThisWeek(0); List<EmployeeWorkInterval> employeeWorkIntervals = dao.findEmployeeWorkIntervalsBetweenDates(fromEmployeeDtoFunction.apply(employeeDto), lastSunday, new DateTime()); for (EmployeeWorkInterval interval : employeeWorkIntervals) { //If the interval isn't closed then use the current time to determine the number of minutes worked. Otherwise use the difference between start and end time. if (interval.getEndDateTime() == null) { Period period = new Period(new DateTime(interval.getStartDateTime()), new DateTime(), PeriodType.minutes()); System.out.println("Period length in min: " + period.getMinutes()); System.out.println("Minutes worked before update: " + employeeDto.getMinsWorkedThisWeek()); employeeDto.setMinsWorkedThisWeek(employeeDto.getMinsWorkedThisWeek() + period.getMinutes()); System.out.println("Minutes worked after update: " + employeeDto.getMinsWorkedThisWeek()); } else { Period period = new Period(new DateTime(interval.getStartDateTime()), new DateTime(interval.getEndDateTime()), PeriodType.minutes()); System.out.println("Time now in mill: " + new DateMidnight().getMillis()); System.out.println("StartTime in mill: " + new DateTime(interval.getStartDateTime()).getMillis()); System.out.println("EndTime in mill: " + new DateTime(interval.getEndDateTime()).getMillis()); System.out.println("Period length in sec: " + period.getSeconds()); System.out.println("Minutes worked before update: " + employeeDto.getMinsWorkedThisWeek()); employeeDto.setMinsWorkedThisWeek(employeeDto.getMinsWorkedThisWeek() + period.getMinutes()); System.out.println("Minutes worked after update: " + employeeDto.getMinsWorkedThisWeek()); } } } @Override public IntervalDto getLastPayPeriodIntervalFromServer(Date date) { DateTime startOfPayPeriod; DateTime endOfPayPeriod; DateTime dateTime = new DateTime(date); if(dateTime.getDayOfMonth() > 15) { startOfPayPeriod = dateTime.withDayOfMonth(1); endOfPayPeriod = dateTime.withDayOfMonth(15); } else { startOfPayPeriod = dateTime.minusMonths(1); startOfPayPeriod = startOfPayPeriod.withDayOfMonth(16); endOfPayPeriod = dateTime.minusMonths(1); endOfPayPeriod = endOfPayPeriod.dayOfMonth().withMaximumValue(); } return new IntervalDto(startOfPayPeriod.toDate(), endOfPayPeriod.toDate()); } @Override public List<PayPeriodReportData> getPayPeriodReportDataFromDatabase( Date start, Date end, Integer shift) { EmployeeDao employeeDao = new EmployeeHibernateDao(); EmployeeWorkIntervalDao intervalDao = new EmployeeWorkIntervalHibernateDao(); List<PayPeriodReportData> reportData = newArrayList(); DateMidnight payPeriodStart = new DateMidnight(start); System.out.println("Pay Period Start: " + payPeriodStart.toString("MMMM hh:mm a")); DateMidnight payPeriodEnd = new DateMidnight(end); System.out.println("Pay Period End: " + payPeriodStart.toString("MMMM hh:mm a")); payPeriodEnd = payPeriodEnd.plusDays(1); DateMidnight sundayBeforePayPeriodStart; if (payPeriodStart.getDayOfWeek() == 7) { sundayBeforePayPeriodStart = payPeriodStart; } else { sundayBeforePayPeriodStart = payPeriodStart.minusDays(payPeriodStart.getDayOfWeek()); } System.out.println("Sunday Before Period Start: " + payPeriodStart.toString("MMMM hh:mm a")); List<Employee> employees; if (shift == 0) { employees = employeeDao.findAll(); } else { employees = employeeDao.findEmployeesByShift(shift); } for (Employee employee : employees) { if (intervalDao.findEmployeeWorkIntervalsBetweenDates(employee, payPeriodStart.toDateTime(), payPeriodEnd.toDateTime()).size() != 0) { PayPeriodReportData payPeriod = new PayPeriodReportData(); payPeriod.setName(employee.getFirstName() + " " + employee.getLastName()); payPeriod.setId(employee.getId()); payPeriod.setShift(employee.getShift()); payPeriod.setDate(new Date()); payPeriod.setPayPeriodStart(payPeriodStart.toDate()); payPeriod.setPayPeriodEnd(payPeriodEnd.minusDays(1).toDate()); WeekReportData week = new WeekReportData(); payPeriod.addInterval(week); DayReportData day = new DayReportData(); week.addInterval(day); int d = 0; while (d < new Period(sundayBeforePayPeriodStart, payPeriodStart, PeriodType.days()).getDays()) { for (EmployeeWorkInterval interval : findIntervalsHelper(employee, sundayBeforePayPeriodStart, d)) { double intervalHours = getDifference(interval.getStartDateTime(), interval.getEndDateTime()); week.addPrePayPeriodHours(intervalHours); } d++; } while (d < new Period(sundayBeforePayPeriodStart, payPeriodEnd, PeriodType.days()).getDays()) { if (d == 7 || d == 14 || d == 21) { week = new WeekReportData(); payPeriod.addInterval(week); } for (EmployeeWorkInterval interval : findIntervalsHelper(employee, sundayBeforePayPeriodStart, d)) { if (interval.getEndDateTime() != null) { double intervalHours = getDifference(interval.getStartDateTime(), interval.getEndDateTime()); week.addHours(intervalHours); day.addHours(intervalHours); EmployeeWorkIntervalDto intervalDto = DtoUtils.toEmployeeWorkIntervalDtoFunction.apply(interval); intervalDto.addHours(intervalHours); day.addInterval(intervalDto); } } day = new DayReportData(); week.addInterval(day); d++; } for (WeekReportData weekData : payPeriod.getWeekReportData()) { payPeriod.addNormalPayHours(weekData.getHoursNormalPay()); payPeriod.addOvertimeHours(weekData.getHoursOvertime()); } reportData.add(payPeriod); } } sort(reportData, new Comparator<PayPeriodReportData>() { @Override public int compare(PayPeriodReportData person1, PayPeriodReportData person2) { - String lastName1 = person1.getName().substring(person1.getName().indexOf(" ")); - String lastName2 = person2.getName().substring(person2.getName().indexOf(" ")); + String lastName1 = person1.getName().substring(person1.getName().lastIndexOf(" ")); + String lastName2 = person2.getName().substring(person2.getName().lastIndexOf(" ")); return lastName1.compareTo(lastName2); } }); return reportData; } private List<EmployeeWorkInterval> findIntervalsHelper(Employee employee, DateMidnight sundayBeforePayPeriodStart, int day) { return new EmployeeWorkIntervalHibernateDao().findEmployeeWorkIntervalsBetweenDates(employee, sundayBeforePayPeriodStart.plusDays(day).toDateTime(), sundayBeforePayPeriodStart.plusDays(day + 1).toDateTime()); } private double getDifference(Date start, Date end) { Period period = new Period(new DateTime(start), new DateTime(end)); return new Double(period.getHours()) + new Double(period.getMinutes())/60; } @Override public SortedSet<EmployeeDto> updateMinutesWorkedInCurrentWeek( SortedSet<EmployeeDto> employees) { for (EmployeeDto employeeDto : employees) { calculateMinutesWorkedThisWeek(employeeDto); } return employees; } }
true
true
public List<PayPeriodReportData> getPayPeriodReportDataFromDatabase( Date start, Date end, Integer shift) { EmployeeDao employeeDao = new EmployeeHibernateDao(); EmployeeWorkIntervalDao intervalDao = new EmployeeWorkIntervalHibernateDao(); List<PayPeriodReportData> reportData = newArrayList(); DateMidnight payPeriodStart = new DateMidnight(start); System.out.println("Pay Period Start: " + payPeriodStart.toString("MMMM hh:mm a")); DateMidnight payPeriodEnd = new DateMidnight(end); System.out.println("Pay Period End: " + payPeriodStart.toString("MMMM hh:mm a")); payPeriodEnd = payPeriodEnd.plusDays(1); DateMidnight sundayBeforePayPeriodStart; if (payPeriodStart.getDayOfWeek() == 7) { sundayBeforePayPeriodStart = payPeriodStart; } else { sundayBeforePayPeriodStart = payPeriodStart.minusDays(payPeriodStart.getDayOfWeek()); } System.out.println("Sunday Before Period Start: " + payPeriodStart.toString("MMMM hh:mm a")); List<Employee> employees; if (shift == 0) { employees = employeeDao.findAll(); } else { employees = employeeDao.findEmployeesByShift(shift); } for (Employee employee : employees) { if (intervalDao.findEmployeeWorkIntervalsBetweenDates(employee, payPeriodStart.toDateTime(), payPeriodEnd.toDateTime()).size() != 0) { PayPeriodReportData payPeriod = new PayPeriodReportData(); payPeriod.setName(employee.getFirstName() + " " + employee.getLastName()); payPeriod.setId(employee.getId()); payPeriod.setShift(employee.getShift()); payPeriod.setDate(new Date()); payPeriod.setPayPeriodStart(payPeriodStart.toDate()); payPeriod.setPayPeriodEnd(payPeriodEnd.minusDays(1).toDate()); WeekReportData week = new WeekReportData(); payPeriod.addInterval(week); DayReportData day = new DayReportData(); week.addInterval(day); int d = 0; while (d < new Period(sundayBeforePayPeriodStart, payPeriodStart, PeriodType.days()).getDays()) { for (EmployeeWorkInterval interval : findIntervalsHelper(employee, sundayBeforePayPeriodStart, d)) { double intervalHours = getDifference(interval.getStartDateTime(), interval.getEndDateTime()); week.addPrePayPeriodHours(intervalHours); } d++; } while (d < new Period(sundayBeforePayPeriodStart, payPeriodEnd, PeriodType.days()).getDays()) { if (d == 7 || d == 14 || d == 21) { week = new WeekReportData(); payPeriod.addInterval(week); } for (EmployeeWorkInterval interval : findIntervalsHelper(employee, sundayBeforePayPeriodStart, d)) { if (interval.getEndDateTime() != null) { double intervalHours = getDifference(interval.getStartDateTime(), interval.getEndDateTime()); week.addHours(intervalHours); day.addHours(intervalHours); EmployeeWorkIntervalDto intervalDto = DtoUtils.toEmployeeWorkIntervalDtoFunction.apply(interval); intervalDto.addHours(intervalHours); day.addInterval(intervalDto); } } day = new DayReportData(); week.addInterval(day); d++; } for (WeekReportData weekData : payPeriod.getWeekReportData()) { payPeriod.addNormalPayHours(weekData.getHoursNormalPay()); payPeriod.addOvertimeHours(weekData.getHoursOvertime()); } reportData.add(payPeriod); } } sort(reportData, new Comparator<PayPeriodReportData>() { @Override public int compare(PayPeriodReportData person1, PayPeriodReportData person2) { String lastName1 = person1.getName().substring(person1.getName().indexOf(" ")); String lastName2 = person2.getName().substring(person2.getName().indexOf(" ")); return lastName1.compareTo(lastName2); } }); return reportData; }
public List<PayPeriodReportData> getPayPeriodReportDataFromDatabase( Date start, Date end, Integer shift) { EmployeeDao employeeDao = new EmployeeHibernateDao(); EmployeeWorkIntervalDao intervalDao = new EmployeeWorkIntervalHibernateDao(); List<PayPeriodReportData> reportData = newArrayList(); DateMidnight payPeriodStart = new DateMidnight(start); System.out.println("Pay Period Start: " + payPeriodStart.toString("MMMM hh:mm a")); DateMidnight payPeriodEnd = new DateMidnight(end); System.out.println("Pay Period End: " + payPeriodStart.toString("MMMM hh:mm a")); payPeriodEnd = payPeriodEnd.plusDays(1); DateMidnight sundayBeforePayPeriodStart; if (payPeriodStart.getDayOfWeek() == 7) { sundayBeforePayPeriodStart = payPeriodStart; } else { sundayBeforePayPeriodStart = payPeriodStart.minusDays(payPeriodStart.getDayOfWeek()); } System.out.println("Sunday Before Period Start: " + payPeriodStart.toString("MMMM hh:mm a")); List<Employee> employees; if (shift == 0) { employees = employeeDao.findAll(); } else { employees = employeeDao.findEmployeesByShift(shift); } for (Employee employee : employees) { if (intervalDao.findEmployeeWorkIntervalsBetweenDates(employee, payPeriodStart.toDateTime(), payPeriodEnd.toDateTime()).size() != 0) { PayPeriodReportData payPeriod = new PayPeriodReportData(); payPeriod.setName(employee.getFirstName() + " " + employee.getLastName()); payPeriod.setId(employee.getId()); payPeriod.setShift(employee.getShift()); payPeriod.setDate(new Date()); payPeriod.setPayPeriodStart(payPeriodStart.toDate()); payPeriod.setPayPeriodEnd(payPeriodEnd.minusDays(1).toDate()); WeekReportData week = new WeekReportData(); payPeriod.addInterval(week); DayReportData day = new DayReportData(); week.addInterval(day); int d = 0; while (d < new Period(sundayBeforePayPeriodStart, payPeriodStart, PeriodType.days()).getDays()) { for (EmployeeWorkInterval interval : findIntervalsHelper(employee, sundayBeforePayPeriodStart, d)) { double intervalHours = getDifference(interval.getStartDateTime(), interval.getEndDateTime()); week.addPrePayPeriodHours(intervalHours); } d++; } while (d < new Period(sundayBeforePayPeriodStart, payPeriodEnd, PeriodType.days()).getDays()) { if (d == 7 || d == 14 || d == 21) { week = new WeekReportData(); payPeriod.addInterval(week); } for (EmployeeWorkInterval interval : findIntervalsHelper(employee, sundayBeforePayPeriodStart, d)) { if (interval.getEndDateTime() != null) { double intervalHours = getDifference(interval.getStartDateTime(), interval.getEndDateTime()); week.addHours(intervalHours); day.addHours(intervalHours); EmployeeWorkIntervalDto intervalDto = DtoUtils.toEmployeeWorkIntervalDtoFunction.apply(interval); intervalDto.addHours(intervalHours); day.addInterval(intervalDto); } } day = new DayReportData(); week.addInterval(day); d++; } for (WeekReportData weekData : payPeriod.getWeekReportData()) { payPeriod.addNormalPayHours(weekData.getHoursNormalPay()); payPeriod.addOvertimeHours(weekData.getHoursOvertime()); } reportData.add(payPeriod); } } sort(reportData, new Comparator<PayPeriodReportData>() { @Override public int compare(PayPeriodReportData person1, PayPeriodReportData person2) { String lastName1 = person1.getName().substring(person1.getName().lastIndexOf(" ")); String lastName2 = person2.getName().substring(person2.getName().lastIndexOf(" ")); return lastName1.compareTo(lastName2); } }); return reportData; }
diff --git a/src/com/triposo/automator/itunesconnect/AddNewVersion.java b/src/com/triposo/automator/itunesconnect/AddNewVersion.java index 1a9e279..e4230b1 100644 --- a/src/com/triposo/automator/itunesconnect/AddNewVersion.java +++ b/src/com/triposo/automator/itunesconnect/AddNewVersion.java @@ -1,95 +1,93 @@ package com.triposo.automator.itunesconnect; import com.triposo.automator.Task; import org.openqa.selenium.*; import org.yaml.snakeyaml.Yaml; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Iterator; import java.util.Map; import static org.junit.Assert.assertTrue; public class AddNewVersion extends Task { public static void main(String[] args) throws Exception { new AddNewVersion().run(); } public void doRun() throws Exception { - String version = "1.8"; + String version = "1.8.1"; String whatsnew = - "★ Sync bookmarks between devices and our website.\n" + - "★ Travelpedia.\n" + - "★ Bugfixes."; + "★ Fixes an issue which prevented bookmark syncing to work for some of our users.\n"; Yaml yaml = new Yaml(); Map guides = (Map) yaml.load(new FileInputStream(new File("../pipeline/config/guides.yaml"))); for (Iterator iterator = guides.entrySet().iterator(); iterator.hasNext(); ) { Map.Entry entry = (Map.Entry) iterator.next(); String location = (String) entry.getKey(); Map guide = (Map) entry.getValue(); Map ios = (Map) guide.get("ios"); if (ios != null) { Integer appleId = (Integer) ios.get("apple_id"); if (appleId != null && appleId.intValue() > 0) { System.out.println("Processing " + location); try { addNewVersion(appleId, version, whatsnew); } catch (Exception e) { e.printStackTrace(); System.out.println("Error processing, skipping: " + location); } System.out.println("Done " + location); } } } System.out.println("All done."); } private void addNewVersion(Integer appleId, String version, String whatsnew) { ManageApplicationsPage manageApplicationsPage = gotoItunesConnect(getProperty("itunes.username"), getProperty("itunes.password")).gotoManageApplications(); SearchResultPage searchResultPage = manageApplicationsPage.searchByAppleId(appleId); AppSummaryPage appSummaryPage = searchResultPage.clickFirstResult(); if (appSummaryPage.containsText("The most recent version of your app has been rejected")) { System.out.println("Last version rejected, skipping: " + appleId); return; } VersionDetailsPage versionDetailsPage; if (!appSummaryPage.containsText(version)) { NewVersionPage newVersionPage = appSummaryPage.clickAddVersion(); newVersionPage.setVersionNumber(version); newVersionPage.setWhatsnew(whatsnew); versionDetailsPage = newVersionPage.clickSave(); } else { versionDetailsPage = appSummaryPage.clickNewVersionViewDetails(); } if (appSummaryPage.containsText("Prepare for Upload") || appSummaryPage.containsText("Developer Rejected")) { LegalIssuesPage legalIssuesPage = versionDetailsPage.clickReadyToUploadBinary(); legalIssuesPage.theUsualBlahBlah(); AutoReleasePage autoReleasePage = legalIssuesPage.clickSave(); autoReleasePage.setAutoReleaseYes(); autoReleasePage.clickSave(); } } private MainPage gotoItunesConnect(String username, String password) { driver.get("https://itunesconnect.apple.com"); if (driver.findElement(By.cssSelector("body")).getText().contains("Password")) { SigninPage signinPage = new SigninPage(driver); signinPage.signin(username, password); } try { WebElement continueButton = driver.findElement(By.cssSelector("img.customActionButton")); continueButton.click(); } catch (NoSuchElementException e) { } return new MainPage(driver); } }
false
true
public void doRun() throws Exception { String version = "1.8"; String whatsnew = "★ Sync bookmarks between devices and our website.\n" + "★ Travelpedia.\n" + "★ Bugfixes."; Yaml yaml = new Yaml(); Map guides = (Map) yaml.load(new FileInputStream(new File("../pipeline/config/guides.yaml"))); for (Iterator iterator = guides.entrySet().iterator(); iterator.hasNext(); ) { Map.Entry entry = (Map.Entry) iterator.next(); String location = (String) entry.getKey(); Map guide = (Map) entry.getValue(); Map ios = (Map) guide.get("ios"); if (ios != null) { Integer appleId = (Integer) ios.get("apple_id"); if (appleId != null && appleId.intValue() > 0) { System.out.println("Processing " + location); try { addNewVersion(appleId, version, whatsnew); } catch (Exception e) { e.printStackTrace(); System.out.println("Error processing, skipping: " + location); } System.out.println("Done " + location); } } } System.out.println("All done."); }
public void doRun() throws Exception { String version = "1.8.1"; String whatsnew = "★ Fixes an issue which prevented bookmark syncing to work for some of our users.\n"; Yaml yaml = new Yaml(); Map guides = (Map) yaml.load(new FileInputStream(new File("../pipeline/config/guides.yaml"))); for (Iterator iterator = guides.entrySet().iterator(); iterator.hasNext(); ) { Map.Entry entry = (Map.Entry) iterator.next(); String location = (String) entry.getKey(); Map guide = (Map) entry.getValue(); Map ios = (Map) guide.get("ios"); if (ios != null) { Integer appleId = (Integer) ios.get("apple_id"); if (appleId != null && appleId.intValue() > 0) { System.out.println("Processing " + location); try { addNewVersion(appleId, version, whatsnew); } catch (Exception e) { e.printStackTrace(); System.out.println("Error processing, skipping: " + location); } System.out.println("Done " + location); } } } System.out.println("All done."); }
diff --git a/dspace-api/src/main/java/org/dspace/eperson/Group.java b/dspace-api/src/main/java/org/dspace/eperson/Group.java index 8cb349ded..caae51ada 100644 --- a/dspace-api/src/main/java/org/dspace/eperson/Group.java +++ b/dspace-api/src/main/java/org/dspace/eperson/Group.java @@ -1,1328 +1,1328 @@ /* * Group.java * * Version: $Revision$ * * Date: $Date$ * * Copyright (c) 2002-2009, The DSpace 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: * * - 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 DSpace Foundation 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 * HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ package org.dspace.eperson; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.io.IOException; import org.apache.log4j.Logger; import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeManager; import org.dspace.content.DSpaceObject; import org.dspace.core.ConfigurationManager; import org.dspace.core.Constants; import org.dspace.core.Context; import org.dspace.core.LogManager; import org.dspace.event.Event; import org.dspace.storage.rdbms.DatabaseManager; import org.dspace.storage.rdbms.TableRow; import org.dspace.storage.rdbms.TableRowIterator; /** * Class representing a group of e-people. * * @author David Stuve * @version $Revision$ */ public class Group extends DSpaceObject { // findAll sortby types public static final int ID = 0; // sort by ID public static final int NAME = 1; // sort by NAME (default) /** log4j logger */ private static Logger log = Logger.getLogger(Group.class); /** Our context */ private Context myContext; /** The row in the table representing this object */ private TableRow myRow; /** lists of epeople and groups in the group */ private List<EPerson> epeople = new ArrayList<EPerson>(); private List<Group> groups = new ArrayList<Group>(); /** lists that need to be written out again */ private boolean epeopleChanged = false; private boolean groupsChanged = false; /** is this just a stub, or is all data loaded? */ private boolean isDataLoaded = false; /** Flag set when metadata is modified, for events */ private boolean modifiedMetadata; /** * Construct a Group from a given context and tablerow * * @param context * @param row */ Group(Context context, TableRow row) throws SQLException { myContext = context; myRow = row; // Cache ourselves context.cache(this, row.getIntColumn("eperson_group_id")); modifiedMetadata = false; clearDetails(); } /** * Populate Group with eperson and group objects * * @throws SQLException */ public void loadData() { // only populate if not already populated if (!isDataLoaded) { // naughty thing to do - swallowing SQL exception and throwing it as // a RuntimeException - a hack to avoid changing the API all over // the place try { // get epeople objects TableRowIterator tri = DatabaseManager.queryTable(myContext,"eperson", "SELECT eperson.* FROM eperson, epersongroup2eperson WHERE " + "epersongroup2eperson.eperson_id=eperson.eperson_id AND " + "epersongroup2eperson.eperson_group_id= ?", myRow.getIntColumn("eperson_group_id")); try { while (tri.hasNext()) { TableRow r = (TableRow) tri.next(); // First check the cache EPerson fromCache = (EPerson) myContext.fromCache( EPerson.class, r.getIntColumn("eperson_id")); if (fromCache != null) { epeople.add(fromCache); } else { epeople.add(new EPerson(myContext, r)); } } } finally { // close the TableRowIterator to free up resources if (tri != null) tri.close(); } // now get Group objects tri = DatabaseManager.queryTable(myContext,"epersongroup", "SELECT epersongroup.* FROM epersongroup, group2group WHERE " + "group2group.child_id=epersongroup.eperson_group_id AND "+ "group2group.parent_id= ? ", myRow.getIntColumn("eperson_group_id")); try { while (tri.hasNext()) { TableRow r = (TableRow) tri.next(); // First check the cache Group fromCache = (Group) myContext.fromCache(Group.class, r.getIntColumn("eperson_group_id")); if (fromCache != null) { groups.add(fromCache); } else { groups.add(new Group(myContext, r)); } } } finally { // close the TableRowIterator to free up resources if (tri != null) tri.close(); } } catch (Exception e) { throw new RuntimeException(e); } isDataLoaded = true; } } /** * Create a new group * * @param context * DSpace context object */ public static Group create(Context context) throws SQLException, AuthorizeException { // FIXME - authorization? if (!AuthorizeManager.isAdmin(context)) { throw new AuthorizeException( "You must be an admin to create an EPerson Group"); } // Create a table row TableRow row = DatabaseManager.create(context, "epersongroup"); Group g = new Group(context, row); log.info(LogManager.getHeader(context, "create_group", "group_id=" + g.getID())); context.addEvent(new Event(Event.CREATE, Constants.GROUP, g.getID(), null)); return g; } /** * get the ID of the group object * * @return id */ public int getID() { return myRow.getIntColumn("eperson_group_id"); } /** * get name of group * * @return name */ public String getName() { return myRow.getStringColumn("name"); } /** * set name of group * * @param name * new group name */ public void setName(String name) { myRow.setColumn("name", name); modifiedMetadata = true; addDetails("name"); } /** * add an eperson member * * @param e * eperson */ public void addMember(EPerson e) { loadData(); // make sure Group has data loaded if (isMember(e)) { return; } epeople.add(e); epeopleChanged = true; myContext.addEvent(new Event(Event.ADD, Constants.GROUP, getID(), Constants.EPERSON, e.getID(), e.getEmail())); } /** * add group to this group * * @param g */ public void addMember(Group g) { loadData(); // make sure Group has data loaded // don't add if it's already a member // and don't add itself if (isMember(g) || getID()==g.getID()) { return; } groups.add(g); groupsChanged = true; myContext.addEvent(new Event(Event.ADD, Constants.GROUP, getID(), Constants.GROUP, g.getID(), g.getName())); } /** * remove an eperson from a group * * @param e * eperson */ public void removeMember(EPerson e) { loadData(); // make sure Group has data loaded if (epeople.remove(e)) { epeopleChanged = true; myContext.addEvent(new Event(Event.REMOVE, Constants.GROUP, getID(), Constants.EPERSON, e.getID(), e.getEmail())); } } /** * remove group from this group * * @param g */ public void removeMember(Group g) { loadData(); // make sure Group has data loaded if (groups.remove(g)) { groupsChanged = true; myContext.addEvent(new Event(Event.REMOVE, Constants.GROUP, getID(), Constants.GROUP, g.getID(), g.getName())); } } /** * check to see if an eperson is a direct member. * If the eperson is a member via a subgroup will be returned <code>false</code> * * @param e * eperson to check membership */ public boolean isMember(EPerson e) { // special, group 0 is anonymous if (getID() == 0) { return true; } loadData(); // make sure Group has data loaded return epeople.contains(e); } /** * check to see if g is a direct group member. * If g is a subgroup via another group will be returned <code>false</code> * * @param g * group to check * @return */ public boolean isMember(Group g) { loadData(); // make sure Group has data loaded return groups.contains(g); } /** * fast check to see if an eperson is a member called with eperson id, does * database lookup without instantiating all of the epeople objects and is * thus a static method * * @param c * context * @param groupid * group ID to check */ public static boolean isMember(Context c, int groupid) throws SQLException { // special, everyone is member of group 0 (anonymous) if (groupid == 0) { return true; } EPerson currentuser = c.getCurrentUser(); return epersonInGroup(c, groupid, currentuser); } /** * Get all of the groups that an eperson is a member of * * @param c * @param e * @return * @throws SQLException */ public static Group[] allMemberGroups(Context c, EPerson e) throws SQLException { List<Group> groupList = new ArrayList<Group>(); Set<Integer> myGroups = allMemberGroupIDs(c, e); // now convert those Integers to Groups Iterator i = myGroups.iterator(); while (i.hasNext()) { groupList.add(Group.find(c, ((Integer) i.next()).intValue())); } return (Group[]) groupList.toArray(new Group[0]); } /** * get Set of Integers all of the group memberships for an eperson * * @param c * @param e * @return Set of Integer groupIDs * @throws SQLException */ public static Set<Integer> allMemberGroupIDs(Context c, EPerson e) throws SQLException { Set<Integer> groupIDs = new HashSet<Integer>(); if (e != null) { // two queries - first to get groups eperson is a member of // second query gets parent groups for groups eperson is a member of TableRowIterator tri = DatabaseManager.queryTable(c, "epersongroup2eperson", "SELECT * FROM epersongroup2eperson WHERE eperson_id= ?", e .getID()); try { while (tri.hasNext()) { TableRow row = tri.next(); int childID = row.getIntColumn("eperson_group_id"); groupIDs.add(new Integer(childID)); } } finally { // close the TableRowIterator to free up resources if (tri != null) tri.close(); } } // Also need to get all "Special Groups" user is a member of! // Otherwise, you're ignoring the user's membership to these groups! // However, we only do this is we are looking up the special groups // of the current user, as we cannot look up the special groups // of a user who is not logged in. - if (c.getCurrentUser().getID() == e.getID()) + if ((c.getCurrentUser() != null) && (c.getCurrentUser().getID() == e.getID())) { Group[] specialGroups = c.getSpecialGroups(); for(Group special : specialGroups) { groupIDs.add(new Integer(special.getID())); } } // all the users are members of the anonymous group groupIDs.add(new Integer(0)); // now we have all owning groups, also grab all parents of owning groups // yes, I know this could have been done as one big query and a union, // but doing the Oracle port taught me to keep to simple SQL! String groupQuery = ""; Iterator i = groupIDs.iterator(); // Build a list of query parameters Object[] parameters = new Object[groupIDs.size()]; int idx = 0; while (i.hasNext()) { int groupID = ((Integer) i.next()).intValue(); parameters[idx++] = new Integer(groupID); groupQuery += "child_id= ? "; if (i.hasNext()) groupQuery += " OR "; } // was member of at least one group // NOTE: even through the query is built dynamicaly all data is seperated into the // the parameters array. TableRowIterator tri = DatabaseManager.queryTable(c, "group2groupcache", "SELECT * FROM group2groupcache WHERE " + groupQuery, parameters); try { while (tri.hasNext()) { TableRow row = tri.next(); int parentID = row.getIntColumn("parent_id"); groupIDs.add(new Integer(parentID)); } } finally { // close the TableRowIterator to free up resources if (tri != null) tri.close(); } return groupIDs; } /** * Get all of the epeople who are a member of the * specified group, or a member of a sub-group of the * specified group, etc. * * @param c * DSpace context * @param g * Group object * @return Array of EPerson objects * @throws SQLException */ public static EPerson[] allMembers(Context c, Group g) throws SQLException { List<EPerson> epersonList = new ArrayList<EPerson>(); Set<Integer> myEpeople = allMemberIDs(c, g); // now convert those Integers to EPerson objects Iterator i = myEpeople.iterator(); while (i.hasNext()) { epersonList.add(EPerson.find(c, ((Integer) i.next()).intValue())); } return (EPerson[]) epersonList.toArray(new EPerson[0]); } /** * Get Set of all Integers all of the epeople * members for a group * * @param c * DSpace context * @param g * Group object * @return Set of Integer epersonIDs * @throws SQLException */ public static Set<Integer> allMemberIDs(Context c, Group g) throws SQLException { // two queries - first to get all groups which are a member of this group // second query gets all members of each group in the first query Set<Integer> epeopleIDs = new HashSet<Integer>(); // Get all groups which are a member of this group TableRowIterator tri = DatabaseManager.queryTable(c, "group2groupcache", "SELECT * FROM group2groupcache WHERE parent_id= ? ", g.getID()); Set<Integer> groupIDs = new HashSet<Integer>(); try { while (tri.hasNext()) { TableRow row = tri.next(); int childID = row.getIntColumn("child_id"); groupIDs.add(new Integer(childID)); } } finally { // close the TableRowIterator to free up resources if (tri != null) tri.close(); } // now we have all the groups (including this one) // it is time to find all the EPeople who belong to those groups // and filter out all duplicates Object[] parameters = new Object[groupIDs.size()+1]; int idx = 0; Iterator i = groupIDs.iterator(); // don't forget to add the current group to this query! parameters[idx++] = new Integer(g.getID()); String epersonQuery = "eperson_group_id= ? "; if (i.hasNext()) epersonQuery += " OR "; while (i.hasNext()) { int groupID = ((Integer) i.next()).intValue(); parameters[idx++] = new Integer(groupID); epersonQuery += "eperson_group_id= ? "; if (i.hasNext()) epersonQuery += " OR "; } //get all the EPerson IDs // Note: even through the query is dynamicaly built all data is seperated // into the parameters array. tri = DatabaseManager.queryTable(c, "epersongroup2eperson", "SELECT * FROM epersongroup2eperson WHERE " + epersonQuery, parameters); try { while (tri.hasNext()) { TableRow row = tri.next(); int epersonID = row.getIntColumn("eperson_id"); epeopleIDs.add(new Integer(epersonID)); } } finally { // close the TableRowIterator to free up resources if (tri != null) tri.close(); } return epeopleIDs; } private static boolean epersonInGroup(Context c, int groupID, EPerson e) throws SQLException { Set<Integer> groupIDs = Group.allMemberGroupIDs(c, e); return groupIDs.contains(new Integer(groupID)); } /** * find the group by its ID * * @param context * @param id */ public static Group find(Context context, int id) throws SQLException { // First check the cache Group fromCache = (Group) context.fromCache(Group.class, id); if (fromCache != null) { return fromCache; } TableRow row = DatabaseManager.find(context, "epersongroup", id); if (row == null) { return null; } else { return new Group(context, row); } } /** * Find the group by its name - assumes name is unique * * @param context * @param name * * @return Group */ public static Group findByName(Context context, String name) throws SQLException { TableRow row = DatabaseManager.findByUnique(context, "epersongroup", "name", name); if (row == null) { return null; } else { // First check the cache Group fromCache = (Group) context.fromCache(Group.class, row .getIntColumn("eperson_group_id")); if (fromCache != null) { return fromCache; } else { return new Group(context, row); } } } /** * Finds all groups in the site * * @param context * DSpace context * @param sortField * field to sort by -- Group.ID or Group.NAME * * @return array of all groups in the site */ public static Group[] findAll(Context context, int sortField) throws SQLException { String s; switch (sortField) { case ID: s = "eperson_group_id"; break; case NAME: s = "name"; break; default: s = "name"; } // NOTE: The use of 's' in the order by clause can not cause an sql // injection because the string is derived from constant values above. TableRowIterator rows = DatabaseManager.queryTable( context, "epersongroup", "SELECT * FROM epersongroup ORDER BY "+s); try { List gRows = rows.toList(); Group[] groups = new Group[gRows.size()]; for (int i = 0; i < gRows.size(); i++) { TableRow row = (TableRow) gRows.get(i); // First check the cache Group fromCache = (Group) context.fromCache(Group.class, row .getIntColumn("eperson_group_id")); if (fromCache != null) { groups[i] = fromCache; } else { groups[i] = new Group(context, row); } } return groups; } finally { if (rows != null) rows.close(); } } /** * Find the groups that match the search query across eperson_group_id or name * * @param context * DSpace context * @param query * The search string * * @return array of Group objects */ public static Group[] search(Context context, String query) throws SQLException { return search(context, query, -1, -1); } /** * Find the groups that match the search query across eperson_group_id or name * * @param context * DSpace context * @param query * The search string * @param offset * Inclusive offset * @param limit * Maximum number of matches returned * * @return array of Group objects */ public static Group[] search(Context context, String query, int offset, int limit) throws SQLException { String params = "%"+query.toLowerCase()+"%"; StringBuffer queryBuf = new StringBuffer(); queryBuf.append("SELECT * FROM epersongroup WHERE LOWER(name) LIKE LOWER(?) OR eperson_group_id = ? ORDER BY name ASC "); // Add offset and limit restrictions - Oracle requires special code if ("oracle".equals(ConfigurationManager.getProperty("db.name"))) { // First prepare the query to generate row numbers if (limit > 0 || offset > 0) { queryBuf.insert(0, "SELECT /*+ FIRST_ROWS(n) */ rec.*, ROWNUM rnum FROM ("); queryBuf.append(") "); } // Restrict the number of rows returned based on the limit if (limit > 0) { queryBuf.append("rec WHERE rownum<=? "); // If we also have an offset, then convert the limit into the maximum row number if (offset > 0) limit += offset; } // Return only the records after the specified offset (row number) if (offset > 0) { queryBuf.insert(0, "SELECT * FROM ("); queryBuf.append(") WHERE rnum>?"); } } else { if (limit > 0) queryBuf.append(" LIMIT ? "); if (offset > 0) queryBuf.append(" OFFSET ? "); } String dbquery = queryBuf.toString(); // When checking against the eperson-id, make sure the query can be made into a number Integer int_param; try { int_param = Integer.valueOf(query); } catch (NumberFormatException e) { int_param = new Integer(-1); } // Create the parameter array, including limit and offset if part of the query Object[] paramArr = new Object[]{params, int_param}; if (limit > 0 && offset > 0) paramArr = new Object[] {params, int_param,limit,offset}; else if (limit > 0) paramArr = new Object[] {params, int_param,limit}; else if (offset > 0) paramArr = new Object[] {params, int_param,offset}; TableRowIterator rows = DatabaseManager.query(context, dbquery, paramArr); try { List groupRows = rows.toList(); Group[] groups = new Group[groupRows.size()]; for (int i = 0; i < groupRows.size(); i++) { TableRow row = (TableRow) groupRows.get(i); // First check the cache Group fromCache = (Group) context.fromCache(Group.class, row .getIntColumn("eperson_group_id")); if (fromCache != null) { groups[i] = fromCache; } else { groups[i] = new Group(context, row); } } return groups; } finally { if (rows != null) rows.close(); } } /** * Returns the total number of groups returned by a specific query, without the overhead * of creating the Group objects to store the results. * * @param context * DSpace context * @param query * The search string * * @return the number of groups mathching the query */ public static int searchResultCount(Context context, String query) throws SQLException { String params = "%"+query.toLowerCase()+"%"; String dbquery = "SELECT count(*) as gcount FROM epersongroup WHERE LOWER(name) LIKE LOWER(?) OR eperson_group_id = ? "; // When checking against the eperson-id, make sure the query can be made into a number Integer int_param; try { int_param = Integer.valueOf(query); } catch (NumberFormatException e) { int_param = new Integer(-1); } // Get all the epeople that match the query TableRow row = DatabaseManager.querySingle(context, dbquery, new Object[] {params, int_param}); // use getIntColumn for Oracle count data Long count; if ("oracle".equals(ConfigurationManager.getProperty("db.name"))) { count = new Long(row.getIntColumn("gcount")); } else //getLongColumn works for postgres { count = new Long(row.getLongColumn("gcount")); } return count.intValue(); } /** * Delete a group * */ public void delete() throws SQLException { // FIXME: authorizations myContext.addEvent(new Event(Event.DELETE, Constants.GROUP, getID(), getName())); // Remove from cache myContext.removeCached(this, getID()); // Remove any ResourcePolicies that reference this group AuthorizeManager.removeGroupPolicies(myContext, getID()); // Remove any group memberships first DatabaseManager.updateQuery(myContext, "DELETE FROM EPersonGroup2EPerson WHERE eperson_group_id= ? ", getID()); // remove any group2groupcache entries DatabaseManager.updateQuery(myContext, "DELETE FROM group2groupcache WHERE parent_id= ? OR child_id= ? ", getID(),getID()); // Now remove any group2group assignments DatabaseManager.updateQuery(myContext, "DELETE FROM group2group WHERE parent_id= ? OR child_id= ? ", getID(),getID()); // don't forget the new table deleteEpersonGroup2WorkspaceItem(); // Remove ourself DatabaseManager.delete(myContext, myRow); epeople.clear(); log.info(LogManager.getHeader(myContext, "delete_group", "group_id=" + getID())); } /** * @throws SQLException */ private void deleteEpersonGroup2WorkspaceItem() throws SQLException { DatabaseManager.updateQuery(myContext, "DELETE FROM EPersonGroup2WorkspaceItem WHERE eperson_group_id= ? ", getID()); } /** * Return EPerson members of a Group */ public EPerson[] getMembers() { loadData(); // make sure all data is loaded EPerson[] myArray = new EPerson[epeople.size()]; myArray = (EPerson[]) epeople.toArray(myArray); return myArray; } /** * Return Group members of a Group * * @return */ public Group[] getMemberGroups() { loadData(); // make sure all data is loaded Group[] myArray = new Group[groups.size()]; myArray = (Group[]) groups.toArray(myArray); return myArray; } /** * Return true if group has no direct or indirect members */ public boolean isEmpty() { loadData(); // make sure all data is loaded // the only fast check available is on epeople... boolean hasMembers = (epeople.size() != 0); if (hasMembers) { return false; } else { // well, groups is never null... for (Group subGroup : groups){ hasMembers = !subGroup.isEmpty(); if (hasMembers){ return false; } } return !hasMembers; } } /** * Update the group - writing out group object and EPerson list if necessary */ public void update() throws SQLException, AuthorizeException { // FIXME: Check authorisation DatabaseManager.update(myContext, myRow); if (modifiedMetadata) { myContext.addEvent(new Event(Event.MODIFY_METADATA, Constants.GROUP, getID(), getDetails())); modifiedMetadata = false; clearDetails(); } // Redo eperson mappings if they've changed if (epeopleChanged) { // Remove any existing mappings DatabaseManager.updateQuery(myContext, "delete from epersongroup2eperson where eperson_group_id= ? ", getID()); // Add new mappings Iterator i = epeople.iterator(); while (i.hasNext()) { EPerson e = (EPerson) i.next(); TableRow mappingRow = DatabaseManager.create(myContext, "epersongroup2eperson"); mappingRow.setColumn("eperson_id", e.getID()); mappingRow.setColumn("eperson_group_id", getID()); DatabaseManager.update(myContext, mappingRow); } epeopleChanged = false; } // Redo Group mappings if they've changed if (groupsChanged) { // Remove any existing mappings DatabaseManager.updateQuery(myContext, "delete from group2group where parent_id= ? ", getID()); // Add new mappings Iterator i = groups.iterator(); while (i.hasNext()) { Group g = (Group) i.next(); TableRow mappingRow = DatabaseManager.create(myContext, "group2group"); mappingRow.setColumn("parent_id", getID()); mappingRow.setColumn("child_id", g.getID()); DatabaseManager.update(myContext, mappingRow); } // groups changed, now change group cache rethinkGroupCache(); groupsChanged = false; } log.info(LogManager.getHeader(myContext, "update_group", "group_id=" + getID())); } /** * Return <code>true</code> if <code>other</code> is the same Group as * this object, <code>false</code> otherwise * * @param other * object to compare to * * @return <code>true</code> if object passed in represents the same group * as this object */ public boolean equals(Object other) { if (!(other instanceof Group)) { return false; } return (getID() == ((Group) other).getID()); } public int getType() { return Constants.GROUP; } public String getHandle() { return null; } /** * Regenerate the group cache AKA the group2groupcache table in the database - * meant to be called when a group is added or removed from another group * */ private void rethinkGroupCache() throws SQLException { // read in the group2group table TableRowIterator tri = DatabaseManager.queryTable(myContext, "group2group", "SELECT * FROM group2group"); Map<Integer,Set<Integer>> parents = new HashMap<Integer,Set<Integer>>(); try { while (tri.hasNext()) { TableRow row = (TableRow) tri.next(); Integer parentID = new Integer(row.getIntColumn("parent_id")); Integer childID = new Integer(row.getIntColumn("child_id")); // if parent doesn't have an entry, create one if (!parents.containsKey(parentID)) { Set<Integer> children = new HashSet<Integer>(); // add child id to the list children.add(childID); parents.put(parentID, children); } else { // parent has an entry, now add the child to the parent's record // of children Set<Integer> children = parents.get(parentID); children.add(childID); } } } finally { // close the TableRowIterator to free up resources if (tri != null) tri.close(); } // now parents is a hash of all of the IDs of groups that are parents // and each hash entry is a hash of all of the IDs of children of those // parent groups // so now to establish all parent,child relationships we can iterate // through the parents hash Iterator i = parents.keySet().iterator(); while (i.hasNext()) { Integer parentID = (Integer) i.next(); Set<Integer> myChildren = getChildren(parents, parentID); Iterator j = myChildren.iterator(); while (j.hasNext()) { // child of a parent Integer childID = (Integer) j.next(); ((Set<Integer>) parents.get(parentID)).add(childID); } } // empty out group2groupcache table DatabaseManager.updateQuery(myContext, "DELETE FROM group2groupcache WHERE id >= 0"); // write out new one Iterator pi = parents.keySet().iterator(); // parent iterator while (pi.hasNext()) { Integer parent = (Integer) pi.next(); Set<Integer> children = parents.get(parent); Iterator ci = children.iterator(); // child iterator while (ci.hasNext()) { Integer child = (Integer) ci.next(); TableRow row = DatabaseManager.create(myContext, "group2groupcache"); int parentID = parent.intValue(); int childID = child.intValue(); row.setColumn("parent_id", parentID); row.setColumn("child_id", childID); DatabaseManager.update(myContext, row); } } } /** * Used recursively to generate a map of ALL of the children of the given * parent * * @param parents * Map of parent,child relationships * @param parent * the parent you're interested in * @return Map whose keys are all of the children of a parent */ private Set<Integer> getChildren(Map<Integer,Set<Integer>> parents, Integer parent) { Set<Integer> myChildren = new HashSet<Integer>(); // degenerate case, this parent has no children if (!parents.containsKey(parent)) return myChildren; // got this far, so we must have children Set<Integer> children = parents.get(parent); // now iterate over all of the children Iterator i = children.iterator(); while (i.hasNext()) { Integer childID = (Integer) i.next(); // add this child's ID to our return set myChildren.add(childID); // and now its children myChildren.addAll(getChildren(parents, childID)); } return myChildren; } }
true
true
public static Set<Integer> allMemberGroupIDs(Context c, EPerson e) throws SQLException { Set<Integer> groupIDs = new HashSet<Integer>(); if (e != null) { // two queries - first to get groups eperson is a member of // second query gets parent groups for groups eperson is a member of TableRowIterator tri = DatabaseManager.queryTable(c, "epersongroup2eperson", "SELECT * FROM epersongroup2eperson WHERE eperson_id= ?", e .getID()); try { while (tri.hasNext()) { TableRow row = tri.next(); int childID = row.getIntColumn("eperson_group_id"); groupIDs.add(new Integer(childID)); } } finally { // close the TableRowIterator to free up resources if (tri != null) tri.close(); } } // Also need to get all "Special Groups" user is a member of! // Otherwise, you're ignoring the user's membership to these groups! // However, we only do this is we are looking up the special groups // of the current user, as we cannot look up the special groups // of a user who is not logged in. if (c.getCurrentUser().getID() == e.getID()) { Group[] specialGroups = c.getSpecialGroups(); for(Group special : specialGroups) { groupIDs.add(new Integer(special.getID())); } } // all the users are members of the anonymous group groupIDs.add(new Integer(0)); // now we have all owning groups, also grab all parents of owning groups // yes, I know this could have been done as one big query and a union, // but doing the Oracle port taught me to keep to simple SQL! String groupQuery = ""; Iterator i = groupIDs.iterator(); // Build a list of query parameters Object[] parameters = new Object[groupIDs.size()]; int idx = 0; while (i.hasNext()) { int groupID = ((Integer) i.next()).intValue(); parameters[idx++] = new Integer(groupID); groupQuery += "child_id= ? "; if (i.hasNext()) groupQuery += " OR "; } // was member of at least one group // NOTE: even through the query is built dynamicaly all data is seperated into the // the parameters array. TableRowIterator tri = DatabaseManager.queryTable(c, "group2groupcache", "SELECT * FROM group2groupcache WHERE " + groupQuery, parameters); try { while (tri.hasNext()) { TableRow row = tri.next(); int parentID = row.getIntColumn("parent_id"); groupIDs.add(new Integer(parentID)); } } finally { // close the TableRowIterator to free up resources if (tri != null) tri.close(); } return groupIDs; }
public static Set<Integer> allMemberGroupIDs(Context c, EPerson e) throws SQLException { Set<Integer> groupIDs = new HashSet<Integer>(); if (e != null) { // two queries - first to get groups eperson is a member of // second query gets parent groups for groups eperson is a member of TableRowIterator tri = DatabaseManager.queryTable(c, "epersongroup2eperson", "SELECT * FROM epersongroup2eperson WHERE eperson_id= ?", e .getID()); try { while (tri.hasNext()) { TableRow row = tri.next(); int childID = row.getIntColumn("eperson_group_id"); groupIDs.add(new Integer(childID)); } } finally { // close the TableRowIterator to free up resources if (tri != null) tri.close(); } } // Also need to get all "Special Groups" user is a member of! // Otherwise, you're ignoring the user's membership to these groups! // However, we only do this is we are looking up the special groups // of the current user, as we cannot look up the special groups // of a user who is not logged in. if ((c.getCurrentUser() != null) && (c.getCurrentUser().getID() == e.getID())) { Group[] specialGroups = c.getSpecialGroups(); for(Group special : specialGroups) { groupIDs.add(new Integer(special.getID())); } } // all the users are members of the anonymous group groupIDs.add(new Integer(0)); // now we have all owning groups, also grab all parents of owning groups // yes, I know this could have been done as one big query and a union, // but doing the Oracle port taught me to keep to simple SQL! String groupQuery = ""; Iterator i = groupIDs.iterator(); // Build a list of query parameters Object[] parameters = new Object[groupIDs.size()]; int idx = 0; while (i.hasNext()) { int groupID = ((Integer) i.next()).intValue(); parameters[idx++] = new Integer(groupID); groupQuery += "child_id= ? "; if (i.hasNext()) groupQuery += " OR "; } // was member of at least one group // NOTE: even through the query is built dynamicaly all data is seperated into the // the parameters array. TableRowIterator tri = DatabaseManager.queryTable(c, "group2groupcache", "SELECT * FROM group2groupcache WHERE " + groupQuery, parameters); try { while (tri.hasNext()) { TableRow row = tri.next(); int parentID = row.getIntColumn("parent_id"); groupIDs.add(new Integer(parentID)); } } finally { // close the TableRowIterator to free up resources if (tri != null) tri.close(); } return groupIDs; }
diff --git a/src/web/wcs/src/main/java/org/geoserver/wcs/web/WCSAdminPage.java b/src/web/wcs/src/main/java/org/geoserver/wcs/web/WCSAdminPage.java index e3bf1f77c6..170f2aa088 100644 --- a/src/web/wcs/src/main/java/org/geoserver/wcs/web/WCSAdminPage.java +++ b/src/web/wcs/src/main/java/org/geoserver/wcs/web/WCSAdminPage.java @@ -1,55 +1,55 @@ /* Copyright (c) 2001 - 2007 TOPP - www.openplans.org. All rights reserved. * This code is licensed under the GPL 2.0 license, available at the root * application directory. */ package org.geoserver.wcs.web; import java.util.Arrays; import org.apache.wicket.markup.html.form.CheckBox; import org.apache.wicket.markup.html.form.DropDownChoice; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.IChoiceRenderer; import org.apache.wicket.markup.html.form.TextField; import org.apache.wicket.model.IModel; import org.apache.wicket.model.StringResourceModel; import org.apache.wicket.validation.validator.MinimumValidator; import org.geoserver.wcs.WCSInfo; import org.geoserver.web.services.BaseServiceAdminPage; import org.geotools.coverage.grid.io.OverviewPolicy; public class WCSAdminPage extends BaseServiceAdminPage<WCSInfo> { protected Class<WCSInfo> getServiceClass() { return WCSInfo.class; } protected void build(IModel info, Form form) { // overview policy form.add(new DropDownChoice("overviewPolicy", Arrays.asList(OverviewPolicy.values()), new OverviewPolicyRenderer())); form.add(new CheckBox("subsamplingEnabled")); // resource limits TextField maxInputMemory = new TextField("maxInputMemory"); - maxInputMemory.add(new MinimumValidator(0.0)); + maxInputMemory.add(new MinimumValidator(0l)); form.add(maxInputMemory); TextField maxOutputMemory = new TextField("maxOutputMemory"); - maxOutputMemory.add(new MinimumValidator(0.0)); + maxOutputMemory.add(new MinimumValidator(0l)); form.add(maxOutputMemory); } protected String getServiceName(){ return "WCS"; } private class OverviewPolicyRenderer implements IChoiceRenderer { public Object getDisplayValue(Object object) { return new StringResourceModel(((OverviewPolicy) object).name(), WCSAdminPage.this, null).getString(); } public String getIdValue(Object object, int index) { return ((OverviewPolicy) object).name(); } } }
false
true
protected void build(IModel info, Form form) { // overview policy form.add(new DropDownChoice("overviewPolicy", Arrays.asList(OverviewPolicy.values()), new OverviewPolicyRenderer())); form.add(new CheckBox("subsamplingEnabled")); // resource limits TextField maxInputMemory = new TextField("maxInputMemory"); maxInputMemory.add(new MinimumValidator(0.0)); form.add(maxInputMemory); TextField maxOutputMemory = new TextField("maxOutputMemory"); maxOutputMemory.add(new MinimumValidator(0.0)); form.add(maxOutputMemory); }
protected void build(IModel info, Form form) { // overview policy form.add(new DropDownChoice("overviewPolicy", Arrays.asList(OverviewPolicy.values()), new OverviewPolicyRenderer())); form.add(new CheckBox("subsamplingEnabled")); // resource limits TextField maxInputMemory = new TextField("maxInputMemory"); maxInputMemory.add(new MinimumValidator(0l)); form.add(maxInputMemory); TextField maxOutputMemory = new TextField("maxOutputMemory"); maxOutputMemory.add(new MinimumValidator(0l)); form.add(maxOutputMemory); }
diff --git a/PartManager.java b/PartManager.java index 606b087..e3dc09e 100644 --- a/PartManager.java +++ b/PartManager.java @@ -1,294 +1,287 @@ import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; @SuppressWarnings("serial") public class PartManager extends JPanel { /** PartsClient variable which will sent Msg classes to the server when a button is pressed */ private PartsClient myClient; /** layout for part manager*/ private JPanel myLayout; /** print text in a label "part name:" */ private JLabel pName; /** print text in a label "part number:" */ private JLabel pNumber; /** print text in a label "part info:" */ private JLabel pInfo; /** print text in a label "part image:" */ private JLabel pImage; /** print text in a label "Number of part to be changed/deleted" */ private JLabel pEdit; /** print text in a label "Part will be changed to new part above" */ private JLabel pEdit2; /** textfield for prompting part name */ private JTextField tName; /** textfield for prompting part number */ private JTextField tNumber; /** textfield for prompting part description */ private JTextField tInfo; /** textfield for prompting the number of part he wants to change */ private JTextField tEdit; /** create button to create a part */ private JButton create; /** change button to change a part */ private JButton change; /** delete button to delete a part */ private JButton delete; /** scroll pane that stored parts */ private JScrollPane scroll; /** panel that contains all of the available parts */ private JPanel parts; /** print error message */ private JLabel msg; /** JComboBox for selecting images */ private JComboBox imageCB; /** Array to link indices in the parts combobox to their ImageEnum */ private ArrayList<Painter.ImageEnum> imgEnumList; /** Title of Client */ private JLabel title; /** Frame for title */ private JPanel titleFrame; /** initialization*/ public PartManager( PartsClient pc ){ myClient = pc; Painter.loadImages(); myLayout = new JPanel(); pName = new JLabel("Part Name: "); pNumber = new JLabel("Part Number: "); pInfo = new JLabel("Part Info: "); pImage = new JLabel("Part Image: "); pEdit = new JLabel("Number of part to be changed/deleted: "); pEdit2 = new JLabel("Part will be changed to new part above"); tName = new JTextField(10); tNumber = new JTextField(10); tInfo = new JTextField(10); tEdit = new JTextField(10); create = new JButton("Create"); change = new JButton("Change"); delete = new JButton("Delete"); msg = new JLabel(""); pName.setForeground(Color.BLACK.darker()); - pName.setFont( new Font( "Serif", Font.BOLD, 16 ) ); pNumber.setForeground(Color.BLACK.darker()); - pNumber.setFont( new Font( "Serif", Font.BOLD, 16 ) ); pInfo.setForeground(Color.BLACK.darker()); - pInfo.setFont( new Font( "Serif", Font.BOLD, 16 ) ); pImage.setForeground(Color.BLACK.darker()); - pImage.setFont( new Font( "Serif", Font.BOLD, 16 ) ); pEdit.setForeground(Color.BLACK.darker()); - pEdit.setFont( new Font( "Serif", Font.BOLD, 16 ) ); pEdit2.setForeground(Color.BLACK.darker()); - pEdit2.setFont( new Font( "Serif", Font.BOLD, 16 ) ); msg.setForeground(Color.RED.darker()); - msg.setFont( new Font( "Serif", Font.BOLD, 16 ) ); title = new JLabel( "Part Manager" ); title.setFont( new Font( "Serif", Font.BOLD, 30 ) ); title.setForeground(Color.BLACK.darker()); JPanel titleFrame = new JPanel(); titleFrame.add(title); titleFrame.setBorder( BorderFactory.createLineBorder( Color.black ) ); imageCB = new JComboBox(); imgEnumList = new ArrayList<Painter.ImageEnum>(); int i = 0; for ( Painter.ImageEnum en : Painter.ImageEnum.values() ) { if(i >= Painter.NUMPARTS){ break; } ImageIcon img = new ImageIcon( ( ( Painter.getImageIcon(en).getImage() ).getScaledInstance( 25, 25, java.awt.Image.SCALE_SMOOTH ) ) ); //add images to JComboBox imageCB.addItem(img); imgEnumList.add(en); ++i; } //JScrollPane for list of parts parts = new JPanel(); parts.setLayout( new GridBagLayout() ); scroll = new JScrollPane(parts); //layout GUI myLayout.setLayout( new GridBagLayout() ); GridBagConstraints c = new GridBagConstraints(); //parts scroll pane c.fill = GridBagConstraints.BOTH; c.gridx = 0; c.gridy = 0; c.weightx = 1; c.weighty = 0; c.gridwidth = 2; c.gridheight = 10; myLayout.add( scroll, c ); //adding parts c.fill = GridBagConstraints.HORIZONTAL; c.insets = new Insets(20,10,0,0); c.gridx = 2; c.gridy = 0; c.weightx = 0; c.gridwidth = 1; c.gridheight = 1; myLayout.add( pName, c ); c.gridx = 2; c.gridy = 1; myLayout.add( pNumber, c ); c.gridx = 2; c.gridy = 2; myLayout.add( pInfo, c ); c.gridx = 2; c.gridy = 3; myLayout.add( pImage, c ); c.gridx = 3; c.gridy = 0; myLayout.add( tName, c ); c.gridx = 3; c.gridy = 1; myLayout.add( tNumber, c ); c.gridx = 3; c.gridy = 2; myLayout.add( tInfo, c ); c.gridx = 4; c.gridy = 1; myLayout.add( create, c ); c.gridx = 3; c.gridy = 3; myLayout.add( imageCB, c ); //changing/deleting parts c.gridx = 2; c.gridy = 5; myLayout.add( pEdit, c ); c.gridx = 3; c.gridy = 4; myLayout.add( pEdit2, c ); c.gridx = 3; c.gridy = 5; myLayout.add( tEdit, c ); c.gridheight = 1; c.gridx = 4; c.gridy = 4; myLayout.add( change, c ); c.gridx = 4; c.gridy = 5; myLayout.add( delete, c ); //messages c.gridx = 2; c.gridy = 6; c.gridwidth = 3; myLayout.add( msg, c ); //layout onto manager setLayout( new BorderLayout() ); add( myLayout, BorderLayout.CENTER ); add( titleFrame, BorderLayout.NORTH ); titleFrame.setOpaque(false); myLayout.setOpaque(false); //setBackground(Color.WHITE); //action listeners for buttons create.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ){ if( !tName.getText().equals("") && !tInfo.getText().equals("") && !tNumber.getText().equals("") ) { try{ //add part to server myClient.getCom().write( new NewPartMsg( new Part( tName.getText(), tInfo.getText(), (int)Integer.parseInt( tNumber.getText() ), imgEnumList.get(imageCB.getSelectedIndex()) ) ) ); } catch (NumberFormatException nfe) { msg.setText( "Please enter a number for Part Number" ); } } else { msg.setText( "Please enter all part information" ); } } }); change.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ){ if( !tName.getText().equals("") && !tInfo.getText().equals("") && !tNumber.getText().equals("") && !tEdit.getText().equals("") ) { try{ //replace part number X with new part myClient.getCom().write( new ChangePartMsg( (int)Integer.parseInt( tEdit.getText() ), new Part( tName.getText(), tInfo.getText(), (int)Integer.parseInt( tNumber.getText() ), imgEnumList.get(imageCB.getSelectedIndex()) ) ) ); } catch (NumberFormatException nfe) { msg.setText( "Please enter a number for part to be changed" ); } } else if( tEdit.getText().equals("") ) { msg.setText( "Please enter part number of part to be changed." ); } else { msg.setText( "Please enter all part information" ); } } }); delete.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ){ if( !tEdit.getText().equals("") ) { try { //delete the part on the server myClient.getCom().write( new DeletePartMsg( (int)Integer.parseInt( tEdit.getText() ) ) ); } catch (NumberFormatException nfe) { msg.setText( "Please enter a number for part to be deleted" ); } } else { msg.setText( "Please enter part number of part to be deleted." ); } } }); } /** regenerate parts label in parts panel */ public void displayParts(){ //remove current list from the panel parts.removeAll(); //add new list to panel ArrayList<Part> temp = myClient.getParts(); //constraints GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; for( Part p : temp ){ parts.add( new JLabel( Painter.getImageIcon(p.getImage())), c ); c.gridx++; parts.add( new JLabel( p.getNumber() + " - " + p.getName() + " - " + p.getDescription() ), c ); c.gridx--; c.gridy++; } validate(); repaint(); } public void setMsg( String s ){ msg.setText(s); } public void paintComponent( Graphics gfx ){ super.paintComponents(gfx); gfx.drawImage( Painter.getImageIcon(Painter.ImageEnum.BACKGROUND).getImage(), 0, 0, null); } }
false
true
public PartManager( PartsClient pc ){ myClient = pc; Painter.loadImages(); myLayout = new JPanel(); pName = new JLabel("Part Name: "); pNumber = new JLabel("Part Number: "); pInfo = new JLabel("Part Info: "); pImage = new JLabel("Part Image: "); pEdit = new JLabel("Number of part to be changed/deleted: "); pEdit2 = new JLabel("Part will be changed to new part above"); tName = new JTextField(10); tNumber = new JTextField(10); tInfo = new JTextField(10); tEdit = new JTextField(10); create = new JButton("Create"); change = new JButton("Change"); delete = new JButton("Delete"); msg = new JLabel(""); pName.setForeground(Color.BLACK.darker()); pName.setFont( new Font( "Serif", Font.BOLD, 16 ) ); pNumber.setForeground(Color.BLACK.darker()); pNumber.setFont( new Font( "Serif", Font.BOLD, 16 ) ); pInfo.setForeground(Color.BLACK.darker()); pInfo.setFont( new Font( "Serif", Font.BOLD, 16 ) ); pImage.setForeground(Color.BLACK.darker()); pImage.setFont( new Font( "Serif", Font.BOLD, 16 ) ); pEdit.setForeground(Color.BLACK.darker()); pEdit.setFont( new Font( "Serif", Font.BOLD, 16 ) ); pEdit2.setForeground(Color.BLACK.darker()); pEdit2.setFont( new Font( "Serif", Font.BOLD, 16 ) ); msg.setForeground(Color.RED.darker()); msg.setFont( new Font( "Serif", Font.BOLD, 16 ) ); title = new JLabel( "Part Manager" ); title.setFont( new Font( "Serif", Font.BOLD, 30 ) ); title.setForeground(Color.BLACK.darker()); JPanel titleFrame = new JPanel(); titleFrame.add(title); titleFrame.setBorder( BorderFactory.createLineBorder( Color.black ) ); imageCB = new JComboBox(); imgEnumList = new ArrayList<Painter.ImageEnum>(); int i = 0; for ( Painter.ImageEnum en : Painter.ImageEnum.values() ) { if(i >= Painter.NUMPARTS){ break; } ImageIcon img = new ImageIcon( ( ( Painter.getImageIcon(en).getImage() ).getScaledInstance( 25, 25, java.awt.Image.SCALE_SMOOTH ) ) ); //add images to JComboBox imageCB.addItem(img); imgEnumList.add(en); ++i; } //JScrollPane for list of parts parts = new JPanel(); parts.setLayout( new GridBagLayout() ); scroll = new JScrollPane(parts); //layout GUI myLayout.setLayout( new GridBagLayout() ); GridBagConstraints c = new GridBagConstraints(); //parts scroll pane c.fill = GridBagConstraints.BOTH; c.gridx = 0; c.gridy = 0; c.weightx = 1; c.weighty = 0; c.gridwidth = 2; c.gridheight = 10; myLayout.add( scroll, c ); //adding parts c.fill = GridBagConstraints.HORIZONTAL; c.insets = new Insets(20,10,0,0); c.gridx = 2; c.gridy = 0; c.weightx = 0; c.gridwidth = 1; c.gridheight = 1; myLayout.add( pName, c ); c.gridx = 2; c.gridy = 1; myLayout.add( pNumber, c ); c.gridx = 2; c.gridy = 2; myLayout.add( pInfo, c ); c.gridx = 2; c.gridy = 3; myLayout.add( pImage, c ); c.gridx = 3; c.gridy = 0; myLayout.add( tName, c ); c.gridx = 3; c.gridy = 1; myLayout.add( tNumber, c ); c.gridx = 3; c.gridy = 2; myLayout.add( tInfo, c ); c.gridx = 4; c.gridy = 1; myLayout.add( create, c ); c.gridx = 3; c.gridy = 3; myLayout.add( imageCB, c ); //changing/deleting parts c.gridx = 2; c.gridy = 5; myLayout.add( pEdit, c ); c.gridx = 3; c.gridy = 4; myLayout.add( pEdit2, c ); c.gridx = 3; c.gridy = 5; myLayout.add( tEdit, c ); c.gridheight = 1; c.gridx = 4; c.gridy = 4; myLayout.add( change, c ); c.gridx = 4; c.gridy = 5; myLayout.add( delete, c ); //messages c.gridx = 2; c.gridy = 6; c.gridwidth = 3; myLayout.add( msg, c ); //layout onto manager setLayout( new BorderLayout() ); add( myLayout, BorderLayout.CENTER ); add( titleFrame, BorderLayout.NORTH ); titleFrame.setOpaque(false); myLayout.setOpaque(false); //setBackground(Color.WHITE); //action listeners for buttons create.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ){ if( !tName.getText().equals("") && !tInfo.getText().equals("") && !tNumber.getText().equals("") ) { try{ //add part to server myClient.getCom().write( new NewPartMsg( new Part( tName.getText(), tInfo.getText(), (int)Integer.parseInt( tNumber.getText() ), imgEnumList.get(imageCB.getSelectedIndex()) ) ) ); } catch (NumberFormatException nfe) { msg.setText( "Please enter a number for Part Number" ); } } else { msg.setText( "Please enter all part information" ); } } }); change.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ){ if( !tName.getText().equals("") && !tInfo.getText().equals("") && !tNumber.getText().equals("") && !tEdit.getText().equals("") ) { try{ //replace part number X with new part myClient.getCom().write( new ChangePartMsg( (int)Integer.parseInt( tEdit.getText() ), new Part( tName.getText(), tInfo.getText(), (int)Integer.parseInt( tNumber.getText() ), imgEnumList.get(imageCB.getSelectedIndex()) ) ) ); } catch (NumberFormatException nfe) { msg.setText( "Please enter a number for part to be changed" ); } } else if( tEdit.getText().equals("") ) { msg.setText( "Please enter part number of part to be changed." ); } else { msg.setText( "Please enter all part information" ); } } }); delete.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ){ if( !tEdit.getText().equals("") ) { try { //delete the part on the server myClient.getCom().write( new DeletePartMsg( (int)Integer.parseInt( tEdit.getText() ) ) ); } catch (NumberFormatException nfe) { msg.setText( "Please enter a number for part to be deleted" ); } } else { msg.setText( "Please enter part number of part to be deleted." ); } } }); }
public PartManager( PartsClient pc ){ myClient = pc; Painter.loadImages(); myLayout = new JPanel(); pName = new JLabel("Part Name: "); pNumber = new JLabel("Part Number: "); pInfo = new JLabel("Part Info: "); pImage = new JLabel("Part Image: "); pEdit = new JLabel("Number of part to be changed/deleted: "); pEdit2 = new JLabel("Part will be changed to new part above"); tName = new JTextField(10); tNumber = new JTextField(10); tInfo = new JTextField(10); tEdit = new JTextField(10); create = new JButton("Create"); change = new JButton("Change"); delete = new JButton("Delete"); msg = new JLabel(""); pName.setForeground(Color.BLACK.darker()); pNumber.setForeground(Color.BLACK.darker()); pInfo.setForeground(Color.BLACK.darker()); pImage.setForeground(Color.BLACK.darker()); pEdit.setForeground(Color.BLACK.darker()); pEdit2.setForeground(Color.BLACK.darker()); msg.setForeground(Color.RED.darker()); title = new JLabel( "Part Manager" ); title.setFont( new Font( "Serif", Font.BOLD, 30 ) ); title.setForeground(Color.BLACK.darker()); JPanel titleFrame = new JPanel(); titleFrame.add(title); titleFrame.setBorder( BorderFactory.createLineBorder( Color.black ) ); imageCB = new JComboBox(); imgEnumList = new ArrayList<Painter.ImageEnum>(); int i = 0; for ( Painter.ImageEnum en : Painter.ImageEnum.values() ) { if(i >= Painter.NUMPARTS){ break; } ImageIcon img = new ImageIcon( ( ( Painter.getImageIcon(en).getImage() ).getScaledInstance( 25, 25, java.awt.Image.SCALE_SMOOTH ) ) ); //add images to JComboBox imageCB.addItem(img); imgEnumList.add(en); ++i; } //JScrollPane for list of parts parts = new JPanel(); parts.setLayout( new GridBagLayout() ); scroll = new JScrollPane(parts); //layout GUI myLayout.setLayout( new GridBagLayout() ); GridBagConstraints c = new GridBagConstraints(); //parts scroll pane c.fill = GridBagConstraints.BOTH; c.gridx = 0; c.gridy = 0; c.weightx = 1; c.weighty = 0; c.gridwidth = 2; c.gridheight = 10; myLayout.add( scroll, c ); //adding parts c.fill = GridBagConstraints.HORIZONTAL; c.insets = new Insets(20,10,0,0); c.gridx = 2; c.gridy = 0; c.weightx = 0; c.gridwidth = 1; c.gridheight = 1; myLayout.add( pName, c ); c.gridx = 2; c.gridy = 1; myLayout.add( pNumber, c ); c.gridx = 2; c.gridy = 2; myLayout.add( pInfo, c ); c.gridx = 2; c.gridy = 3; myLayout.add( pImage, c ); c.gridx = 3; c.gridy = 0; myLayout.add( tName, c ); c.gridx = 3; c.gridy = 1; myLayout.add( tNumber, c ); c.gridx = 3; c.gridy = 2; myLayout.add( tInfo, c ); c.gridx = 4; c.gridy = 1; myLayout.add( create, c ); c.gridx = 3; c.gridy = 3; myLayout.add( imageCB, c ); //changing/deleting parts c.gridx = 2; c.gridy = 5; myLayout.add( pEdit, c ); c.gridx = 3; c.gridy = 4; myLayout.add( pEdit2, c ); c.gridx = 3; c.gridy = 5; myLayout.add( tEdit, c ); c.gridheight = 1; c.gridx = 4; c.gridy = 4; myLayout.add( change, c ); c.gridx = 4; c.gridy = 5; myLayout.add( delete, c ); //messages c.gridx = 2; c.gridy = 6; c.gridwidth = 3; myLayout.add( msg, c ); //layout onto manager setLayout( new BorderLayout() ); add( myLayout, BorderLayout.CENTER ); add( titleFrame, BorderLayout.NORTH ); titleFrame.setOpaque(false); myLayout.setOpaque(false); //setBackground(Color.WHITE); //action listeners for buttons create.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ){ if( !tName.getText().equals("") && !tInfo.getText().equals("") && !tNumber.getText().equals("") ) { try{ //add part to server myClient.getCom().write( new NewPartMsg( new Part( tName.getText(), tInfo.getText(), (int)Integer.parseInt( tNumber.getText() ), imgEnumList.get(imageCB.getSelectedIndex()) ) ) ); } catch (NumberFormatException nfe) { msg.setText( "Please enter a number for Part Number" ); } } else { msg.setText( "Please enter all part information" ); } } }); change.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ){ if( !tName.getText().equals("") && !tInfo.getText().equals("") && !tNumber.getText().equals("") && !tEdit.getText().equals("") ) { try{ //replace part number X with new part myClient.getCom().write( new ChangePartMsg( (int)Integer.parseInt( tEdit.getText() ), new Part( tName.getText(), tInfo.getText(), (int)Integer.parseInt( tNumber.getText() ), imgEnumList.get(imageCB.getSelectedIndex()) ) ) ); } catch (NumberFormatException nfe) { msg.setText( "Please enter a number for part to be changed" ); } } else if( tEdit.getText().equals("") ) { msg.setText( "Please enter part number of part to be changed." ); } else { msg.setText( "Please enter all part information" ); } } }); delete.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ){ if( !tEdit.getText().equals("") ) { try { //delete the part on the server myClient.getCom().write( new DeletePartMsg( (int)Integer.parseInt( tEdit.getText() ) ) ); } catch (NumberFormatException nfe) { msg.setText( "Please enter a number for part to be deleted" ); } } else { msg.setText( "Please enter part number of part to be deleted." ); } } }); }
diff --git a/EnrichmentAnalysisUI/src/org/mongkie/ui/enrichment/EnrichmentChooserTopComponent.java b/EnrichmentAnalysisUI/src/org/mongkie/ui/enrichment/EnrichmentChooserTopComponent.java index 3840160..dd098a3 100644 --- a/EnrichmentAnalysisUI/src/org/mongkie/ui/enrichment/EnrichmentChooserTopComponent.java +++ b/EnrichmentAnalysisUI/src/org/mongkie/ui/enrichment/EnrichmentChooserTopComponent.java @@ -1,478 +1,479 @@ /* * This file is part of MONGKIE. Visit <http://www.mongkie.org/> for details. * Copyright (C) 2011 Korean Bioinformation Center(KOBIC) * * MONGKIE 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. * * MONGKIE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.mongkie.ui.enrichment; import java.awt.BorderLayout; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import javax.swing.DefaultComboBoxModel; import javax.swing.SwingUtilities; import static kobic.prefuse.Constants.NODES; import kobic.prefuse.display.DisplayListener; import org.mongkie.enrichment.EnrichmentController; import org.mongkie.enrichment.EnrichmentModel; import org.mongkie.enrichment.EnrichmentModelListener; import org.mongkie.enrichment.spi.Enrichment; import org.mongkie.enrichment.spi.EnrichmentBuilder; import static org.mongkie.visualization.Config.MODE_ACTION; import static org.mongkie.visualization.Config.ROLE_NETWORK; import org.mongkie.visualization.MongkieDisplay; import org.mongkie.visualization.workspace.ModelChangeListener; import org.netbeans.api.settings.ConvertAsProperties; import org.openide.DialogDisplayer; import org.openide.NotifyDescriptor; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.util.ImageUtilities; import org.openide.util.Lookup; import org.openide.util.NbBundle; import org.openide.windows.TopComponent; import prefuse.Visualization; import prefuse.data.Graph; import prefuse.data.Table; import prefuse.data.Tuple; import static prefuse.data.event.EventConstants.*; import prefuse.data.event.TableListener; /** * * @author Yeongjun Jang <[email protected]> */ @ConvertAsProperties(dtd = "-//org.mongkie.ui.enrichment//EnrichmentChooser//EN", autostore = false) @TopComponent.Description(preferredID = "EnrichmentChooserTopComponent", iconBase = "org/mongkie/ui/enrichment/resources/enrichment.png", persistenceType = TopComponent.PERSISTENCE_ALWAYS) @TopComponent.Registration(mode = MODE_ACTION, openAtStartup = false, roles = ROLE_NETWORK, position = 400) @ActionID(category = "Window", id = "org.mongkie.ui.enrichment.EnrichmentChooserTopComponent") @ActionReference(path = "Menu/Window", position = 70) @TopComponent.OpenActionRegistration(displayName = "#CTL_EnrichmentChooserAction", preferredID = "EnrichmentChooserTopComponent") public final class EnrichmentChooserTopComponent extends TopComponent implements EnrichmentModelListener, DisplayListener<MongkieDisplay>, TableListener { private static final String NO_SELECTION = NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.choose.displayText"); private EnrichmentModel model; public EnrichmentChooserTopComponent() { initComponents(); settingsSeparator.setVisible(false); setName(NbBundle.getMessage(EnrichmentChooserTopComponent.class, "CTL_EnrichmentChooserTopComponent")); setToolTipText(NbBundle.getMessage(EnrichmentChooserTopComponent.class, "HINT_EnrichmentChooserTopComponent")); putClientProperty(TopComponent.PROP_MAXIMIZATION_DISABLED, Boolean.TRUE); initializeChooser(); addEventListeners(); Lookup.getDefault().lookup(EnrichmentController.class).fireModelChangeEvent(); } private void initializeChooser() { DefaultComboBoxModel enrichmentComboBoxModel = new DefaultComboBoxModel(); enrichmentComboBoxModel.addElement(NO_SELECTION); enrichmentComboBoxModel.setSelectedItem(NO_SELECTION); for (EnrichmentBuilder builder : Lookup.getDefault().lookupAll(EnrichmentBuilder.class)) { enrichmentComboBoxModel.addElement(builder); } enrichmentComboBox.setModel(enrichmentComboBoxModel); } private void addEventListeners() { Lookup.getDefault().lookup(EnrichmentController.class).addModelChangeListener(new ModelChangeListener<EnrichmentModel>() { @Override public void modelChanged(EnrichmentModel o, EnrichmentModel n) { if (o != null) { o.removeModelListener(EnrichmentChooserTopComponent.this); o.getDisplay().removeDisplayListener(EnrichmentChooserTopComponent.this); } model = n; if (model != null) { model.addModelListener(EnrichmentChooserTopComponent.this); model.getDisplay().addDisplayListener(EnrichmentChooserTopComponent.this); } refreshModel(); } }); enrichmentComboBox.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (enrichmentComboBox.getSelectedItem().equals(NO_SELECTION)) { if (model != null) { setSelectedEnrichment(null); } settingsSeparator.setVisible(false); settingsPanel.removeAll(); settingsPanel.revalidate(); settingsPanel.repaint(); } else if (enrichmentComboBox.getSelectedItem() instanceof EnrichmentBuilder) { EnrichmentBuilder builder = (EnrichmentBuilder) enrichmentComboBox.getSelectedItem(); setSelectedEnrichment(builder); settingsPanel.removeAll(); EnrichmentBuilder.SettingUI settings = builder.getSettingUI(); if (settings != null) { settingsSeparator.setVisible(true); settings.load(builder.getEnrichment()); settingsPanel.add(settings.getPanel(), BorderLayout.CENTER); } else { settingsSeparator.setVisible(false); } settingsPanel.revalidate(); settingsPanel.repaint(); } } }); geneIdColumnComboBox.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (model != null) { Lookup.getDefault().lookup(EnrichmentController.class).setGeneIDColumn((String) e.getItem()); } } }); } private void setSelectedEnrichment(EnrichmentBuilder builder) { if (model.get() != null && model.get().getBuilder() == builder) { return; } Lookup.getDefault().lookup(EnrichmentController.class).setEnrichment(builder != null ? builder.getEnrichment() : null); } private void refreshModel() { refreshChooser(); refreshGeneIdColumnComboBox(); refreshEnabled(); refreshResult(); } @Override public void graphDisposing(MongkieDisplay d, Graph g) { g.getNodeTable().removeTableListener(this); } @Override public void graphChanged(MongkieDisplay d, Graph g) { if (g != null) { g.getNodeTable().addTableListener(this); } refreshGeneIdColumnComboBox(); } @Override public void tableChanged(Table t, int start, int end, int col, int type) { if (col != ALL_COLUMNS && (type == INSERT || type == DELETE)) { refreshGeneIdColumnComboBox(); } } private void refreshGeneIdColumnComboBox() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { geneIdColumnComboBox.removeAllItems(); if (model != null) { Table nodeTable = model.getDisplay().getGraph().getNodeTable(); String geneIdCol = model.getGeneIDColumn(); for (int i = 0; i < nodeTable.getColumnCount(); i++) { if (nodeTable.getColumn(i).canGetString()) { geneIdColumnComboBox.addItem(nodeTable.getColumnName(i)); } } geneIdColumnComboBox.setSelectedItem( model.get() == null || nodeTable.getColumnNumber(geneIdCol) < 0 ? null : geneIdCol); } } }); } private void refreshChooser() { Enrichment en = model != null ? model.get() : null; enrichmentComboBox.getModel().setSelectedItem(en != null ? en.getBuilder() : NO_SELECTION); } private void refreshEnabled() { if (model == null || !model.isRunning()) { runButton.setText(NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.runButton.text")); runButton.setIcon(ImageUtilities.loadImageIcon("org/mongkie/ui/enrichment/resources/run.gif", false)); runButton.setToolTipText(NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.runButton.toolTipText")); } else if (model.isRunning()) { runButton.setText(NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.cancelButton.text")); runButton.setIcon(ImageUtilities.loadImageIcon("org/mongkie/ui/enrichment/resources/stop.png", false)); runButton.setToolTipText(NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.cancelButton.toolTipText")); } boolean enabled = model != null && model.get() != null && model.getDisplay().isFired(); runButton.setEnabled(enabled); infoLabel.setEnabled(enabled); wholeNetworkButton.setEnabled(enabled && !model.isRunning()); fromSelectionButton.setEnabled(enabled && !model.isRunning()); geneIdColumnComboBox.setEnabled(enabled && !model.isRunning()); EnrichmentBuilder.SettingUI settings = enabled ? model.get().getBuilder().getSettingUI() : null; if (settings != null) { settings.setEnabled(!model.isRunning()); } enrichmentComboBox.setEnabled(model != null && !model.isRunning() && model.getDisplay().isFired()); } private void refreshResult() { EnrichmentResultTopComponent resultDisplayer = EnrichmentResultTopComponent.getInstance(); if (model == null || model.getDisplay().getGraph().getNodeCount() < 1) { resultDisplayer.setResult(null); } else if (model.isRunning()) { resultDisplayer.setBusy(true); } else { resultDisplayer.setResult(model.getResult()); } } private void run() { Enrichment en = model.get(); EnrichmentBuilder.SettingUI settings = en.getBuilder().getSettingUI(); if (settings != null) { settings.apply(en); } Object geneIdCol = model.getGeneIDColumn(); if (geneIdCol == null) { DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message("Select a ID column of query genes.", NotifyDescriptor.ERROR_MESSAGE)); return; } Lookup.getDefault().lookup(EnrichmentController.class).analyze(getGeneIdsFromSelectedColumn()); } private String[] getGeneIdsFromSelectedColumn() { Set<String> genes = new HashSet<String>(); // for (Iterator<Tuple> nodeIter = model.getDisplay().getGraph().getNodeTable().tuples(); nodeIter.hasNext();) { for (Iterator<Tuple> nodeIter = fromSelectionButton.isSelected() ? model.getDisplay().getVisualization().getFocusGroup(Visualization.FOCUS_ITEMS).tuples() : model.getDisplay().getVisualization().items(NODES); nodeIter.hasNext();) { String gene = nodeIter.next().getString(model.getGeneIDColumn()); if (gene == null || (gene = gene.trim()).isEmpty()) { continue; } genes.add(gene); } return genes.toArray(new String[genes.size()]); } private void cancel() { Lookup.getDefault().lookup(EnrichmentController.class).cancelAnalyzing(); } /** * This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { selectionButtonGroup = new javax.swing.ButtonGroup(); enrichmentComboBox = new javax.swing.JComboBox(); infoLabel = new javax.swing.JLabel(); selectionSeparator = new org.jdesktop.swingx.JXTitledSeparator(); wholeNetworkButton = new javax.swing.JRadioButton(); fromSelectionButton = new javax.swing.JRadioButton(); settingsSeparator = new org.jdesktop.swingx.JXTitledSeparator(); runButton = new javax.swing.JButton(); settingsPanel = new javax.swing.JPanel(); geneIdColumnLabel = new javax.swing.JLabel(); geneIdColumnComboBox = new javax.swing.JComboBox(); selectionButtonGroup.add(wholeNetworkButton); selectionButtonGroup.add(fromSelectionButton); - setBorder(javax.swing.BorderFactory.createEmptyBorder(4, 3, 2, 4)); + setBorder(javax.swing.BorderFactory.createEmptyBorder(6, 3, 2, 4)); enrichmentComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Gene Ontology", "Pathway (KoPath)" })); infoLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/mongkie/ui/enrichment/resources/information.png"))); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(infoLabel, org.openide.util.NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.infoLabel.text")); // NOI18N selectionSeparator.setEnabled(false); selectionSeparator.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/mongkie/ui/enrichment/resources/light-bulb.png"))); // NOI18N selectionSeparator.setTitle(org.openide.util.NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.selectionSeparator.title")); // NOI18N wholeNetworkButton.setSelected(true); org.openide.awt.Mnemonics.setLocalizedText(wholeNetworkButton, org.openide.util.NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.wholeNetworkButton.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(fromSelectionButton, org.openide.util.NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.fromSelectionButton.text")); // NOI18N settingsSeparator.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/mongkie/ui/enrichment/resources/settings.png"))); // NOI18N settingsSeparator.setTitle(org.openide.util.NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.settingsSeparator.title")); // NOI18N runButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/mongkie/ui/enrichment/resources/run.gif"))); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(runButton, org.openide.util.NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.runButton.text")); // NOI18N runButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { runButtonActionPerformed(evt); } }); settingsPanel.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 16, 2, 4)); settingsPanel.setLayout(new java.awt.BorderLayout()); org.openide.awt.Mnemonics.setLocalizedText(geneIdColumnLabel, org.openide.util.NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.geneIdColumnLabel.text")); // NOI18N geneIdColumnComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Gene ID" })); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addComponent(settingsPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 283, Short.MAX_VALUE) - .addComponent(settingsSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 283, Short.MAX_VALUE) - .addComponent(selectionSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 283, Short.MAX_VALUE) + .addComponent(settingsPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(settingsSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(selectionSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(enrichmentComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addComponent(infoLabel)) + .addGap(8, 8, 8) + .addComponent(infoLabel) + .addGap(6, 6, 6)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(runButton, javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addComponent(geneIdColumnLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(geneIdColumnComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addComponent(wholeNetworkButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(fromSelectionButton))) - .addContainerGap(18, Short.MAX_VALUE)))) + .addContainerGap(20, Short.MAX_VALUE)))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(infoLabel) - .addComponent(enrichmentComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(enrichmentComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGap(18, 18, 18) .addComponent(selectionSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(wholeNetworkButton) .addComponent(fromSelectionButton)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(geneIdColumnLabel) .addComponent(geneIdColumnComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addGap(18, 18, 18) .addComponent(settingsSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addComponent(settingsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 121, Short.MAX_VALUE) + .addComponent(settingsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(runButton)) ); layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {selectionSeparator, settingsSeparator}); }// </editor-fold>//GEN-END:initComponents private void runButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_runButtonActionPerformed if (model.isRunning()) { cancel(); } else { run(); } }//GEN-LAST:event_runButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JComboBox enrichmentComboBox; private javax.swing.JRadioButton fromSelectionButton; private javax.swing.JComboBox geneIdColumnComboBox; private javax.swing.JLabel geneIdColumnLabel; private javax.swing.JLabel infoLabel; private javax.swing.JButton runButton; private javax.swing.ButtonGroup selectionButtonGroup; private org.jdesktop.swingx.JXTitledSeparator selectionSeparator; private javax.swing.JPanel settingsPanel; private org.jdesktop.swingx.JXTitledSeparator settingsSeparator; private javax.swing.JRadioButton wholeNetworkButton; // End of variables declaration//GEN-END:variables @Override public void componentOpened() { // TODO add custom code on component opening } @Override public void componentClosed() { // TODO add custom code on component closing } void writeProperties(java.util.Properties p) { // better to version settings since initial version as advocated at // http://wiki.apidesign.org/wiki/PropertyFiles p.setProperty("version", "1.0"); // TODO store your settings } void readProperties(java.util.Properties p) { String version = p.getProperty("version"); // TODO read your settings according to their version } @Override public void analyzingStarted(Enrichment en) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { EnrichmentResultTopComponent resultDisplayer = EnrichmentResultTopComponent.getInstance(); Lookup.getDefault().lookup(EnrichmentController.class).clearResult(); resultDisplayer.setLookupContents(); resultDisplayer.setBusy(true); resultDisplayer.open(); resultDisplayer.requestActive(); refreshEnabled(); } }); } @Override public void analyzingFinished(final Enrichment en) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { EnrichmentResultTopComponent resultDisplayer = EnrichmentResultTopComponent.getInstance(); resultDisplayer.setResult(model.getResult(en)); resultDisplayer.open(); resultDisplayer.requestActive(); refreshEnabled(); } }); } @Override public void enrichmentChanged(Enrichment oe, Enrichment ne) { refreshModel(); } }
false
true
private void initComponents() { selectionButtonGroup = new javax.swing.ButtonGroup(); enrichmentComboBox = new javax.swing.JComboBox(); infoLabel = new javax.swing.JLabel(); selectionSeparator = new org.jdesktop.swingx.JXTitledSeparator(); wholeNetworkButton = new javax.swing.JRadioButton(); fromSelectionButton = new javax.swing.JRadioButton(); settingsSeparator = new org.jdesktop.swingx.JXTitledSeparator(); runButton = new javax.swing.JButton(); settingsPanel = new javax.swing.JPanel(); geneIdColumnLabel = new javax.swing.JLabel(); geneIdColumnComboBox = new javax.swing.JComboBox(); selectionButtonGroup.add(wholeNetworkButton); selectionButtonGroup.add(fromSelectionButton); setBorder(javax.swing.BorderFactory.createEmptyBorder(4, 3, 2, 4)); enrichmentComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Gene Ontology", "Pathway (KoPath)" })); infoLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/mongkie/ui/enrichment/resources/information.png"))); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(infoLabel, org.openide.util.NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.infoLabel.text")); // NOI18N selectionSeparator.setEnabled(false); selectionSeparator.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/mongkie/ui/enrichment/resources/light-bulb.png"))); // NOI18N selectionSeparator.setTitle(org.openide.util.NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.selectionSeparator.title")); // NOI18N wholeNetworkButton.setSelected(true); org.openide.awt.Mnemonics.setLocalizedText(wholeNetworkButton, org.openide.util.NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.wholeNetworkButton.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(fromSelectionButton, org.openide.util.NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.fromSelectionButton.text")); // NOI18N settingsSeparator.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/mongkie/ui/enrichment/resources/settings.png"))); // NOI18N settingsSeparator.setTitle(org.openide.util.NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.settingsSeparator.title")); // NOI18N runButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/mongkie/ui/enrichment/resources/run.gif"))); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(runButton, org.openide.util.NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.runButton.text")); // NOI18N runButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { runButtonActionPerformed(evt); } }); settingsPanel.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 16, 2, 4)); settingsPanel.setLayout(new java.awt.BorderLayout()); org.openide.awt.Mnemonics.setLocalizedText(geneIdColumnLabel, org.openide.util.NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.geneIdColumnLabel.text")); // NOI18N geneIdColumnComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Gene ID" })); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(settingsPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 283, Short.MAX_VALUE) .addComponent(settingsSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 283, Short.MAX_VALUE) .addComponent(selectionSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 283, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(enrichmentComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(infoLabel)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(runButton, javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addComponent(geneIdColumnLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(geneIdColumnComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addComponent(wholeNetworkButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(fromSelectionButton))) .addContainerGap(18, Short.MAX_VALUE)))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(infoLabel) .addComponent(enrichmentComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(selectionSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(wholeNetworkButton) .addComponent(fromSelectionButton)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(geneIdColumnLabel) .addComponent(geneIdColumnComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(settingsSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(settingsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 121, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(runButton)) ); layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {selectionSeparator, settingsSeparator}); }// </editor-fold>//GEN-END:initComponents
private void initComponents() { selectionButtonGroup = new javax.swing.ButtonGroup(); enrichmentComboBox = new javax.swing.JComboBox(); infoLabel = new javax.swing.JLabel(); selectionSeparator = new org.jdesktop.swingx.JXTitledSeparator(); wholeNetworkButton = new javax.swing.JRadioButton(); fromSelectionButton = new javax.swing.JRadioButton(); settingsSeparator = new org.jdesktop.swingx.JXTitledSeparator(); runButton = new javax.swing.JButton(); settingsPanel = new javax.swing.JPanel(); geneIdColumnLabel = new javax.swing.JLabel(); geneIdColumnComboBox = new javax.swing.JComboBox(); selectionButtonGroup.add(wholeNetworkButton); selectionButtonGroup.add(fromSelectionButton); setBorder(javax.swing.BorderFactory.createEmptyBorder(6, 3, 2, 4)); enrichmentComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Gene Ontology", "Pathway (KoPath)" })); infoLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/mongkie/ui/enrichment/resources/information.png"))); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(infoLabel, org.openide.util.NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.infoLabel.text")); // NOI18N selectionSeparator.setEnabled(false); selectionSeparator.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/mongkie/ui/enrichment/resources/light-bulb.png"))); // NOI18N selectionSeparator.setTitle(org.openide.util.NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.selectionSeparator.title")); // NOI18N wholeNetworkButton.setSelected(true); org.openide.awt.Mnemonics.setLocalizedText(wholeNetworkButton, org.openide.util.NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.wholeNetworkButton.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(fromSelectionButton, org.openide.util.NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.fromSelectionButton.text")); // NOI18N settingsSeparator.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/mongkie/ui/enrichment/resources/settings.png"))); // NOI18N settingsSeparator.setTitle(org.openide.util.NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.settingsSeparator.title")); // NOI18N runButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/mongkie/ui/enrichment/resources/run.gif"))); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(runButton, org.openide.util.NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.runButton.text")); // NOI18N runButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { runButtonActionPerformed(evt); } }); settingsPanel.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 16, 2, 4)); settingsPanel.setLayout(new java.awt.BorderLayout()); org.openide.awt.Mnemonics.setLocalizedText(geneIdColumnLabel, org.openide.util.NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.geneIdColumnLabel.text")); // NOI18N geneIdColumnComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Gene ID" })); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(settingsPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(settingsSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(selectionSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(enrichmentComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(8, 8, 8) .addComponent(infoLabel) .addGap(6, 6, 6)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(runButton, javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addComponent(geneIdColumnLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(geneIdColumnComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addComponent(wholeNetworkButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(fromSelectionButton))) .addContainerGap(20, Short.MAX_VALUE)))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(infoLabel) .addComponent(enrichmentComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(selectionSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(wholeNetworkButton) .addComponent(fromSelectionButton)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(geneIdColumnLabel) .addComponent(geneIdColumnComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(settingsSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(settingsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(runButton)) ); layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {selectionSeparator, settingsSeparator}); }// </editor-fold>//GEN-END:initComponents
diff --git a/orbisgis-view/src/main/java/org/orbisgis/view/geocatalog/Catalog.java b/orbisgis-view/src/main/java/org/orbisgis/view/geocatalog/Catalog.java index e33c8cba6..cb0034199 100644 --- a/orbisgis-view/src/main/java/org/orbisgis/view/geocatalog/Catalog.java +++ b/orbisgis-view/src/main/java/org/orbisgis/view/geocatalog/Catalog.java @@ -1,359 +1,359 @@ /* * OrbisGIS is a GIS application dedicated to scientific spatial simulation. * This cross-platform GIS is developed at French IRSTV institute and is able to * manipulate and create vector and raster spatial information. OrbisGIS is * distributed under GPL 3 license. It is produced by the "Atelier SIG" team of * the IRSTV Institute <http://www.irstv.cnrs.fr/> CNRS FR 2488. * * * * This file is part of OrbisGIS. * * OrbisGIS 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. * * OrbisGIS 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 * OrbisGIS. If not, see <http://www.gnu.org/licenses/>. * * For more information, please consult: <http://www.orbisgis.org/> * * or contact directly: * info _at_ orbisgis.org */ package org.orbisgis.view.geocatalog; import java.awt.BorderLayout; import java.awt.Component; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.beans.EventHandler; import java.io.File; import javax.swing.*; import org.apache.log4j.Logger; import org.gdms.data.SourceAlreadyExistsException; import org.gdms.data.db.DBSource; import org.gdms.data.db.DBTableSourceDefinition; import org.gdms.source.SourceManager; import org.orbisgis.core.context.SourceContext.SourceContext; import org.orbisgis.core.events.EventException; import org.orbisgis.core.events.Listener; import org.orbisgis.core.events.ListenerContainer; import org.orbisgis.sif.UIFactory; import org.orbisgis.sif.UIPanel; import org.orbisgis.utils.CollectionUtils; import org.orbisgis.utils.FileUtils; import org.orbisgis.utils.I18N; import org.orbisgis.view.components.filter.FilterFactoryManager; import org.orbisgis.view.docking.DockingPanel; import org.orbisgis.view.docking.DockingPanelParameters; import org.orbisgis.view.geocatalog.dialogs.OpenGdmsFilePanel; import org.orbisgis.view.geocatalog.filters.IFilter; import org.orbisgis.view.geocatalog.filters.factories.NameContains; import org.orbisgis.view.geocatalog.filters.factories.NameNotContains; import org.orbisgis.view.geocatalog.filters.factories.SourceTypeIs; import org.orbisgis.view.geocatalog.renderer.DataSourceListCellRenderer; import org.orbisgis.view.geocatalog.sourceWizards.db.ConnectionPanel; import org.orbisgis.view.geocatalog.sourceWizards.db.TableSelectionPanel; import org.orbisgis.view.icons.OrbisGISIcon; /** * @brief This is the GeoCatalog panel. That Panel show the list of avaible DataSource * * This is connected with the SourceManager model. * @note If you want to add new functionnality to data source items without change * this class you can use the eventSourceListPopupMenuCreating listener container * to add more items in the source list popup menu. */ public class Catalog extends JPanel implements DockingPanel { //The UID must be incremented when the serialization is not compatible with the new version of this class private static final long serialVersionUID = 1L; private static final Logger LOGGER = Logger.getLogger(Catalog.class); private DockingPanelParameters dockingParameters = new DockingPanelParameters(); /*!< GeoCatalog docked panel properties */ private JList sourceList; private SourceListModel sourceListContent; //The factory shown when the user click on new factory button private static final String DEFAULT_FILTER_FACTORY = "name_contains"; //The popup menu event listener manager private ListenerContainer<MenuPopupEventData> eventSourceListPopupMenuCreating = new ListenerContainer<MenuPopupEventData>(); private FilterFactoryManager<IFilter> filterFactoryManager; /** * For the Unit test purpose * @return The source list instance */ public JList getSourceList() { return sourceList; } /** * The popup menu event listener manager * The popup menu is being created, * all listeners are able to feed the menu with custom functions * @return */ public ListenerContainer<MenuPopupEventData> getEventSourceListPopupMenuCreating() { return eventSourceListPopupMenuCreating; } /** * Default constructor */ public Catalog(SourceContext sourceContext) { super(new BorderLayout()); dockingParameters.setName("geocatalog"); dockingParameters.setTitle(I18N.getString("orbisgis.org.orbisgis.Catalog.title")); dockingParameters.setTitleIcon(OrbisGISIcon.getIcon("geocatalog")); //Add the Source List in a Scroll Pane, //then add the scroll pane in this panel add(new JScrollPane(makeSourceList(sourceContext)), BorderLayout.CENTER); //Init the filter factory manager filterFactoryManager = new FilterFactoryManager<IFilter>(); //Set the factory that must be shown when the user click on add filter button filterFactoryManager.setDefaultFilterFactory(DEFAULT_FILTER_FACTORY); //Set listener on filter change event, this event will update the filters filterFactoryManager.getEventFilterChange().addListener(sourceListContent, EventHandler.create(Listener.class, sourceListContent, //target of event "setFilters", //target method "source.getFilters" //target method argument )); //Add the filter list at the top of the geocatalog add(filterFactoryManager.makeFilterPanel(), BorderLayout.NORTH); registerFilterFactories(); } /** * For JUnit purpose, return the filter factory manager * @return Instance of filterFactoryManager */ public FilterFactoryManager<IFilter> getFilterFactoryManager() { return filterFactoryManager; } /** * Add the built-ins filter factory */ private void registerFilterFactories() { filterFactoryManager.registerFilterFactory(new NameContains()); filterFactoryManager.registerFilterFactory(new SourceTypeIs()); filterFactoryManager.registerFilterFactory(new NameNotContains()); } /** * The user click on the source list control * @param e The mouse event fired by the LI */ public void onMouseActionOnSourceList(MouseEvent e) { //Manage selection of items before popping up the menu if (e.isPopupTrigger()) { //Right mouse button under linux and windows int itemUnderMouse = -1; //Item under the position of the mouse event //Find the Item under the position of the mouse cursor for (int i = 0; i < sourceListContent.getSize(); i++) { //If the coordinate of the cursor cover the cell bouding box if (sourceList.getCellBounds(i, i).contains(e.getPoint())) { itemUnderMouse = i; break; } } //Retrieve all selected items index int[] selectedItems = sourceList.getSelectedIndices(); //If there are a list item under the mouse if ((selectedItems != null) && (itemUnderMouse != -1)) { //If the item under the mouse was not previously selected if (!CollectionUtils.contains(selectedItems, itemUnderMouse)) { //Control must be pushed to add the list item to the selection if (e.isControlDown()) { sourceList.addSelectionInterval(itemUnderMouse, itemUnderMouse); } else { //Unselect the other items and select only the item under the mouse sourceList.setSelectionInterval(itemUnderMouse, itemUnderMouse); } } } else if (itemUnderMouse == -1) { //Unselect all items sourceList.clearSelection(); } //Selection are ready, now create the popup menu JPopupMenu popup = makePopupMenu(); if (popup != null) { popup.show(e.getComponent(), e.getX(), e.getY()); } } } /** * The user click on the menu item called "Add/File" * The user wants to open a file using the geocatalog. * It will open a panel dedicated to the selection of the wanted files. This * panel will then return the selected files. */ public void onMenuAddFile() { SourceContext srcContext = sourceListContent.getSourceContext(); //Create the SIF panel OpenGdmsFilePanel openDialog = new OpenGdmsFilePanel(I18N.getString("orbisgis.view.geocatalog.OpenGdmsFilePanelTitle"), srcContext.getSourceManager().getDriverManager()); //Ask SIF to open the dialog if (UIFactory.showDialog(new UIPanel[]{openDialog})) { // We can retrieve the files that have been selected by the user File[] files = openDialog.getSelectedFiles(); for (int i = 0; i < files.length; i++) { File file = files[i]; //If there is a driver compatible with //this file extensions if (srcContext.isFileCanBeRegistered(file)) { //Try to add the data source try { String name = srcContext.getSourceManager().getUniqueName(FileUtils.getFileNameWithoutExtensionU(file)); srcContext.getSourceManager().register(name, file); } catch (SourceAlreadyExistsException e) { LOGGER.error(I18N.getString("orbisgis.view.geocatalog.SourceAlreadyRegistered"), e); } } } } } /** * Connect to a database and add one or more tables in the geocatalog. */ public void onMenuAddFromDataBase() { SourceContext srcContext = sourceListContent.getSourceContext(); SourceManager sm = srcContext.getSourceManager(); final ConnectionPanel firstPanel = new ConnectionPanel(sm); final TableSelectionPanel secondPanel = new TableSelectionPanel( firstPanel); if (UIFactory.showDialog(new UIPanel[]{firstPanel, secondPanel})) { for (DBSource dBSource : secondPanel.getSelectedDBSources()) { String name = sm.getUniqueName(dBSource.getTableName().toString()); sm.register(name, new DBTableSourceDefinition(dBSource)); } } } /** * The user click on the menu item called "clear geocatalog" */ public void onMenuClearGeoCatalog() { //User must validate this action int option = JOptionPane.showConfirmDialog(this, I18N.getString("orbisgis.view.geocatalog.validateClearMessage"), I18N.getString("orbisgis.view.geocatalog.validateClearTitle"), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); if (option == JOptionPane.YES_OPTION) { sourceListContent.clearAllSourceExceptSystemTables(); } } /** * Create a popup menu corresponding to the current state of source selection * @return A new popup menu */ private JPopupMenu makePopupMenu() { JPopupMenu rootMenu = new JPopupMenu(); //Popup:ClearGeocatalog (added if the datasource manager is not empty) if (!sourceListContent.getSourceContext().isDataSourceManagerEmpty()) { JMenuItem clearCatalogItem = new JMenuItem(I18N.getString("orbisgis.view.geocatalog.clearGeoCatalogMenuItem"), OrbisGISIcon.getIcon("bin_closed")); clearCatalogItem.addActionListener(EventHandler.create(ActionListener.class, this, "onMenuClearGeoCatalog")); rootMenu.add(clearCatalogItem); } //Popup:Add JMenu addMenu = new JMenu(I18N.getString("orbisgis.view.geocatalog.addMenuItem")); rootMenu.addSeparator(); rootMenu.add(addMenu); //Popup:Add:File JMenuItem addFileItem = new JMenuItem( I18N.getString("orbisgis.view.geocatalog.addFileMenuItem"), OrbisGISIcon.getIcon("page_white_add")); addFileItem.addActionListener(EventHandler.create(ActionListener.class, this, "onMenuAddFile")); addMenu.add(addFileItem); //Add the database panel addFileItem = new JMenuItem( I18N.getString("orbisgis.view.geocatalog.addDataBaseMenuItem"), - OrbisGISIcon.getIcon("database_add.png")); + OrbisGISIcon.getIcon("database_add")); addFileItem.addActionListener(EventHandler.create(ActionListener.class, this, "onMenuAddFromDataBase")); addMenu.add(addFileItem); ////////////////////////////// //Plugins //Add additionnal extern data source functions try { eventSourceListPopupMenuCreating.callListeners(new MenuPopupEventData(rootMenu, this)); } catch (EventException ex) { //A listener cancel the creation of the popup menu LOGGER.warn(I18N.getString("orbisgis.view.geocatalog.listenerMenuThrown"), ex); return null; } return rootMenu; } /** * Create the Source List ui compenent */ private JList makeSourceList(SourceContext sourceContext) { sourceList = new JList(); //Set the list content renderer sourceList.setCellRenderer(new DataSourceListCellRenderer()); //Add mouse listener for popup menu sourceList.addMouseListener(EventHandler.create(MouseListener.class, this, "onMouseActionOnSourceList", "")); //This method ask the event data as argument //Create the list content manager sourceListContent = new SourceListModel(sourceContext); //Replace the default model by the GeoCatalog model sourceList.setModel(sourceListContent); //Attach the content to the DataSource instance sourceListContent.setListeners(); return sourceList; } /** * Free listeners, Catalog must not be reachable to let the Garbage Collector * free this instance */ public void dispose() { //Remove listeners linked with the source list content filterFactoryManager.getEventFilterChange().clearListeners(); sourceListContent.dispose(); } /** * Give information on the behaviour of this panel related to the current * docking system * @return The panel parameter instance */ public DockingPanelParameters getDockingParameters() { return dockingParameters; } /** * Return the content of the view. * @return An awt content to show in this panel */ public Component getComponent() { return this; } }
true
true
private JPopupMenu makePopupMenu() { JPopupMenu rootMenu = new JPopupMenu(); //Popup:ClearGeocatalog (added if the datasource manager is not empty) if (!sourceListContent.getSourceContext().isDataSourceManagerEmpty()) { JMenuItem clearCatalogItem = new JMenuItem(I18N.getString("orbisgis.view.geocatalog.clearGeoCatalogMenuItem"), OrbisGISIcon.getIcon("bin_closed")); clearCatalogItem.addActionListener(EventHandler.create(ActionListener.class, this, "onMenuClearGeoCatalog")); rootMenu.add(clearCatalogItem); } //Popup:Add JMenu addMenu = new JMenu(I18N.getString("orbisgis.view.geocatalog.addMenuItem")); rootMenu.addSeparator(); rootMenu.add(addMenu); //Popup:Add:File JMenuItem addFileItem = new JMenuItem( I18N.getString("orbisgis.view.geocatalog.addFileMenuItem"), OrbisGISIcon.getIcon("page_white_add")); addFileItem.addActionListener(EventHandler.create(ActionListener.class, this, "onMenuAddFile")); addMenu.add(addFileItem); //Add the database panel addFileItem = new JMenuItem( I18N.getString("orbisgis.view.geocatalog.addDataBaseMenuItem"), OrbisGISIcon.getIcon("database_add.png")); addFileItem.addActionListener(EventHandler.create(ActionListener.class, this, "onMenuAddFromDataBase")); addMenu.add(addFileItem); ////////////////////////////// //Plugins //Add additionnal extern data source functions try { eventSourceListPopupMenuCreating.callListeners(new MenuPopupEventData(rootMenu, this)); } catch (EventException ex) { //A listener cancel the creation of the popup menu LOGGER.warn(I18N.getString("orbisgis.view.geocatalog.listenerMenuThrown"), ex); return null; } return rootMenu; }
private JPopupMenu makePopupMenu() { JPopupMenu rootMenu = new JPopupMenu(); //Popup:ClearGeocatalog (added if the datasource manager is not empty) if (!sourceListContent.getSourceContext().isDataSourceManagerEmpty()) { JMenuItem clearCatalogItem = new JMenuItem(I18N.getString("orbisgis.view.geocatalog.clearGeoCatalogMenuItem"), OrbisGISIcon.getIcon("bin_closed")); clearCatalogItem.addActionListener(EventHandler.create(ActionListener.class, this, "onMenuClearGeoCatalog")); rootMenu.add(clearCatalogItem); } //Popup:Add JMenu addMenu = new JMenu(I18N.getString("orbisgis.view.geocatalog.addMenuItem")); rootMenu.addSeparator(); rootMenu.add(addMenu); //Popup:Add:File JMenuItem addFileItem = new JMenuItem( I18N.getString("orbisgis.view.geocatalog.addFileMenuItem"), OrbisGISIcon.getIcon("page_white_add")); addFileItem.addActionListener(EventHandler.create(ActionListener.class, this, "onMenuAddFile")); addMenu.add(addFileItem); //Add the database panel addFileItem = new JMenuItem( I18N.getString("orbisgis.view.geocatalog.addDataBaseMenuItem"), OrbisGISIcon.getIcon("database_add")); addFileItem.addActionListener(EventHandler.create(ActionListener.class, this, "onMenuAddFromDataBase")); addMenu.add(addFileItem); ////////////////////////////// //Plugins //Add additionnal extern data source functions try { eventSourceListPopupMenuCreating.callListeners(new MenuPopupEventData(rootMenu, this)); } catch (EventException ex) { //A listener cancel the creation of the popup menu LOGGER.warn(I18N.getString("orbisgis.view.geocatalog.listenerMenuThrown"), ex); return null; } return rootMenu; }
diff --git a/newdir/hello.java b/newdir/hello.java index fc41167..7a8ae36 100644 --- a/newdir/hello.java +++ b/newdir/hello.java @@ -1,8 +1,8 @@ public class HelloWorld { public static void main(String[] args) { - System.out.println("Hello, World"); + System.out.println("Hello, World!"); } }
true
true
public static void main(String[] args) { System.out.println("Hello, World"); }
public static void main(String[] args) { System.out.println("Hello, World!"); }
diff --git a/integration/src/main/java/org/obiba/magma/integration/IntegrationApp.java b/integration/src/main/java/org/obiba/magma/integration/IntegrationApp.java index 2d21b1f4..335ada86 100644 --- a/integration/src/main/java/org/obiba/magma/integration/IntegrationApp.java +++ b/integration/src/main/java/org/obiba/magma/integration/IntegrationApp.java @@ -1,191 +1,193 @@ package org.obiba.magma.integration; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.security.NoSuchAlgorithmException; import java.util.Date; import java.util.Properties; import org.obiba.magma.Datasource; import org.obiba.magma.MagmaEngine; import org.obiba.magma.Value; import org.obiba.magma.ValueSequence; import org.obiba.magma.ValueSet; import org.obiba.magma.ValueTable; import org.obiba.magma.Variable; import org.obiba.magma.crypt.support.GeneratedKeyPairProvider; import org.obiba.magma.datasource.crypt.EncryptedSecretKeyDatasourceEncryptionStrategy; import org.obiba.magma.datasource.crypt.GeneratedSecretKeyDatasourceEncryptionStrategy; import org.obiba.magma.datasource.csv.CsvDatasource; import org.obiba.magma.datasource.excel.ExcelDatasource; import org.obiba.magma.datasource.fs.FsDatasource; import org.obiba.magma.datasource.hibernate.SessionFactoryProvider; import org.obiba.magma.datasource.hibernate.support.HibernateDatasourceFactory; import org.obiba.magma.datasource.hibernate.support.LocalSessionFactoryProvider; import org.obiba.magma.datasource.jdbc.JdbcDatasourceFactory; import org.obiba.magma.datasource.jdbc.JdbcDatasourceSettings; import org.obiba.magma.integration.service.XStreamIntegrationServiceFactory; import org.obiba.magma.js.MagmaJsExtension; import org.obiba.magma.support.DatasourceCopier; import org.obiba.magma.type.DateTimeType; import org.obiba.magma.type.TextType; import org.obiba.magma.xstream.MagmaXStreamExtension; /** */ public class IntegrationApp { public static void main(String[] args) throws IOException, NoSuchAlgorithmException { new MagmaEngine().extend(new MagmaJsExtension()).extend(new MagmaXStreamExtension()); XStreamIntegrationServiceFactory factory = new XStreamIntegrationServiceFactory(); IntegrationDatasource integrationDatasource = new IntegrationDatasource(factory.buildService(new InputStreamReader(IntegrationApp.class.getResourceAsStream("participants.xml"), "UTF-8"))); MagmaEngine.get().addDatasource(integrationDatasource); File encrypted = new File("target", "output-encrypted.zip"); if(encrypted.exists()) { encrypted.delete(); } // Generate a new KeyPair. GeneratedKeyPairProvider keyPairProvider = new GeneratedKeyPairProvider(); GeneratedSecretKeyDatasourceEncryptionStrategy generatedEncryptionStrategy = new GeneratedSecretKeyDatasourceEncryptionStrategy(); generatedEncryptionStrategy.setKeyProvider(keyPairProvider); FsDatasource fs = new FsDatasource("export", encrypted, generatedEncryptionStrategy); MagmaEngine.get().addDatasource(fs); // Export the IntegrationDatasource to the FsDatasource DatasourceCopier copier = DatasourceCopier.Builder.newCopier().build(); copier.copy(integrationDatasource.getName(), fs.getName()); // Disconnect it from Magma MagmaEngine.get().removeDatasource(fs); // Read it back EncryptedSecretKeyDatasourceEncryptionStrategy encryptedEncryptionStrategy = new EncryptedSecretKeyDatasourceEncryptionStrategy(); encryptedEncryptionStrategy.setKeyProvider(keyPairProvider); MagmaEngine.get().addDatasource(new FsDatasource("imported", encrypted, encryptedEncryptionStrategy)); // Dump its values for(ValueTable table : MagmaEngine.get().getDatasource("imported").getValueTables()) { for(ValueSet valueSet : table.getValueSets()) { for(Variable variable : table.getVariables()) { Value value = table.getValue(variable, valueSet); if(value.isSequence() && value.isNull() == false) { ValueSequence seq = value.asSequence(); int order = 0; for(Value item : seq.getValues()) { System.out.println(variable.getName() + "[" + value.getValueType().getName() + "]@" + (order++) + ": " + item); } } else { System.out.println(variable.getName() + "[" + value.getValueType().getName() + "]: " + value); } } } } File decrypted = new File("target", "output-decrypted.zip"); if(decrypted.exists()) { - decrypted.delete(); + if(!decrypted.delete()) { + System.err.println("Failed to delete file: " + decrypted.getPath()); + } } fs = new FsDatasource("export", decrypted); MagmaEngine.get().addDatasource(fs); // Export the IntegrationDatasource to the FsDatasource copier.copy(integrationDatasource.getName(), fs.getName()); // Disconnect it from Magma MagmaEngine.get().removeDatasource(fs); SessionFactoryProvider provider = new LocalSessionFactoryProvider("org.hsqldb.jdbcDriver", "jdbc:hsqldb:file:target/integration-hibernate.db;shutdown=true", "sa", "", "org.hibernate.dialect.HSQLDialect"); HibernateDatasourceFactory hdsFactory = new HibernateDatasourceFactory("integration-hibernate", provider); try { // This is uncool. We have to initialise the DatasourceFactory before passing it to Magma, because we need to // start a transaction before the datasource initialises itself. Starting the transaction requires the // SessionFactory which is created by the DatasourceFactory. Ideally, we would have passed the factory to Magma // directly. hdsFactory.initialise(); // Start a transaction before passing the Datasource to Magma. A tx is required for the Datasource to initialise // correctly. provider.getSessionFactory().getCurrentSession().beginTransaction(); Datasource ds = MagmaEngine.get().addDatasource(hdsFactory.create()); // Add some attributes to the HibernateDatasource. if(!ds.hasAttribute("Created by")) { ds.setAttributeValue("Created by", TextType.get().valueOf("Magma Integration App")); } if(!ds.hasAttribute("Created on")) { ds.setAttributeValue("Created on", DateTimeType.get().valueOf(new Date())); } ds.setAttributeValue("Last connected", DateTimeType.get().valueOf(new Date())); // Copy the data from the IntegrationDatasource to the HibernateDatasource. copier.copy(integrationDatasource, ds); MagmaEngine.get().removeDatasource(ds); provider.getSessionFactory().getCurrentSession().getTransaction().commit(); } catch(RuntimeException e) { try { provider.getSessionFactory().getCurrentSession().getTransaction().rollback(); } catch(Exception ignore) { } e.printStackTrace(); throw e; } // CSV Datasource File csvDataFile = new File("target", "data.csv"); deleteFile(csvDataFile); csvDataFile.createNewFile(); File csvVariablesFile = new File("target", "variables.csv"); deleteFile(csvVariablesFile); csvVariablesFile.createNewFile(); CsvDatasource csvDatasource = new CsvDatasource("csv"); csvDatasource.addValueTable("integration-app", csvVariablesFile, csvDataFile); csvDatasource.setVariablesHeader("integration-app", "name#valueType#entityType#mimeType#unit#occurrenceGroup#repeatable#script".split("#")); MagmaEngine.get().addDatasource(csvDatasource); DatasourceCopier.Builder.newCopier().dontCopyNullValues().build().copy(integrationDatasource, csvDatasource); // Excel Datasource File excelFile = new File("target", "excel-datasource.xls"); if(excelFile.exists()) { excelFile.delete(); } ExcelDatasource ed = new ExcelDatasource("excel", excelFile); MagmaEngine.get().addDatasource(ed); DatasourceCopier.Builder.newCopier().dontCopyValues().build().copy(integrationDatasource, ed); JdbcDatasourceFactory jdbcDatasourceFactory = new JdbcDatasourceFactory(); jdbcDatasourceFactory.setName("jdbc"); jdbcDatasourceFactory.setJdbcProperties(getJdbcProperties()); jdbcDatasourceFactory.setDatasourceSettings(new JdbcDatasourceSettings("Participant", null, null, true)); Datasource jd = jdbcDatasourceFactory.create(); MagmaEngine.get().addDatasource(jd); DatasourceCopier.Builder.newCopier().dontCopyNullValues().build().copy(integrationDatasource, jd); MagmaEngine.get().shutdown(); } private static Properties getJdbcProperties() { Properties jdbcProperties = new Properties(); jdbcProperties.setProperty(JdbcDatasourceFactory.DRIVER_CLASS_NAME, "org.hsqldb.jdbcDriver"); jdbcProperties.setProperty(JdbcDatasourceFactory.URL, "jdbc:hsqldb:file:target/datasource_jdbc.db;shutdown=true"); jdbcProperties.setProperty(JdbcDatasourceFactory.USERNAME, "sa"); jdbcProperties.setProperty(JdbcDatasourceFactory.PASSWORD, ""); return jdbcProperties; } private static void deleteFile(File file) { if(file.exists()) file.delete(); } }
true
true
public static void main(String[] args) throws IOException, NoSuchAlgorithmException { new MagmaEngine().extend(new MagmaJsExtension()).extend(new MagmaXStreamExtension()); XStreamIntegrationServiceFactory factory = new XStreamIntegrationServiceFactory(); IntegrationDatasource integrationDatasource = new IntegrationDatasource(factory.buildService(new InputStreamReader(IntegrationApp.class.getResourceAsStream("participants.xml"), "UTF-8"))); MagmaEngine.get().addDatasource(integrationDatasource); File encrypted = new File("target", "output-encrypted.zip"); if(encrypted.exists()) { encrypted.delete(); } // Generate a new KeyPair. GeneratedKeyPairProvider keyPairProvider = new GeneratedKeyPairProvider(); GeneratedSecretKeyDatasourceEncryptionStrategy generatedEncryptionStrategy = new GeneratedSecretKeyDatasourceEncryptionStrategy(); generatedEncryptionStrategy.setKeyProvider(keyPairProvider); FsDatasource fs = new FsDatasource("export", encrypted, generatedEncryptionStrategy); MagmaEngine.get().addDatasource(fs); // Export the IntegrationDatasource to the FsDatasource DatasourceCopier copier = DatasourceCopier.Builder.newCopier().build(); copier.copy(integrationDatasource.getName(), fs.getName()); // Disconnect it from Magma MagmaEngine.get().removeDatasource(fs); // Read it back EncryptedSecretKeyDatasourceEncryptionStrategy encryptedEncryptionStrategy = new EncryptedSecretKeyDatasourceEncryptionStrategy(); encryptedEncryptionStrategy.setKeyProvider(keyPairProvider); MagmaEngine.get().addDatasource(new FsDatasource("imported", encrypted, encryptedEncryptionStrategy)); // Dump its values for(ValueTable table : MagmaEngine.get().getDatasource("imported").getValueTables()) { for(ValueSet valueSet : table.getValueSets()) { for(Variable variable : table.getVariables()) { Value value = table.getValue(variable, valueSet); if(value.isSequence() && value.isNull() == false) { ValueSequence seq = value.asSequence(); int order = 0; for(Value item : seq.getValues()) { System.out.println(variable.getName() + "[" + value.getValueType().getName() + "]@" + (order++) + ": " + item); } } else { System.out.println(variable.getName() + "[" + value.getValueType().getName() + "]: " + value); } } } } File decrypted = new File("target", "output-decrypted.zip"); if(decrypted.exists()) { decrypted.delete(); } fs = new FsDatasource("export", decrypted); MagmaEngine.get().addDatasource(fs); // Export the IntegrationDatasource to the FsDatasource copier.copy(integrationDatasource.getName(), fs.getName()); // Disconnect it from Magma MagmaEngine.get().removeDatasource(fs); SessionFactoryProvider provider = new LocalSessionFactoryProvider("org.hsqldb.jdbcDriver", "jdbc:hsqldb:file:target/integration-hibernate.db;shutdown=true", "sa", "", "org.hibernate.dialect.HSQLDialect"); HibernateDatasourceFactory hdsFactory = new HibernateDatasourceFactory("integration-hibernate", provider); try { // This is uncool. We have to initialise the DatasourceFactory before passing it to Magma, because we need to // start a transaction before the datasource initialises itself. Starting the transaction requires the // SessionFactory which is created by the DatasourceFactory. Ideally, we would have passed the factory to Magma // directly. hdsFactory.initialise(); // Start a transaction before passing the Datasource to Magma. A tx is required for the Datasource to initialise // correctly. provider.getSessionFactory().getCurrentSession().beginTransaction(); Datasource ds = MagmaEngine.get().addDatasource(hdsFactory.create()); // Add some attributes to the HibernateDatasource. if(!ds.hasAttribute("Created by")) { ds.setAttributeValue("Created by", TextType.get().valueOf("Magma Integration App")); } if(!ds.hasAttribute("Created on")) { ds.setAttributeValue("Created on", DateTimeType.get().valueOf(new Date())); } ds.setAttributeValue("Last connected", DateTimeType.get().valueOf(new Date())); // Copy the data from the IntegrationDatasource to the HibernateDatasource. copier.copy(integrationDatasource, ds); MagmaEngine.get().removeDatasource(ds); provider.getSessionFactory().getCurrentSession().getTransaction().commit(); } catch(RuntimeException e) { try { provider.getSessionFactory().getCurrentSession().getTransaction().rollback(); } catch(Exception ignore) { } e.printStackTrace(); throw e; } // CSV Datasource File csvDataFile = new File("target", "data.csv"); deleteFile(csvDataFile); csvDataFile.createNewFile(); File csvVariablesFile = new File("target", "variables.csv"); deleteFile(csvVariablesFile); csvVariablesFile.createNewFile(); CsvDatasource csvDatasource = new CsvDatasource("csv"); csvDatasource.addValueTable("integration-app", csvVariablesFile, csvDataFile); csvDatasource.setVariablesHeader("integration-app", "name#valueType#entityType#mimeType#unit#occurrenceGroup#repeatable#script".split("#")); MagmaEngine.get().addDatasource(csvDatasource); DatasourceCopier.Builder.newCopier().dontCopyNullValues().build().copy(integrationDatasource, csvDatasource); // Excel Datasource File excelFile = new File("target", "excel-datasource.xls"); if(excelFile.exists()) { excelFile.delete(); } ExcelDatasource ed = new ExcelDatasource("excel", excelFile); MagmaEngine.get().addDatasource(ed); DatasourceCopier.Builder.newCopier().dontCopyValues().build().copy(integrationDatasource, ed); JdbcDatasourceFactory jdbcDatasourceFactory = new JdbcDatasourceFactory(); jdbcDatasourceFactory.setName("jdbc"); jdbcDatasourceFactory.setJdbcProperties(getJdbcProperties()); jdbcDatasourceFactory.setDatasourceSettings(new JdbcDatasourceSettings("Participant", null, null, true)); Datasource jd = jdbcDatasourceFactory.create(); MagmaEngine.get().addDatasource(jd); DatasourceCopier.Builder.newCopier().dontCopyNullValues().build().copy(integrationDatasource, jd); MagmaEngine.get().shutdown(); }
public static void main(String[] args) throws IOException, NoSuchAlgorithmException { new MagmaEngine().extend(new MagmaJsExtension()).extend(new MagmaXStreamExtension()); XStreamIntegrationServiceFactory factory = new XStreamIntegrationServiceFactory(); IntegrationDatasource integrationDatasource = new IntegrationDatasource(factory.buildService(new InputStreamReader(IntegrationApp.class.getResourceAsStream("participants.xml"), "UTF-8"))); MagmaEngine.get().addDatasource(integrationDatasource); File encrypted = new File("target", "output-encrypted.zip"); if(encrypted.exists()) { encrypted.delete(); } // Generate a new KeyPair. GeneratedKeyPairProvider keyPairProvider = new GeneratedKeyPairProvider(); GeneratedSecretKeyDatasourceEncryptionStrategy generatedEncryptionStrategy = new GeneratedSecretKeyDatasourceEncryptionStrategy(); generatedEncryptionStrategy.setKeyProvider(keyPairProvider); FsDatasource fs = new FsDatasource("export", encrypted, generatedEncryptionStrategy); MagmaEngine.get().addDatasource(fs); // Export the IntegrationDatasource to the FsDatasource DatasourceCopier copier = DatasourceCopier.Builder.newCopier().build(); copier.copy(integrationDatasource.getName(), fs.getName()); // Disconnect it from Magma MagmaEngine.get().removeDatasource(fs); // Read it back EncryptedSecretKeyDatasourceEncryptionStrategy encryptedEncryptionStrategy = new EncryptedSecretKeyDatasourceEncryptionStrategy(); encryptedEncryptionStrategy.setKeyProvider(keyPairProvider); MagmaEngine.get().addDatasource(new FsDatasource("imported", encrypted, encryptedEncryptionStrategy)); // Dump its values for(ValueTable table : MagmaEngine.get().getDatasource("imported").getValueTables()) { for(ValueSet valueSet : table.getValueSets()) { for(Variable variable : table.getVariables()) { Value value = table.getValue(variable, valueSet); if(value.isSequence() && value.isNull() == false) { ValueSequence seq = value.asSequence(); int order = 0; for(Value item : seq.getValues()) { System.out.println(variable.getName() + "[" + value.getValueType().getName() + "]@" + (order++) + ": " + item); } } else { System.out.println(variable.getName() + "[" + value.getValueType().getName() + "]: " + value); } } } } File decrypted = new File("target", "output-decrypted.zip"); if(decrypted.exists()) { if(!decrypted.delete()) { System.err.println("Failed to delete file: " + decrypted.getPath()); } } fs = new FsDatasource("export", decrypted); MagmaEngine.get().addDatasource(fs); // Export the IntegrationDatasource to the FsDatasource copier.copy(integrationDatasource.getName(), fs.getName()); // Disconnect it from Magma MagmaEngine.get().removeDatasource(fs); SessionFactoryProvider provider = new LocalSessionFactoryProvider("org.hsqldb.jdbcDriver", "jdbc:hsqldb:file:target/integration-hibernate.db;shutdown=true", "sa", "", "org.hibernate.dialect.HSQLDialect"); HibernateDatasourceFactory hdsFactory = new HibernateDatasourceFactory("integration-hibernate", provider); try { // This is uncool. We have to initialise the DatasourceFactory before passing it to Magma, because we need to // start a transaction before the datasource initialises itself. Starting the transaction requires the // SessionFactory which is created by the DatasourceFactory. Ideally, we would have passed the factory to Magma // directly. hdsFactory.initialise(); // Start a transaction before passing the Datasource to Magma. A tx is required for the Datasource to initialise // correctly. provider.getSessionFactory().getCurrentSession().beginTransaction(); Datasource ds = MagmaEngine.get().addDatasource(hdsFactory.create()); // Add some attributes to the HibernateDatasource. if(!ds.hasAttribute("Created by")) { ds.setAttributeValue("Created by", TextType.get().valueOf("Magma Integration App")); } if(!ds.hasAttribute("Created on")) { ds.setAttributeValue("Created on", DateTimeType.get().valueOf(new Date())); } ds.setAttributeValue("Last connected", DateTimeType.get().valueOf(new Date())); // Copy the data from the IntegrationDatasource to the HibernateDatasource. copier.copy(integrationDatasource, ds); MagmaEngine.get().removeDatasource(ds); provider.getSessionFactory().getCurrentSession().getTransaction().commit(); } catch(RuntimeException e) { try { provider.getSessionFactory().getCurrentSession().getTransaction().rollback(); } catch(Exception ignore) { } e.printStackTrace(); throw e; } // CSV Datasource File csvDataFile = new File("target", "data.csv"); deleteFile(csvDataFile); csvDataFile.createNewFile(); File csvVariablesFile = new File("target", "variables.csv"); deleteFile(csvVariablesFile); csvVariablesFile.createNewFile(); CsvDatasource csvDatasource = new CsvDatasource("csv"); csvDatasource.addValueTable("integration-app", csvVariablesFile, csvDataFile); csvDatasource.setVariablesHeader("integration-app", "name#valueType#entityType#mimeType#unit#occurrenceGroup#repeatable#script".split("#")); MagmaEngine.get().addDatasource(csvDatasource); DatasourceCopier.Builder.newCopier().dontCopyNullValues().build().copy(integrationDatasource, csvDatasource); // Excel Datasource File excelFile = new File("target", "excel-datasource.xls"); if(excelFile.exists()) { excelFile.delete(); } ExcelDatasource ed = new ExcelDatasource("excel", excelFile); MagmaEngine.get().addDatasource(ed); DatasourceCopier.Builder.newCopier().dontCopyValues().build().copy(integrationDatasource, ed); JdbcDatasourceFactory jdbcDatasourceFactory = new JdbcDatasourceFactory(); jdbcDatasourceFactory.setName("jdbc"); jdbcDatasourceFactory.setJdbcProperties(getJdbcProperties()); jdbcDatasourceFactory.setDatasourceSettings(new JdbcDatasourceSettings("Participant", null, null, true)); Datasource jd = jdbcDatasourceFactory.create(); MagmaEngine.get().addDatasource(jd); DatasourceCopier.Builder.newCopier().dontCopyNullValues().build().copy(integrationDatasource, jd); MagmaEngine.get().shutdown(); }
diff --git a/src/br/com/developer/redu/ReduClient.java b/src/br/com/developer/redu/ReduClient.java index 1a2a1c5..df2e0f0 100644 --- a/src/br/com/developer/redu/ReduClient.java +++ b/src/br/com/developer/redu/ReduClient.java @@ -1,386 +1,386 @@ package br.com.developer.redu; import br.com.developer.redu.api.Redu; import br.com.developer.redu.http.ScribeHttpClient; import br.com.developer.redu.models.*; import br.com.developer.redu.http.HttpClient; import br.com.developer.redu.http.ArgPair; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * @author igor * * Classe que faz uma implementação parcial do Wrapper do redu. * Todos os objetos que representam recursos da api são parametrizados para * facilitar a customização. O objetivo principal dessa classe é abstrair o parsing e * a requisição dos recursos. * * @param <A> Tipo de Course * @param <B> Tipo de Enrollment * @param <C> Tipo de Environment * @param <D> Tipo de Space * @param <E> Tipo de Subject * @param <F> Tipo de User * @param <G> Tipo de Status * @param <H> Tipo de ChatMessage * @param <I> Tipo de Chat */ public abstract class ReduClient<A,B,C,D,E,F,G, H,I> implements Redu<A,B,C,D,E,F,G,H,I> { private HttpClient httpClient; private final String BASE_URL="http://www.redu.com.br/api/"; private Gson gson; protected Type userList; protected Type statusList; protected Type courseList; protected Type spaceList; protected Type subjectList; protected Type environmentList; protected Type enrollmentList; protected Type chatMessageList; protected Type chatList; protected Class<A> courseClass; protected Class<B> enrollmentClass; protected Class<C> environmentClass; protected Class<D> spaceClass; protected Class<E> subjectClass; protected Class<F> userClass; protected Class<G> statusClass; protected Class<H> chatMessageClass; protected Class<I> chatClass; public ReduClient(String consumerKey, String consumerSecret){ this.initTypes(); this.gson = new Gson(); this.httpClient = new ScribeHttpClient(consumerKey, consumerSecret); } public ReduClient(String consumerKey, String consumerSecret, String pin){ this.initTypes(); this.gson = new Gson(); this.httpClient = new ScribeHttpClient(consumerKey,consumerSecret,pin); } public String getAuthorizeUrl(){ return this.httpClient.getAuthUrl(); } public void initClient(String pin){ this.httpClient.initClient(pin); } /** * Metódo abstrato que inicializa os tipos que representam os recursos da api. * É preciso inicializar TODOS os recursos se não null pointers vão aparecer. */ protected abstract void initTypes(); // private <T> List<T> getUrl(String url, Class<List<T>> classOfT){ // String json = this.httpClient.get(url); // List<T> retorno = this.gson.fromJson(json, classOfT); // return retorno; // } private <T> T getUrl(String url, Class<T> classOfT){ String json = this.httpClient.get(url); T retorno = this.gson.fromJson(json, classOfT); return retorno; } private <T> T getUrl(String url, Class<T> classOfT, Map.Entry<String, String>... args){ String json = this.httpClient.get(url, args); T retorno = this.gson.fromJson(json, classOfT); return retorno; } private <T> T getUrl(String url, Type typeOfT, Map.Entry<String, String>... args){ List<Map.Entry<String, String>> new_args = new ArrayList<Map.Entry<String, String>>(); for(Map.Entry<String, String> o : args){ if(o.getValue() != null){ new_args.add(o); } } String json = ""; if(!new_args.isEmpty()){ - json = this.httpClient.get(url, new_args.toArray(new ArgPair[args.length])); + json = this.httpClient.get(url, new_args.toArray(new ArgPair[new_args.size()])); }else{ json = this.httpClient.get(url); } T retorno = this.gson.fromJson(json, typeOfT); return retorno; } private <T> T getUrl(String url, Type typeOfT){ String json = this.httpClient.get(url); T retorno = this.gson.fromJson(json, typeOfT); return retorno; } private <T> T postUrl(String url, Class<T> classOfT, String payload, Map.Entry<String, String>... args){ String json = this.httpClient.post(url, payload.getBytes(), args); T retorno = this.gson.fromJson(json, classOfT); return retorno; } @Override public A getCourse(String courseId) { return this.getUrl(BASE_URL+"courses/"+courseId, this.courseClass); } @Override public List<A> getCoursesByEnvironment(String environmentId){ return this.getUrl(BASE_URL+"environments/"+environmentId+"/courses", this.courseList); } @Override public A postCourse(String environmentId, String name, String path, String workload, String description) { CoursePayload load = new CoursePayload(name, path, workload, description); String url = BASE_URL+"environments/"+environmentId+"/courses"; String json = this.gson.toJson(load); return this.postUrl(url, this.courseClass, json); } @Override public void editCourse(String courseId, String name, String path, String workload, String description) { CoursePayload load = new CoursePayload(name, path, workload, description); String url = BASE_URL+"courses/"+courseId; String json = this.gson.toJson(load); this.httpClient.put(url,json.getBytes()); } @Override public void deleteCourse(String courseId){ this.httpClient.delete(BASE_URL+"courses/"+courseId); } @Override public B getEnrollment(String enrollmentId) { return this.getUrl(BASE_URL+"enrollments/"+enrollmentId, this.enrollmentClass); } @Override public B postEnrollment(String courseId, String email) { EnrollmentPayload load = new EnrollmentPayload(email); String json = this.gson.toJson(load); String url = BASE_URL+"courses/"+courseId+"/enrollments"; return this.postUrl(url, this.enrollmentClass, json); } @Override public List<B> getEnrollmentsByCourse(String courseId) { return this.getUrl(BASE_URL+"courses/"+courseId+"/enrollments", this.enrollmentList); } @Override public void deleteEnrollment(String enrollmentId) { this.httpClient.delete(BASE_URL+"enrollments/"+enrollmentId); } @Override public List<C> getEnvironments() { return this.getUrl(BASE_URL+"environments/", environmentList); } @Override public C getEnvironment(String environmentId) { return this.getUrl(BASE_URL+"environments/"+environmentId, this.environmentClass); } @Override public C postEnvironment(String name, String path, String initials, String description) { EnvironmentPayload load = new EnvironmentPayload(name, path, initials, description); String json = this.gson.toJson(load); return this.postUrl(BASE_URL+"environments", this.environmentClass, json); } @Override public void editEnvironment(String environmentId, String name, String path, String initials, String description) { EnvironmentPayload load = new EnvironmentPayload(name, path, initials, description); byte[] json = this.gson.toJson(load).getBytes(); this.httpClient.put(BASE_URL+"environments/"+environmentId, json); } @Override public void deleteEnvironment(String environmentId) { this.httpClient.delete(BASE_URL+"environments/"+environmentId); } @Override public D getSpace(String spaceId) { return this.getUrl(BASE_URL+"spaces/"+spaceId, this.spaceClass); } @Override public void editSpace(String spaceId, String name, String description) { SpacePayload load = new SpacePayload(name, description); byte [] json = this.gson.toJson(load).getBytes(); this.httpClient.put(BASE_URL+"spaces/"+spaceId, json); } @Override public D postSpace(String courseId, String name, String description) { SpacePayload load = new SpacePayload(name, description); String url = BASE_URL+"courses/"+courseId+"/spaces"; String json = this.gson.toJson(load); return this.postUrl(url, this.spaceClass, json); } @Override public List<D> getSpacesByCourse(String courseId) { return this.getUrl(BASE_URL+"courses/"+courseId+"/spaces", this.spaceList); } @Override public void deleteSpace(String spaceId) { this.httpClient.delete(BASE_URL+"spaces/"+spaceId); } @Override public E getSubject(String subjectId) { return this.getUrl(BASE_URL+"subjects/"+subjectId, this.subjectClass); } @Override public List<E> getSubjectsBySpace(String spaceId) { return this.getUrl(BASE_URL+"spaces/"+spaceId+"/subjects", this.subjectList); } @Override public E postSubject(String spaceId, String title, String description) { throw new RuntimeException("NOT SUPPORTED YET!"); } @Override public void editSubject(String subjectId, String title, String description) { throw new RuntimeException("NOT SUPPORTED YET!"); } @Override public void deleteSubject(String subjectId) { this.httpClient.delete(BASE_URL+"subjects/"+subjectId); } @Override public F getUser(String userId) { return this.getUrl(BASE_URL+"users/"+userId, this.userClass); } @Override public F getMe() { return this.getUrl(BASE_URL+"me", this.userClass); } @Override public List<F> getUsersBySpace(String spaceId, String role) { ArgPair arg = new ArgPair("role", role); return this.getUrl(BASE_URL+"spaces/"+spaceId+"/users", this.userList, arg); } @Override public G getStatus(String statusId) { return this.getUrl(BASE_URL+"statuses/"+statusId, this.statusClass); } @Override public List<G> getAnswers(String statusId) { return this.getUrl(BASE_URL+"statuses/"+statusId+"/answers",this.statusList); } @Override public G postAnswer(String statusId, String text) { StatusPayload load = new StatusPayload(text); String url = BASE_URL+"statuses/"+statusId+"/answers"; String json = this.gson.toJson(load); return this.postUrl(url, this.statusClass, json); } @Override public List<G> getStatusesByUser(String userId, String type, String page) { Map.Entry<String, String> arg = new ArgPair("type", type); Map.Entry<String, String> arg1 = new ArgPair("page", page); return this.getUrl(BASE_URL+"users/"+userId+"/statuses", this.statusList, arg, arg1); } @Override public List<G> getStatusesTimelineByUser(String userId, String type, String page) { Map.Entry<String, String> arg = new ArgPair("type", type); Map.Entry<String, String> arg1 = new ArgPair("page", String.valueOf(page)); return this.getUrl(BASE_URL+"users/"+userId+"/statuses/timeline", this.statusList, arg, arg1); } @Override public List<G> getStatusesTimelineBySpace(String spaceId, String type, String page) { Map.Entry<String, String> arg = new ArgPair("type", type); Map.Entry<String, String> arg1 = new ArgPair("page", type); return this.getUrl(BASE_URL+"spaces/"+spaceId+"/statuses/timeline", this.statusList, arg, arg1); } @Override public G postStatusUser(String userId, String status) { StatusPayload load = new StatusPayload(status); String url = BASE_URL+"users/"+userId+"/statuses"; String json = this.gson.toJson(load); return this.postUrl(url, this.statusClass, json); } @Override public List<G> getStatusesBySpace(String spaceId, String type, String page) { Map.Entry<String, String> arg = new ArgPair("type", type); Map.Entry<String, String> arg1 = new ArgPair("page", type); return this.getUrl(BASE_URL+"spaces/"+spaceId+"/statuses", this.statusList, arg, arg1); } @Override public G postStatusSpace(String spaceId, String text) { StatusPayload load = new StatusPayload(text); String url = BASE_URL+"spaces/"+spaceId+"/statuses"; String json = this.gson.toJson(load); return this.postUrl(url, this.statusClass, json); } @Override public List<G> getStatusesByLecture(String lectureId) { return this.getUrl(BASE_URL+"lectures/"+lectureId+"/statuses", this.statusList); } @Override public G postStatusLecture(String lectureId, String status, String type) { StatusPayload load = new StatusPayload(status, type); String url = BASE_URL+"lectures/"+lectureId+"/statuses"; String json = this.gson.toJson(load); return this.postUrl(url, this.statusClass, json); } @Override public void deleteStatus(String statusId) { this.httpClient.delete(BASE_URL+"statuses/"+statusId); } @Override public H getChatMessage(String chatMessageId){ return this.getUrl(BASE_URL+"chat_messages/"+chatMessageId, this.chatMessageClass); } @Override public List<H> getChatMessagesByChat(String chatId){ return this.getUrl(BASE_URL+"chats/"+chatId+"/chat_messages", this.chatMessageList); } @Override public I getChat(String chatId){ return this.getUrl(BASE_URL+"chats/"+chatId, this.chatClass); } @Override public List<I> getChatsByUser(String userId){ return this.getUrl(BASE_URL+"users/"+userId+"/chats",this.chatList); } }
true
true
private <T> T getUrl(String url, Type typeOfT, Map.Entry<String, String>... args){ List<Map.Entry<String, String>> new_args = new ArrayList<Map.Entry<String, String>>(); for(Map.Entry<String, String> o : args){ if(o.getValue() != null){ new_args.add(o); } } String json = ""; if(!new_args.isEmpty()){ json = this.httpClient.get(url, new_args.toArray(new ArgPair[args.length])); }else{ json = this.httpClient.get(url); } T retorno = this.gson.fromJson(json, typeOfT); return retorno; }
private <T> T getUrl(String url, Type typeOfT, Map.Entry<String, String>... args){ List<Map.Entry<String, String>> new_args = new ArrayList<Map.Entry<String, String>>(); for(Map.Entry<String, String> o : args){ if(o.getValue() != null){ new_args.add(o); } } String json = ""; if(!new_args.isEmpty()){ json = this.httpClient.get(url, new_args.toArray(new ArgPair[new_args.size()])); }else{ json = this.httpClient.get(url); } T retorno = this.gson.fromJson(json, typeOfT); return retorno; }
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/src/main/java/com/philihp/weblabora/model/building/PilgrimageSite.java b/src/main/java/com/philihp/weblabora/model/building/PilgrimageSite.java index 6494003..6e9d9b1 100644 --- a/src/main/java/com/philihp/weblabora/model/building/PilgrimageSite.java +++ b/src/main/java/com/philihp/weblabora/model/building/PilgrimageSite.java @@ -1,59 +1,62 @@ package com.philihp.weblabora.model.building; import static com.philihp.weblabora.model.TerrainTypeEnum.COAST; import static com.philihp.weblabora.model.TerrainTypeEnum.MOUNTAIN; import static com.philihp.weblabora.model.TerrainTypeEnum.HILLSIDE; import static com.philihp.weblabora.model.TerrainTypeEnum.PLAINS; import java.util.EnumSet; import java.util.Set; import com.philihp.weblabora.model.Board; import com.philihp.weblabora.model.BuildCost; import com.philihp.weblabora.model.Coordinate; import com.philihp.weblabora.model.Landscape; import com.philihp.weblabora.model.Player; import com.philihp.weblabora.model.TerrainTypeEnum; import com.philihp.weblabora.model.UsageParam; import com.philihp.weblabora.model.UsageParamDouble; import com.philihp.weblabora.model.UsageParamSingle; import com.philihp.weblabora.model.WeblaboraException; import com.philihp.weblabora.model.Wheel; public class PilgrimageSite extends BuildingDoubleUsage { public PilgrimageSite() { super("F36", "D", 3, "Pilgrimage Site", BuildCost.is().coin(6), 6, 2, EnumSet.of(PLAINS, HILLSIDE, COAST), false); } @Override public void use(Board board, UsageParamDouble first) throws WeblaboraException { Player player = board.getPlayer(board.getActivePlayer()); UsageParamSingle second = first.getSecondary(); if(first.getBook() + first.getPottery() + first.getOrnament() > 1) throw new WeblaboraException("First parameter may only have one book, pottery, or ornament"); if(second.getBook() + second.getPottery() + second.getOrnament() > 1) throw new WeblaboraException("Second parameter may only have one book, pottery, or ornament"); doIt(player, first); doIt(player, second); } - private void doIt(Player player, UsageParam input) { + private void doIt(Player player, UsageParam input) throws WeblaboraException { if(input.getBook() == 1) { + if(player.getBook() <= 0) throw new WeblaboraException(getName()+" couldn't find a book to convert"); player.subtractBook(input.getBook()); player.addPottery(input.getBook()); } else if(input.getPottery() == 1) { + if(player.getPottery() <= 0) throw new WeblaboraException(getName()+" couldn't find a ceramic to convert"); player.subtractPottery(input.getPottery()); player.addOrnament(input.getPottery()); } else if(input.getOrnament() == 1) { + if(player.getOrnament() <= 0) throw new WeblaboraException(getName()+" couldn't find an ornament to convert"); player.subtractOrnament(input.getOrnament()); player.addReliquary(input.getOrnament()); } } }
false
true
private void doIt(Player player, UsageParam input) { if(input.getBook() == 1) { player.subtractBook(input.getBook()); player.addPottery(input.getBook()); } else if(input.getPottery() == 1) { player.subtractPottery(input.getPottery()); player.addOrnament(input.getPottery()); } else if(input.getOrnament() == 1) { player.subtractOrnament(input.getOrnament()); player.addReliquary(input.getOrnament()); } }
private void doIt(Player player, UsageParam input) throws WeblaboraException { if(input.getBook() == 1) { if(player.getBook() <= 0) throw new WeblaboraException(getName()+" couldn't find a book to convert"); player.subtractBook(input.getBook()); player.addPottery(input.getBook()); } else if(input.getPottery() == 1) { if(player.getPottery() <= 0) throw new WeblaboraException(getName()+" couldn't find a ceramic to convert"); player.subtractPottery(input.getPottery()); player.addOrnament(input.getPottery()); } else if(input.getOrnament() == 1) { if(player.getOrnament() <= 0) throw new WeblaboraException(getName()+" couldn't find an ornament to convert"); player.subtractOrnament(input.getOrnament()); player.addReliquary(input.getOrnament()); } }
diff --git a/qcadoo-view/src/main/java/com/qcadoo/view/internal/components/awesomeDynamicList/AwesomeDynamicListState.java b/qcadoo-view/src/main/java/com/qcadoo/view/internal/components/awesomeDynamicList/AwesomeDynamicListState.java index 2cacb641c..64efc2078 100644 --- a/qcadoo-view/src/main/java/com/qcadoo/view/internal/components/awesomeDynamicList/AwesomeDynamicListState.java +++ b/qcadoo-view/src/main/java/com/qcadoo/view/internal/components/awesomeDynamicList/AwesomeDynamicListState.java @@ -1,208 +1,208 @@ /** * *************************************************************************** * Copyright (c) 2010 Qcadoo Limited * Project: Qcadoo Framework * Version: 1.2.0 * * This file is part of Qcadoo. * * Qcadoo 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 this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *************************************************************************** */ package com.qcadoo.view.internal.components.awesomeDynamicList; import static com.google.common.base.Preconditions.checkNotNull; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.google.common.collect.Lists; import com.qcadoo.model.api.Entity; import com.qcadoo.view.api.components.AwesomeDynamicListComponent; import com.qcadoo.view.api.components.FormComponent; import com.qcadoo.view.internal.api.ContainerState; import com.qcadoo.view.internal.api.InternalComponentState; import com.qcadoo.view.internal.api.InternalViewDefinitionState; import com.qcadoo.view.internal.components.FieldComponentState; import com.qcadoo.view.internal.components.form.FormComponentPattern; import com.qcadoo.view.internal.components.form.FormComponentState; import com.qcadoo.view.internal.internal.ViewDefinitionStateImpl; public class AwesomeDynamicListState extends FieldComponentState implements AwesomeDynamicListComponent, ContainerState { public static final String JSON_FORM_VALUES = "forms"; private final AwesomeDynamicListModelUtils awesomeDynamicListModelUtils; private final FormComponentPattern innerFormPattern; private List<FormComponentState> forms; public AwesomeDynamicListState(final AwesomeDynamicListPattern pattern, final FormComponentPattern innerFormPattern) { super(pattern); this.innerFormPattern = innerFormPattern; this.awesomeDynamicListModelUtils = new AwesomeDynamicListModelUtilsImpl(); } @Override protected void initializeContent(final JSONObject json) throws JSONException { if (json.has(JSON_FORM_VALUES)) { forms = new LinkedList<FormComponentState>(); JSONArray formValues = json.getJSONArray(JSON_FORM_VALUES); for (int i = 0; i < formValues.length(); i++) { JSONObject value = formValues.getJSONObject(i); String formName = value.getString("name"); JSONObject formValue = value.getJSONObject("value"); InternalViewDefinitionState innerFormState = new ViewDefinitionStateImpl(); FormComponentState formState = (FormComponentState) innerFormPattern.createComponentState(innerFormState); formState.setName(formName); innerFormPattern.updateComponentStateListeners(innerFormState); formState.initialize(formValue, getLocale()); forms.add(formState); } } } @SuppressWarnings("unchecked") @Override public void setFieldValue(final Object value) { requestRender(); forms = new LinkedList<FormComponentState>(); - if (value != null) { + if ((value != null) && (value instanceof List)) { List<Entity> entities = (List<Entity>) value; for (Entity entity : entities) { InternalViewDefinitionState innerFormState = new ViewDefinitionStateImpl(); FormComponentState formState = (FormComponentState) innerFormPattern.createComponentState(innerFormState); innerFormPattern.updateComponentStateListeners(innerFormState); try { formState.initialize(new JSONObject(), getLocale()); } catch (JSONException e) { throw new IllegalStateException(e); } formState.setEntity(entity); forms.add(formState); } } } @Override public Object getFieldValue() { List<Entity> entities = new LinkedList<Entity>(); for (FormComponent form : forms) { Entity e = form.getEntity(); awesomeDynamicListModelUtils.proxyBelongsToFields(e); entities.add(e); } return entities; } @Override public JSONObject render() throws JSONException { JSONObject json = super.render(); if (!json.has(JSON_CONTENT)) { JSONObject childerJson = new JSONObject(); for (FormComponentState form : forms) { childerJson.put(form.getName(), form.render()); } JSONObject content = new JSONObject(); content.put("innerFormChanges", childerJson); json.put(JSON_CONTENT, content); } return json; } @Override protected JSONObject renderContent() throws JSONException { JSONObject json = new JSONObject(); JSONArray formValues = new JSONArray(); for (FormComponentState formState : forms) { formValues.put(formState.render()); } json.put(JSON_FORM_VALUES, formValues); json.put(JSON_REQUIRED, isRequired()); return json; } @Override public Map<String, InternalComponentState> getChildren() { Map<String, InternalComponentState> children = new HashMap<String, InternalComponentState>(); for (FormComponentState form : forms) { children.put(form.getName(), form); } return children; } @Override public InternalComponentState getChild(final String name) { for (FormComponentState form : forms) { if (name.equals(form.getName())) { return form; } } return null; } @Override public void addChild(final InternalComponentState state) { } @Override public boolean isHasError() { for (FormComponent form : forms) { if (form.isHasError()) { return true; } } return false; } @Override public List<FormComponent> getFormComponents() { List<FormComponent> formComponents = Lists.newArrayList(); for (FormComponent form : forms) { formComponents.add(form); } return formComponents; } @Override public FormComponent getFormComponent(final Long id) { checkNotNull(id, "id must be given"); for (FormComponent form : forms) { if (id.equals(form.getEntityId())) { return form; } } return null; } @Override public InternalComponentState findChild(final String reference) { InternalComponentState component = null; for (FormComponent form : getFormComponents()) { component = (InternalComponentState) form.findFieldComponentByName(reference); } return component; } }
true
true
public void setFieldValue(final Object value) { requestRender(); forms = new LinkedList<FormComponentState>(); if (value != null) { List<Entity> entities = (List<Entity>) value; for (Entity entity : entities) { InternalViewDefinitionState innerFormState = new ViewDefinitionStateImpl(); FormComponentState formState = (FormComponentState) innerFormPattern.createComponentState(innerFormState); innerFormPattern.updateComponentStateListeners(innerFormState); try { formState.initialize(new JSONObject(), getLocale()); } catch (JSONException e) { throw new IllegalStateException(e); } formState.setEntity(entity); forms.add(formState); } } }
public void setFieldValue(final Object value) { requestRender(); forms = new LinkedList<FormComponentState>(); if ((value != null) && (value instanceof List)) { List<Entity> entities = (List<Entity>) value; for (Entity entity : entities) { InternalViewDefinitionState innerFormState = new ViewDefinitionStateImpl(); FormComponentState formState = (FormComponentState) innerFormPattern.createComponentState(innerFormState); innerFormPattern.updateComponentStateListeners(innerFormState); try { formState.initialize(new JSONObject(), getLocale()); } catch (JSONException e) { throw new IllegalStateException(e); } formState.setEntity(entity); forms.add(formState); } } }
diff --git a/org.eclipse.jgit/src/org/eclipse/jgit/revwalk/RevCommitList.java b/org.eclipse.jgit/src/org/eclipse/jgit/revwalk/RevCommitList.java index 906f27c5..753cbad5 100644 --- a/org.eclipse.jgit/src/org/eclipse/jgit/revwalk/RevCommitList.java +++ b/org.eclipse.jgit/src/org/eclipse/jgit/revwalk/RevCommitList.java @@ -1,359 +1,355 @@ /* * Copyright (C) 2008, Shawn O. Pearce <[email protected]> * and other copyright owners as documented in the project's IP log. * * This program and the accompanying materials are made available * under the terms of the Eclipse Distribution License v1.0 which * accompanies this distribution, is reproduced below, and is * available at http://www.eclipse.org/org/documents/edl-v10.php * * All rights reserved. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * - Neither the name of the Eclipse Foundation, Inc. nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.eclipse.jgit.revwalk; import java.io.IOException; import org.eclipse.jgit.errors.IncorrectObjectTypeException; import org.eclipse.jgit.errors.MissingObjectException; import org.eclipse.jgit.revwalk.filter.RevFilter; /** * An ordered list of {@link RevCommit} subclasses. * * @param <E> * type of subclass of RevCommit the list is storing. */ public class RevCommitList<E extends RevCommit> extends RevObjectList<E> { private RevWalk walker; @Override public void clear() { super.clear(); walker = null; } /** * Apply a flag to all commits matching the specified filter. * <p> * Same as <code>applyFlag(matching, flag, 0, size())</code>, but without * the incremental behavior. * * @param matching * the filter to test commits with. If the filter includes a * commit it will have the flag set; if the filter does not * include the commit the flag will be unset. * @param flag * the flag to apply (or remove). Applications are responsible * for allocating this flag from the source RevWalk. * @throws IOException * revision filter needed to read additional objects, but an * error occurred while reading the pack files or loose objects * of the repository. * @throws IncorrectObjectTypeException * revision filter needed to read additional objects, but an * object was not of the correct type. Repository corruption may * have occurred. * @throws MissingObjectException * revision filter needed to read additional objects, but an * object that should be present was not found. Repository * corruption may have occurred. */ public void applyFlag(final RevFilter matching, final RevFlag flag) throws MissingObjectException, IncorrectObjectTypeException, IOException { applyFlag(matching, flag, 0, size()); } /** * Apply a flag to all commits matching the specified filter. * <p> * This version allows incremental testing and application, such as from a * background thread that needs to periodically halt processing and send * updates to the UI. * * @param matching * the filter to test commits with. If the filter includes a * commit it will have the flag set; if the filter does not * include the commit the flag will be unset. * @param flag * the flag to apply (or remove). Applications are responsible * for allocating this flag from the source RevWalk. * @param rangeBegin * first commit within the list to begin testing at, inclusive. * Must not be negative, but may be beyond the end of the list. * @param rangeEnd * last commit within the list to end testing at, exclusive. If * smaller than or equal to <code>rangeBegin</code> then no * commits will be tested. * @throws IOException * revision filter needed to read additional objects, but an * error occurred while reading the pack files or loose objects * of the repository. * @throws IncorrectObjectTypeException * revision filter needed to read additional objects, but an * object was not of the correct type. Repository corruption may * have occurred. * @throws MissingObjectException * revision filter needed to read additional objects, but an * object that should be present was not found. Repository * corruption may have occurred. */ public void applyFlag(final RevFilter matching, final RevFlag flag, int rangeBegin, int rangeEnd) throws MissingObjectException, IncorrectObjectTypeException, IOException { final RevWalk w = flag.getRevWalk(); rangeEnd = Math.min(rangeEnd, size()); while (rangeBegin < rangeEnd) { int index = rangeBegin; Block s = contents; while (s.shift > 0) { final int i = index >> s.shift; index -= i << s.shift; s = (Block) s.contents[i]; } while (rangeBegin++ < rangeEnd && index < BLOCK_SIZE) { final RevCommit c = (RevCommit) s.contents[index++]; if (matching.include(w, c)) c.add(flag); else c.remove(flag); } } } /** * Remove the given flag from all commits. * <p> * Same as <code>clearFlag(flag, 0, size())</code>, but without the * incremental behavior. * * @param flag * the flag to remove. Applications are responsible for * allocating this flag from the source RevWalk. */ public void clearFlag(final RevFlag flag) { clearFlag(flag, 0, size()); } /** * Remove the given flag from all commits. * <p> * This method is actually implemented in terms of: * <code>applyFlag(RevFilter.NONE, flag, rangeBegin, rangeEnd)</code>. * * @param flag * the flag to remove. Applications are responsible for * allocating this flag from the source RevWalk. * @param rangeBegin * first commit within the list to begin testing at, inclusive. * Must not be negative, but may be beyond the end of the list. * @param rangeEnd * last commit within the list to end testing at, exclusive. If * smaller than or equal to <code>rangeBegin</code> then no * commits will be tested. */ public void clearFlag(final RevFlag flag, final int rangeBegin, final int rangeEnd) { try { applyFlag(RevFilter.NONE, flag, rangeBegin, rangeEnd); } catch (IOException e) { // Never happen. The filter we use does not throw any // exceptions, for any reason. } } /** * Find the next commit that has the given flag set. * * @param flag * the flag to test commits against. * @param begin * first commit index to test at. Applications may wish to begin * at 0, to test the first commit in the list. * @return index of the first commit at or after index <code>begin</code> * that has the specified flag set on it; -1 if no match is found. */ public int indexOf(final RevFlag flag, int begin) { while (begin < size()) { int index = begin; Block s = contents; while (s.shift > 0) { final int i = index >> s.shift; index -= i << s.shift; s = (Block) s.contents[i]; } while (begin++ < size() && index < BLOCK_SIZE) { final RevCommit c = (RevCommit) s.contents[index++]; if (c.has(flag)) return begin; } } return -1; } /** * Find the next commit that has the given flag set. * * @param flag * the flag to test commits against. * @param begin * first commit index to test at. Applications may wish to begin * at <code>size()-1</code>, to test the last commit in the * list. * @return index of the first commit at or before index <code>begin</code> * that has the specified flag set on it; -1 if no match is found. */ public int lastIndexOf(final RevFlag flag, int begin) { begin = Math.min(begin, size() - 1); while (begin >= 0) { int index = begin; Block s = contents; while (s.shift > 0) { final int i = index >> s.shift; index -= i << s.shift; s = (Block) s.contents[i]; } while (begin-- >= 0 && index >= 0) { final RevCommit c = (RevCommit) s.contents[index--]; if (c.has(flag)) return begin; } } return -1; } /** * Set the revision walker this list populates itself from. * * @param w * the walker to populate from. * @see #fillTo(int) */ public void source(final RevWalk w) { walker = w; } /** * Is this list still pending more items? * * @return true if {@link #fillTo(int)} might be able to extend the list * size when called. */ public boolean isPending() { return walker != null; } /** * Ensure this list contains at least a specified number of commits. * <p> * The revision walker specified by {@link #source(RevWalk)} is pumped until * the given number of commits are contained in this list. If there are * fewer total commits available from the walk then the method will return * early. Callers can test the final size of the list by {@link #size()} to * determine if the high water mark specified was met. * * @param highMark * number of commits the caller wants this list to contain when * the fill operation is complete. * @throws IOException * see {@link RevWalk#next()} * @throws IncorrectObjectTypeException * see {@link RevWalk#next()} * @throws MissingObjectException * see {@link RevWalk#next()} */ public void fillTo(final int highMark) throws MissingObjectException, IncorrectObjectTypeException, IOException { if (walker == null || size > highMark) return; - Generator p = walker.pending; - RevCommit c = p.next(); + RevCommit c = walker.next(); if (c == null) { - walker.pending = EndGenerator.INSTANCE; walker = null; return; } enter(size, (E) c); add((E) c); - p = walker.pending; while (size <= highMark) { int index = size; Block s = contents; while (index >> s.shift >= BLOCK_SIZE) { s = new Block(s.shift + BLOCK_SHIFT); s.contents[0] = contents; contents = s; } while (s.shift > 0) { final int i = index >> s.shift; index -= i << s.shift; if (s.contents[i] == null) s.contents[i] = new Block(s.shift - BLOCK_SHIFT); s = (Block) s.contents[i]; } final Object[] dst = s.contents; while (size <= highMark && index < BLOCK_SIZE) { - c = p.next(); + c = walker.next(); if (c == null) { - walker.pending = EndGenerator.INSTANCE; walker = null; return; } enter(size++, (E) c); dst[index++] = c; } } } /** * Optional callback invoked when commits enter the list by fillTo. * <p> * This method is only called during {@link #fillTo(int)}. * * @param index * the list position this object will appear at. * @param e * the object being added (or set) into the list. */ protected void enter(final int index, final E e) { // Do nothing by default. } }
false
true
public void fillTo(final int highMark) throws MissingObjectException, IncorrectObjectTypeException, IOException { if (walker == null || size > highMark) return; Generator p = walker.pending; RevCommit c = p.next(); if (c == null) { walker.pending = EndGenerator.INSTANCE; walker = null; return; } enter(size, (E) c); add((E) c); p = walker.pending; while (size <= highMark) { int index = size; Block s = contents; while (index >> s.shift >= BLOCK_SIZE) { s = new Block(s.shift + BLOCK_SHIFT); s.contents[0] = contents; contents = s; } while (s.shift > 0) { final int i = index >> s.shift; index -= i << s.shift; if (s.contents[i] == null) s.contents[i] = new Block(s.shift - BLOCK_SHIFT); s = (Block) s.contents[i]; } final Object[] dst = s.contents; while (size <= highMark && index < BLOCK_SIZE) { c = p.next(); if (c == null) { walker.pending = EndGenerator.INSTANCE; walker = null; return; } enter(size++, (E) c); dst[index++] = c; } } }
public void fillTo(final int highMark) throws MissingObjectException, IncorrectObjectTypeException, IOException { if (walker == null || size > highMark) return; RevCommit c = walker.next(); if (c == null) { walker = null; return; } enter(size, (E) c); add((E) c); while (size <= highMark) { int index = size; Block s = contents; while (index >> s.shift >= BLOCK_SIZE) { s = new Block(s.shift + BLOCK_SHIFT); s.contents[0] = contents; contents = s; } while (s.shift > 0) { final int i = index >> s.shift; index -= i << s.shift; if (s.contents[i] == null) s.contents[i] = new Block(s.shift - BLOCK_SHIFT); s = (Block) s.contents[i]; } final Object[] dst = s.contents; while (size <= highMark && index < BLOCK_SIZE) { c = walker.next(); if (c == null) { walker = null; return; } enter(size++, (E) c); dst[index++] = c; } } }
diff --git a/src/org/mvnsearch/snippet/impl/dzone/DzoneSnippetSearchAgent.java b/src/org/mvnsearch/snippet/impl/dzone/DzoneSnippetSearchAgent.java index 0a6e9a0..6068756 100644 --- a/src/org/mvnsearch/snippet/impl/dzone/DzoneSnippetSearchAgent.java +++ b/src/org/mvnsearch/snippet/impl/dzone/DzoneSnippetSearchAgent.java @@ -1,216 +1,221 @@ package org.mvnsearch.snippet.impl.dzone; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringEscapeUtils; import org.htmlparser.Node; import org.htmlparser.Parser; import org.htmlparser.filters.HasAttributeFilter; import org.htmlparser.tags.Div; import org.htmlparser.tags.LinkTag; import org.htmlparser.util.NodeList; import org.mvnsearch.snippet.Category; import org.mvnsearch.snippet.Comment; import org.mvnsearch.snippet.Snippet; import org.mvnsearch.snippet.SnippetSearchAgent; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * dzone snippet search agent * * @author [email protected] */ public class DzoneSnippetSearchAgent extends SnippetSearchAgent { /** * agent id * * @return agent id */ public String getId() { return "dzone"; } /** * Just a convenient method to display the source of the search in the results tree of iSnippet. * * @return brief text about the source from where the results were found */ public String getDisplayName() { return "DZone Snippets"; } /** * The actual web URL * * @return url from where the results were found */ public String getHomePageURL() { return "http://snippets.dzone.com"; } /** * Detailed description of the site providing these snippets. * * @return agent description */ public String getDescription() { return "Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world "; } /** * Performs the search for given keywords * * @param keywords - Array of keywords * @return Matching araaylist of the ISnippets */ public List<Snippet> query(String[] keywords) { List<Snippet> snippets = new ArrayList<Snippet>(); try { String searchUrl = "http://snippets.dzone.com/search/get_results?q=" + StringUtils.join(keywords, "+"); Parser parser = new Parser(); parser.setURL(searchUrl); NodeList nodeList = parser.extractAllNodesThatMatch(new HasAttributeFilter("class", "post")); for (Node node : nodeList.toNodeArray()) { if (node instanceof Div) { Div postTag = (Div) node; Snippet snippet = constructSnippetFromDivTag(postTag); if (snippet != null) snippets.add(snippet); } } } catch (Exception e) { e.printStackTrace(); } return snippets; } /** * construct snippet from post div tag * * @param postTag post div tag * @return snippet object */ private Snippet constructSnippetFromDivTag(Div postTag) { Snippet snippet = new Snippet(); LinkTag titleTag = (LinkTag) postTag.getChild(1).getChildren().elementAt(0); snippet.setTitle(titleTag.getLinkText()); snippet.setId(titleTag.getLink().substring(titleTag.getLink().lastIndexOf("/") + 1)); Div postBodyTag = (Div) postTag.getChild(3); - int dawnStart = postBodyTag.getChildrenHTML().indexOf("<pre class=\"dawn\">"); + String anchor="<pre class=\"dawn\">"; + int dawnStart = postBodyTag.getChildrenHTML().indexOf(anchor); + if(dawnStart == -1) { + anchor="<pre class=\"sunburst\">"; + dawnStart = postBodyTag.getChildrenHTML().indexOf(anchor); + } //if no code present, ignore it if (dawnStart == -1) return null; String description = postBodyTag.getChildrenHTML().substring(0, dawnStart).trim(); if (description.startsWith("//")) { description = description.substring(2); } snippet.setDescription(description); int dawnEnd = postBodyTag.getChildrenHTML().indexOf("</pre>", dawnStart); - String code = postBodyTag.getChildrenHTML().substring(dawnStart + 18, dawnEnd); + String code = postBodyTag.getChildrenHTML().substring(dawnStart + anchor.length(), dawnEnd); //clean line number code = code.replaceAll("<span class=\"line-numbers\">.*?</span>", ""); //clean html tag code = code.replaceAll("</?\\w+((\\s+\\w+(\\s*=\\s*(?:\".*?\"|'.*?'|[^'\">\\s]+))?)+\\s*|\\s*)/?>", ""); code = StringEscapeUtils.unescapeHtml(code); snippet.setCode(code); Div postMetaTag = (Div) postTag.getChild(5); int authorStart = postMetaTag.getChildrenHTML().indexOf("<a href=\"/user/") + 15; String author = postMetaTag.getChildrenHTML().substring(authorStart, postMetaTag.getChildrenHTML().indexOf("\"", authorStart)); snippet.setAuthor(author); snippet.setDetailUrl("http://snippets.dzone.com/posts/show/"+snippet.getId()); return snippet; } /** * find snippets according to snippets * * @param categoryId category id * @return snippet list */ public List<Snippet> findSnippetsByCategory(String categoryId) { return null; //To change body of implemented methods use File | Settings | File Templates. } /** * find recent added snippets for RSS * * @return snippets */ public List<Snippet> findRecentAddedSnippets() { return null; //To change body of implemented methods use File | Settings | File Templates. } /** * find snippet by id * * @param snippetId snippet id * @return snippet object */ public Snippet findById(String snippetId) { try { String searchUrl = "http://snippets.dzone.com/posts/show/" + snippetId; Parser parser = new Parser(); parser.setURL(searchUrl); NodeList nodeList = parser.extractAllNodesThatMatch(new HasAttributeFilter("class", "post")); for (Node node : nodeList.toNodeArray()) { if (node instanceof Div) { Div postTag = (Div) node; Snippet snippet = constructSnippetFromDivTag(postTag); if (snippet != null) return snippet; } } } catch (Exception e) { } return null; } /** * update snippet category * * @param snippet snippet object * @return result */ public boolean updateSnippet(Snippet snippet) { return false; //To change body of implemented methods use File | Settings | File Templates. } /** * find snippet comment * * @param snippetId snippet id * @return comment list */ public List<Comment> findComments(String snippetId) { return null; //To change body of implemented methods use File | Settings | File Templates. } /** * add comment * * @param snippetId snippet id * @param comment comment * @return result */ public boolean addSnippetComment(String snippetId, Comment comment) { return false; //To change body of implemented methods use File | Settings | File Templates. } /** * get category list * * @return category list */ public Collection<Category> findRootCategories() { return null; //To change body of implemented methods use File | Settings | File Templates. } /** * get content type for code text/plain, text/html * * @return content type for code */ public String getCodeContentType() { return "text/palin"; } }
false
true
private Snippet constructSnippetFromDivTag(Div postTag) { Snippet snippet = new Snippet(); LinkTag titleTag = (LinkTag) postTag.getChild(1).getChildren().elementAt(0); snippet.setTitle(titleTag.getLinkText()); snippet.setId(titleTag.getLink().substring(titleTag.getLink().lastIndexOf("/") + 1)); Div postBodyTag = (Div) postTag.getChild(3); int dawnStart = postBodyTag.getChildrenHTML().indexOf("<pre class=\"dawn\">"); //if no code present, ignore it if (dawnStart == -1) return null; String description = postBodyTag.getChildrenHTML().substring(0, dawnStart).trim(); if (description.startsWith("//")) { description = description.substring(2); } snippet.setDescription(description); int dawnEnd = postBodyTag.getChildrenHTML().indexOf("</pre>", dawnStart); String code = postBodyTag.getChildrenHTML().substring(dawnStart + 18, dawnEnd); //clean line number code = code.replaceAll("<span class=\"line-numbers\">.*?</span>", ""); //clean html tag code = code.replaceAll("</?\\w+((\\s+\\w+(\\s*=\\s*(?:\".*?\"|'.*?'|[^'\">\\s]+))?)+\\s*|\\s*)/?>", ""); code = StringEscapeUtils.unescapeHtml(code); snippet.setCode(code); Div postMetaTag = (Div) postTag.getChild(5); int authorStart = postMetaTag.getChildrenHTML().indexOf("<a href=\"/user/") + 15; String author = postMetaTag.getChildrenHTML().substring(authorStart, postMetaTag.getChildrenHTML().indexOf("\"", authorStart)); snippet.setAuthor(author); snippet.setDetailUrl("http://snippets.dzone.com/posts/show/"+snippet.getId()); return snippet; }
private Snippet constructSnippetFromDivTag(Div postTag) { Snippet snippet = new Snippet(); LinkTag titleTag = (LinkTag) postTag.getChild(1).getChildren().elementAt(0); snippet.setTitle(titleTag.getLinkText()); snippet.setId(titleTag.getLink().substring(titleTag.getLink().lastIndexOf("/") + 1)); Div postBodyTag = (Div) postTag.getChild(3); String anchor="<pre class=\"dawn\">"; int dawnStart = postBodyTag.getChildrenHTML().indexOf(anchor); if(dawnStart == -1) { anchor="<pre class=\"sunburst\">"; dawnStart = postBodyTag.getChildrenHTML().indexOf(anchor); } //if no code present, ignore it if (dawnStart == -1) return null; String description = postBodyTag.getChildrenHTML().substring(0, dawnStart).trim(); if (description.startsWith("//")) { description = description.substring(2); } snippet.setDescription(description); int dawnEnd = postBodyTag.getChildrenHTML().indexOf("</pre>", dawnStart); String code = postBodyTag.getChildrenHTML().substring(dawnStart + anchor.length(), dawnEnd); //clean line number code = code.replaceAll("<span class=\"line-numbers\">.*?</span>", ""); //clean html tag code = code.replaceAll("</?\\w+((\\s+\\w+(\\s*=\\s*(?:\".*?\"|'.*?'|[^'\">\\s]+))?)+\\s*|\\s*)/?>", ""); code = StringEscapeUtils.unescapeHtml(code); snippet.setCode(code); Div postMetaTag = (Div) postTag.getChild(5); int authorStart = postMetaTag.getChildrenHTML().indexOf("<a href=\"/user/") + 15; String author = postMetaTag.getChildrenHTML().substring(authorStart, postMetaTag.getChildrenHTML().indexOf("\"", authorStart)); snippet.setAuthor(author); snippet.setDetailUrl("http://snippets.dzone.com/posts/show/"+snippet.getId()); return snippet; }
diff --git a/perun-core/src/main/java/cz/metacentrum/perun/core/impl/AuthzResolverImpl.java b/perun-core/src/main/java/cz/metacentrum/perun/core/impl/AuthzResolverImpl.java index 9603cac8c..d5a043552 100644 --- a/perun-core/src/main/java/cz/metacentrum/perun/core/impl/AuthzResolverImpl.java +++ b/perun-core/src/main/java/cz/metacentrum/perun/core/impl/AuthzResolverImpl.java @@ -1,176 +1,176 @@ package cz.metacentrum.perun.core.impl; import cz.metacentrum.perun.core.api.ActionType; import cz.metacentrum.perun.core.api.AttributeDefinition; import cz.metacentrum.perun.core.api.Group; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.sql.DataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.simple.SimpleJdbcTemplate; import cz.metacentrum.perun.core.api.Member; import cz.metacentrum.perun.core.api.Pair; import cz.metacentrum.perun.core.api.PerunSession; import cz.metacentrum.perun.core.api.Resource; import cz.metacentrum.perun.core.api.Role; import cz.metacentrum.perun.core.api.User; import cz.metacentrum.perun.core.api.exceptions.InternalErrorException; import cz.metacentrum.perun.core.api.exceptions.rt.InternalErrorRuntimeException; import cz.metacentrum.perun.core.implApi.AuthzResolverImplApi; import org.springframework.dao.EmptyResultDataAccessException; public class AuthzResolverImpl implements AuthzResolverImplApi { final static Logger log = LoggerFactory.getLogger(FacilitiesManagerImpl.class); //http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/jdbc.html private static SimpleJdbcTemplate jdbc; private final static Pattern patternForExtractingPerunBean = Pattern.compile("^pb_([a-z]+)_id$"); public final static String authzRoleMappingSelectQuery = " authz.user_id as authz_user_id, authz.role_id as authz_role_id," + "authz.authorized_group_id as authz_authorized_group_id, authz.vo_id as pb_vo_id, authz.group_id as pb_group_id, " + "authz.facility_id as pb_facility_id, authz.member_id as pb_member_id, authz.resource_id as pb_resource_id, " + "authz.service_id as pb_service_id, authz.service_principal_id as pb_user_id"; protected static final RowMapper<Role> AUTHZROLE_MAPPER_FOR_ATTRIBUTES = new RowMapper<Role>() { public Role mapRow(ResultSet rs, int i) throws SQLException { Role role = Role.valueOf(rs.getString("name").toUpperCase()); return role; } }; public static final RowMapper<Pair<Role, Map<String, List<Integer>>>> AUTHZROLE_MAPPER = new RowMapper<Pair<Role, Map<String, List<Integer>>>>() { public Pair<Role, Map<String, List<Integer>>> mapRow(ResultSet rs, int i) throws SQLException { try { Map<String, List<Integer>> perunBeans = null; Role role = Role.valueOf(rs.getString("role_name").toUpperCase()); // Iterate through all returned columns and try to extract PerunBean name from the labels for (int j = rs.getMetaData().getColumnCount(); j > 0; j--) { Matcher matcher = patternForExtractingPerunBean.matcher(rs.getMetaData().getColumnLabel(j).toLowerCase()); if (matcher.find()) { String perunBeanName = matcher.group(1); int id = rs.getInt(j); if (!rs.wasNull()) { // We have to make first letter upercase String className = perunBeanName.substring(0, 1).toUpperCase() + perunBeanName.substring(1); if (perunBeans == null) { perunBeans = new HashMap<String, List<Integer>>(); } if (perunBeans.get(className) == null) { perunBeans.put(className, new ArrayList<Integer>()); } perunBeans.get(className).add(id); } } } return new Pair<Role, Map<String, List<Integer>>>(role, perunBeans); } catch (Exception e) { throw new InternalErrorRuntimeException(e); } } }; public AuthzResolverImpl(DataSource perunPool) { jdbc = new SimpleJdbcTemplate(perunPool); } public AuthzRoles getRoles(User user) throws InternalErrorException { AuthzRoles authzRoles = new AuthzRoles(); if (user != null) { try { // Get roles from Authz table List<Pair<Role, Map<String, List<Integer>>>> authzRolesPairs = jdbc.query("select " + authzRoleMappingSelectQuery + ", roles.name as role_name from authz left join roles on authz.role_id=roles.id where authz.user_id=? or authorized_group_id in " + "(select groups.id from groups join groups_members on groups.id=groups_members.group_id join members on " + "members.id=groups_members.member_id join users on users.id=members.user_id where users.id=?)", AUTHZROLE_MAPPER, user.getId(), user.getId()); for (Pair<Role, Map<String, List<Integer>>> pair : authzRolesPairs) { authzRoles.putAuthzRoles(pair.getLeft(), pair.getRight()); } // Get service users for user List<Integer> authzServiceUsers = jdbc.query("select service_user_users.service_user_id as id from users, " + - "service_user_users where users.id=service_user_users.user_id and service_user_users='0' and users.id=?", Utils.ID_MAPPER ,user.getId()); + "service_user_users where users.id=service_user_users.user_id and service_user_users.status='0' and users.id=?", Utils.ID_MAPPER ,user.getId()); for (Integer serviceUserId : authzServiceUsers) { authzRoles.putAuthzRole(Role.SELF, User.class, serviceUserId); } // Get members for user List<Integer> authzMember = jdbc.query("select members.id as id from members where members.user_id=?", Utils.ID_MAPPER ,user.getId()); for (Integer memberId : authzMember) { authzRoles.putAuthzRole(Role.SELF, Member.class, memberId); } } catch (RuntimeException e) { throw new InternalErrorException(e); } } return authzRoles; } public void initialize() throws InternalErrorException { // Check if all roles defined in class Role exists in the DB for (Role role: Role.values()) { try { if (0 == jdbc.queryForInt("select count(*) from roles where name=?", role.getRoleName())) { int newId = Utils.getNewId(jdbc, "roles_id_seq"); jdbc.update("insert into roles (id, name) values (?,?)", newId, role.getRoleName()); } } catch (RuntimeException e) { throw new InternalErrorException(e); } } } public static List<Role> getRolesWhichCanWorkWithAttribute(PerunSession sess, ActionType actionType, AttributeDefinition attrDef) throws InternalErrorException { String actType = actionType.getActionType().toLowerCase(); try { return jdbc.query("select distinct roles.name from attributes_authz " + "join roles on attributes_authz.role_id=roles.id " + "join action_types on attributes_authz.action_type_id=action_types.id " + "where attributes_authz.attr_id=? and action_types.action_type=?", AUTHZROLE_MAPPER_FOR_ATTRIBUTES, attrDef.getId(), actType); } catch (EmptyResultDataAccessException e) { return new ArrayList<Role>(); } catch (RuntimeException e) { throw new InternalErrorException(e); } } public void removeAllUserAuthz(PerunSession sess, User user) throws InternalErrorException { try { jdbc.update("delete from authz where user_id=?", user.getId()); } catch (RuntimeException e) { throw new InternalErrorException(e); } } public void removeAllGroupAuthz(PerunSession sess, Group group) throws InternalErrorException { try { jdbc.update("delete from authz where authorized_group_id=?", group.getId()); } catch (RuntimeException e) { throw new InternalErrorException(e); } } }
true
true
public AuthzRoles getRoles(User user) throws InternalErrorException { AuthzRoles authzRoles = new AuthzRoles(); if (user != null) { try { // Get roles from Authz table List<Pair<Role, Map<String, List<Integer>>>> authzRolesPairs = jdbc.query("select " + authzRoleMappingSelectQuery + ", roles.name as role_name from authz left join roles on authz.role_id=roles.id where authz.user_id=? or authorized_group_id in " + "(select groups.id from groups join groups_members on groups.id=groups_members.group_id join members on " + "members.id=groups_members.member_id join users on users.id=members.user_id where users.id=?)", AUTHZROLE_MAPPER, user.getId(), user.getId()); for (Pair<Role, Map<String, List<Integer>>> pair : authzRolesPairs) { authzRoles.putAuthzRoles(pair.getLeft(), pair.getRight()); } // Get service users for user List<Integer> authzServiceUsers = jdbc.query("select service_user_users.service_user_id as id from users, " + "service_user_users where users.id=service_user_users.user_id and service_user_users='0' and users.id=?", Utils.ID_MAPPER ,user.getId()); for (Integer serviceUserId : authzServiceUsers) { authzRoles.putAuthzRole(Role.SELF, User.class, serviceUserId); } // Get members for user List<Integer> authzMember = jdbc.query("select members.id as id from members where members.user_id=?", Utils.ID_MAPPER ,user.getId()); for (Integer memberId : authzMember) { authzRoles.putAuthzRole(Role.SELF, Member.class, memberId); } } catch (RuntimeException e) { throw new InternalErrorException(e); } } return authzRoles; }
public AuthzRoles getRoles(User user) throws InternalErrorException { AuthzRoles authzRoles = new AuthzRoles(); if (user != null) { try { // Get roles from Authz table List<Pair<Role, Map<String, List<Integer>>>> authzRolesPairs = jdbc.query("select " + authzRoleMappingSelectQuery + ", roles.name as role_name from authz left join roles on authz.role_id=roles.id where authz.user_id=? or authorized_group_id in " + "(select groups.id from groups join groups_members on groups.id=groups_members.group_id join members on " + "members.id=groups_members.member_id join users on users.id=members.user_id where users.id=?)", AUTHZROLE_MAPPER, user.getId(), user.getId()); for (Pair<Role, Map<String, List<Integer>>> pair : authzRolesPairs) { authzRoles.putAuthzRoles(pair.getLeft(), pair.getRight()); } // Get service users for user List<Integer> authzServiceUsers = jdbc.query("select service_user_users.service_user_id as id from users, " + "service_user_users where users.id=service_user_users.user_id and service_user_users.status='0' and users.id=?", Utils.ID_MAPPER ,user.getId()); for (Integer serviceUserId : authzServiceUsers) { authzRoles.putAuthzRole(Role.SELF, User.class, serviceUserId); } // Get members for user List<Integer> authzMember = jdbc.query("select members.id as id from members where members.user_id=?", Utils.ID_MAPPER ,user.getId()); for (Integer memberId : authzMember) { authzRoles.putAuthzRole(Role.SELF, Member.class, memberId); } } catch (RuntimeException e) { throw new InternalErrorException(e); } } return authzRoles; }
diff --git a/src/bengo/data_fetcher/ReadAction.java b/src/bengo/data_fetcher/ReadAction.java index 78c07f2..1cefb9b 100644 --- a/src/bengo/data_fetcher/ReadAction.java +++ b/src/bengo/data_fetcher/ReadAction.java @@ -1,64 +1,64 @@ package bengo.data_fetcher; import bengo.Bengo; public class ReadAction{ int startCycle; // DataAction will set this in update int neededCycles; Cache cache; Memory mem; int address; public ReadAction(int startCycle, int neededCycles, Memory mem, Cache cache, int address) {; this.startCycle = startCycle; this.neededCycles = neededCycles; this.cache = cache; this.mem = mem; this.address = address; } public void update() { if (Bengo.CURRENT_CYCLE == startCycle + neededCycles - 1) { if (cache != null) { // write to cache action System.out.println("Read from cache " + cache.name + " address: " + address + " word: " + getData()+ " at cycle: " + Bengo.CURRENT_CYCLE); } else { System.out.println("Read from mem " + " address: " + address + " word: " + getData() + " at cycle: " + Bengo.CURRENT_CYCLE); } } } public short getData() { if (isReady()) { if (cache != null) { int offset = cache.map(address)[2]; short[] block = cache.read(address); if (block == null) return -1; else - return block[offset << 2]; + return block[offset >> 2]; } else { return mem.read(address); } } return -555; } public boolean isReady() { return (Bengo.CURRENT_CYCLE == startCycle + neededCycles - 1); } public String toString() { String s = "start: " + startCycle; s += " needed: " + neededCycles; s += " address: " + address; s += " word: " + getData(); s += " from "; s += cache == null? "Memory" : cache.name; return s; } }
true
true
public short getData() { if (isReady()) { if (cache != null) { int offset = cache.map(address)[2]; short[] block = cache.read(address); if (block == null) return -1; else return block[offset << 2]; } else { return mem.read(address); } } return -555; }
public short getData() { if (isReady()) { if (cache != null) { int offset = cache.map(address)[2]; short[] block = cache.read(address); if (block == null) return -1; else return block[offset >> 2]; } else { return mem.read(address); } } return -555; }
diff --git a/org.thingml.parser/src/main/java/org/sintef/thingml/resource/thingml/analysis/ThingMLModelImportsReferenceResolver.java b/org.thingml.parser/src/main/java/org/sintef/thingml/resource/thingml/analysis/ThingMLModelImportsReferenceResolver.java index ea709fec0..37add1d22 100644 --- a/org.thingml.parser/src/main/java/org/sintef/thingml/resource/thingml/analysis/ThingMLModelImportsReferenceResolver.java +++ b/org.thingml.parser/src/main/java/org/sintef/thingml/resource/thingml/analysis/ThingMLModelImportsReferenceResolver.java @@ -1,66 +1,69 @@ /** * Copyright (C) 2011 SINTEF <[email protected]> * * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3, 29 June 2007; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.gnu.org/licenses/lgpl-3.0.txt * * 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. */ /** * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3, 29 June 2007; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.gnu.org/licenses/lgpl-3.0.txt * * 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.sintef.thingml.resource.thingml.analysis; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; import org.eclipse.emf.ecore.util.EcoreUtil; import org.sintef.thingml.ThingMLModel; public class ThingMLModelImportsReferenceResolver implements org.sintef.thingml.resource.thingml.IThingmlReferenceResolver<org.sintef.thingml.ThingMLModel, org.sintef.thingml.ThingMLModel> { private org.sintef.thingml.resource.thingml.analysis.ThingmlDefaultResolverDelegate<org.sintef.thingml.ThingMLModel, org.sintef.thingml.ThingMLModel> delegate = new org.sintef.thingml.resource.thingml.analysis.ThingmlDefaultResolverDelegate<org.sintef.thingml.ThingMLModel, org.sintef.thingml.ThingMLModel>(); public void resolve(java.lang.String identifier, org.sintef.thingml.ThingMLModel container, org.eclipse.emf.ecore.EReference reference, int position, boolean resolveFuzzy, final org.sintef.thingml.resource.thingml.IThingmlReferenceResolveResult<org.sintef.thingml.ThingMLModel> result) { try { URI uri = URI.createURI(identifier).resolve(container.eResource().getURI()); + //System.out.println("identifier = " + identifier + " container.eResource().getURI() = " + container.eResource().getURI()); + //System.out.println("uri = " + uri); //Resource r = container.eResource().getResourceSet().getResource(uri, true); Resource r = new ResourceSetImpl().getResource(uri, true); r.load(null); ThingMLModel m = (ThingMLModel)r.getContents().get(0); result.addMapping(identifier, m); } catch (ClassCastException e) { result.setErrorMessage("The given URI contains a model with a wrong type"); } catch (Exception e) { - result.setErrorMessage("Unable to load model with uri: " + identifier); + //e.printStackTrace(); + result.setErrorMessage("Unable to load model with uri: " + identifier + " cause: " + e.getMessage()); } } public java.lang.String deResolve(org.sintef.thingml.ThingMLModel element, org.sintef.thingml.ThingMLModel container, org.eclipse.emf.ecore.EReference reference) { return element.eResource().getURI().toString(); } public void setOptions(java.util.Map<?,?> options) { // save options in a field or leave method empty if this resolver does not depend on any option } }
false
true
public void resolve(java.lang.String identifier, org.sintef.thingml.ThingMLModel container, org.eclipse.emf.ecore.EReference reference, int position, boolean resolveFuzzy, final org.sintef.thingml.resource.thingml.IThingmlReferenceResolveResult<org.sintef.thingml.ThingMLModel> result) { try { URI uri = URI.createURI(identifier).resolve(container.eResource().getURI()); //Resource r = container.eResource().getResourceSet().getResource(uri, true); Resource r = new ResourceSetImpl().getResource(uri, true); r.load(null); ThingMLModel m = (ThingMLModel)r.getContents().get(0); result.addMapping(identifier, m); } catch (ClassCastException e) { result.setErrorMessage("The given URI contains a model with a wrong type"); } catch (Exception e) { result.setErrorMessage("Unable to load model with uri: " + identifier); } }
public void resolve(java.lang.String identifier, org.sintef.thingml.ThingMLModel container, org.eclipse.emf.ecore.EReference reference, int position, boolean resolveFuzzy, final org.sintef.thingml.resource.thingml.IThingmlReferenceResolveResult<org.sintef.thingml.ThingMLModel> result) { try { URI uri = URI.createURI(identifier).resolve(container.eResource().getURI()); //System.out.println("identifier = " + identifier + " container.eResource().getURI() = " + container.eResource().getURI()); //System.out.println("uri = " + uri); //Resource r = container.eResource().getResourceSet().getResource(uri, true); Resource r = new ResourceSetImpl().getResource(uri, true); r.load(null); ThingMLModel m = (ThingMLModel)r.getContents().get(0); result.addMapping(identifier, m); } catch (ClassCastException e) { result.setErrorMessage("The given URI contains a model with a wrong type"); } catch (Exception e) { //e.printStackTrace(); result.setErrorMessage("Unable to load model with uri: " + identifier + " cause: " + e.getMessage()); } }
diff --git a/source/de/anomic/http/httpdFileHandler.java b/source/de/anomic/http/httpdFileHandler.java index ae217dc25..ba6274331 100644 --- a/source/de/anomic/http/httpdFileHandler.java +++ b/source/de/anomic/http/httpdFileHandler.java @@ -1,1006 +1,1006 @@ // httpdFileHandler.java // ----------------------- // (C) by Michael Peter Christen; [email protected] // first published on http://www.anomic.de // Frankfurt, Germany, 2004, 2005 // last major change: 05.10.2005 // // 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 // // Using this software in any meaning (reading, learning, copying, compiling, // running) means that you agree that the Author(s) is (are) not responsible // for cost, loss of data or any harm that may be caused directly or indirectly // by usage of this softare or this documentation. The usage of this software // is on your own risk. The installation and usage (starting/running) of this // software may allow other people or application to access your computer and // any attached devices and is highly dependent on the configuration of the // software which must be done by the user of the software; the author(s) is // (are) also not responsible for proper configuration and usage of the // software, even if provoked by documentation provided together with // the software. // // Any changes to this file according to the GPL as documented in the file // gpl.txt aside this file in the shipment you received can be done to the // lines that follows this copyright notice here, but changes must not be // done inside the copyright notive above. A re-distribution must contain // the intact and unchanged copyright notice. // Contributions and changes to the program code must be marked as such. /* Class documentation: this class provides a file servlet and CGI interface for the httpd server. Whenever this server is addressed to load a local file, this class searches for the file in the local path as configured in the setting property 'rootPath' The servlet loads the file and returns it to the client. Every file can also act as an template for the built-in CGI interface. There is no specific path for CGI functions. CGI functionality is triggered, if for the file to-be-served 'template.html' also a file 'template.class' exists. Then, the class file is called with the GET/POST properties that are attached to the http call. Possible variable hand-over are: - form method GET - form method POST, enctype text/plain - form method POST, enctype multipart/form-data The class that creates the CGI respond must have at least one static method of the form public static java.util.Hashtable respond(java.util.HashMap, serverSwitch) In the HashMap, the GET/POST variables are handed over. The return value is a Property object that contains replacement key/value pairs for the patterns in the template file. The templates must have the form either '#['<name>']#' for single attributes, or '#{'<enumname>'}#' and '#{/'<enumname>'}#' for enumerations of values '#['<value>']#'. A single value in repetitions/enumerations in the template has the property key '_'<enumname><count>'_'<value> Please see also the example files 'test.html' and 'test.java' */ package de.anomic.http; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PushbackInputStream; import java.io.UnsupportedEncodingException; import java.lang.ref.SoftReference; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URLDecoder; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.logging.Level; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import javax.imageio.ImageIO; import de.anomic.plasma.plasmaParser; import de.anomic.plasma.plasmaSwitchboard; import de.anomic.server.serverByteBuffer; import de.anomic.server.serverClassLoader; import de.anomic.server.serverCore; import de.anomic.server.serverFileUtils; import de.anomic.server.serverObjects; import de.anomic.server.serverSwitch; import de.anomic.server.servletProperties; import de.anomic.server.logging.serverLog; import de.anomic.ymage.ymageMatrix; public final class httpdFileHandler extends httpdAbstractHandler implements httpdHandler { private static final boolean safeServletsMode = false; // if true then all servlets are called synchronized // class variables private static final Properties mimeTable = new Properties(); private static final serverClassLoader provider; private static final HashMap templates = new HashMap(); private static serverSwitch switchboard; private static plasmaSwitchboard sb = plasmaSwitchboard.getSwitchboard(); private static File htRootPath = null; private static File htDocsPath = null; private static File htTemplatePath = null; private static String[] defaultFiles = null; private static File htDefaultPath = null; private static File htLocalePath = null; private static final HashMap templateCache; private static final HashMap templateMethodCache; public static boolean useTemplateCache = false; static { useTemplateCache = plasmaSwitchboard.getSwitchboard().getConfig("enableTemplateCache","true").equalsIgnoreCase("true"); templateCache = (useTemplateCache)? new HashMap() : new HashMap(0); templateMethodCache = (useTemplateCache) ? new HashMap() : new HashMap(0); // create a class loader provider = new serverClassLoader(/*this.getClass().getClassLoader()*/); } public httpdFileHandler(serverSwitch switchboard) { // creating a logger this.theLogger = new serverLog("FILEHANDLER"); if (httpdFileHandler.switchboard == null) { httpdFileHandler.switchboard = switchboard; if (mimeTable.size() == 0) { // load the mime table String mimeTablePath = switchboard.getConfig("mimeConfig",""); BufferedInputStream mimeTableInputStream = null; try { serverLog.logConfig("HTTPDFiles", "Loading mime mapping file " + mimeTablePath); mimeTableInputStream = new BufferedInputStream(new FileInputStream(new File(switchboard.getRootPath(), mimeTablePath))); mimeTable.load(mimeTableInputStream); } catch (Exception e) { serverLog.logSevere("HTTPDFiles", "ERROR: path to configuration file or configuration invalid\n" + e); System.exit(1); } finally { if (mimeTableInputStream != null) try { mimeTableInputStream.close(); } catch (Exception e1) {} } } // create default files array initDefaultPath(); // create a htRootPath: system pages if (htRootPath == null) { htRootPath = new File(switchboard.getRootPath(), switchboard.getConfig("htRootPath","htroot")); if (!(htRootPath.exists())) htRootPath.mkdir(); } // create a htDocsPath: user defined pages if (htDocsPath == null) { htDocsPath = new File(switchboard.getRootPath(), switchboard.getConfig("htDocsPath", "htdocs")); if (!(htDocsPath.exists())) htDocsPath.mkdir(); } // create a htTemplatePath if (htTemplatePath == null) { htTemplatePath = new File(switchboard.getRootPath(), switchboard.getConfig("htTemplatePath","htroot/env/templates")); if (!(htTemplatePath.exists())) htTemplatePath.mkdir(); } //This is now handles by #%env/templates/foo%# //if (templates.size() == 0) templates.putAll(httpTemplate.loadTemplates(htTemplatePath)); // create htLocaleDefault, htLocalePath if (htDefaultPath == null) htDefaultPath = new File(switchboard.getRootPath(), switchboard.getConfig("htDefaultPath","htroot")); if (htLocalePath == null) htLocalePath = new File(switchboard.getConfig("locale.translated_html","DATA/LOCALE/htroot")); } } public static final void initDefaultPath() { // create default files array defaultFiles = switchboard.getConfig("defaultFiles","index.html").split(","); if (defaultFiles.length == 0) defaultFiles = new String[] {"index.html"}; } /** Returns a path to the localized or default file according to the locale.language (from he switchboard) * @param path relative from htroot */ public static File getLocalizedFile(String path){ return getLocalizedFile(path, switchboard.getConfig("locale.language","default")); } /** Returns a path to the localized or default file according to the parameter localeSelection * @param path relative from htroot * @param localeSelection language of localized file; locale.language from switchboard is used if localeSelection.equals("") */ public static File getLocalizedFile(String path, String localeSelection){ if (htDefaultPath == null) htDefaultPath = new File(switchboard.getRootPath(), switchboard.getConfig("htDefaultPath","htroot")); if (htLocalePath == null) htLocalePath = new File(switchboard.getRootPath(), switchboard.getConfig("locale.translated_html","DATA/LOCALE/htroot")); if (!(localeSelection.equals("default"))) { File localePath = new File(htLocalePath, localeSelection + "/" + path); if (localePath.exists()) // avoid "NoSuchFile" troubles if the "localeSelection" is misspelled return localePath; } return new File(htDefaultPath, path); } // private void textMessage(OutputStream out, int retcode, String body) throws IOException { // httpd.sendRespondHeader( // this.connectionProperties, // the connection properties // out, // the output stream // "HTTP/1.1", // the http version that should be used // retcode, // the http status code // null, // the http status message // "text/plain", // the mimetype // body.length(), // the content length // httpc.nowDate(), // the modification date // null, // the expires date // null, // cookies // null, // content encoding // null); // transfer encoding // out.write(body.getBytes()); // out.flush(); // } private httpHeader getDefaultHeaders(String path) { httpHeader headers = new httpHeader(); String ext; int pos; if ((pos = path.lastIndexOf('.')) < 0) { ext = ""; } else { ext = path.substring(pos + 1).toLowerCase(); } headers.put(httpHeader.SERVER, "AnomicHTTPD (www.anomic.de)"); headers.put(httpHeader.DATE, httpc.dateString(httpc.nowDate())); if(!(plasmaParser.mediaExtContains(ext))){ headers.put(httpHeader.PRAGMA, "no-cache"); } return headers; } public void doGet(Properties conProp, httpHeader requestHeader, OutputStream response) throws IOException { doResponse(conProp, requestHeader, response, null); } public void doHead(Properties conProp, httpHeader requestHeader, OutputStream response) throws IOException { doResponse(conProp, requestHeader, response, null); } public void doPost(Properties conProp, httpHeader requestHeader, OutputStream response, PushbackInputStream body) throws IOException { doResponse(conProp, requestHeader, response, body); } public void doResponse(Properties conProp, httpHeader requestHeader, OutputStream out, InputStream body) { this.connectionProperties = conProp; String path = null; try { // getting some connection properties String method = conProp.getProperty(httpHeader.CONNECTION_PROP_METHOD); path = conProp.getProperty(httpHeader.CONNECTION_PROP_PATH); String argsString = conProp.getProperty(httpHeader.CONNECTION_PROP_ARGS); // is null if no args were given String httpVersion= conProp.getProperty(httpHeader.CONNECTION_PROP_HTTP_VER); // check hack attacks in path if (path.indexOf("..") >= 0) { httpd.sendRespondError(conProp,out,4,403,null,"Access not allowed",null); return; } // url decoding of path try { path = URLDecoder.decode(path, "UTF-8"); } catch (UnsupportedEncodingException e) { // This should never occur assert(false) : "UnsupportedEncodingException: " + e.getMessage(); } // check permission/granted access String authorization = (String) requestHeader.get(httpHeader.AUTHORIZATION); String adminAccountBase64MD5 = switchboard.getConfig(httpd.ADMIN_ACCOUNT_B64MD5, ""); int pos = path.lastIndexOf("."); if ((path.substring(0,(pos==-1)?path.length():pos)).endsWith("_p") && (adminAccountBase64MD5.length() != 0)) { //authentication required //userDB if(sb.userDB.hasAdminRight(authorization, conProp.getProperty("CLIENTIP"), requestHeader.getHeaderCookies())){ //Authentication successful. remove brute-force flag serverCore.bfHost.remove(conProp.getProperty("CLIENTIP")); //static }else if(authorization != null && httpd.staticAdminAuthenticated(authorization.trim().substring(6), switchboard)==4){ //Authentication successful. remove brute-force flag serverCore.bfHost.remove(conProp.getProperty("CLIENTIP")); //no auth }else if (authorization == null) { // no authorization given in response. Ask for that httpHeader headers = getDefaultHeaders(path); headers.put(httpHeader.WWW_AUTHENTICATE,"Basic realm=\"admin log-in\""); //httpd.sendRespondHeader(conProp,out,httpVersion,401,headers); servletProperties tp=new servletProperties(); tp.put("returnto", path); //TODO: separate errorpage Wrong Login / No Login httpd.sendRespondError(conProp, out, 5, 401, "Wrong Authentication", "", new File("proxymsg/authfail.inc"), tp, null, headers); return; } else { // a wrong authentication was given or the userDB user does not have admin access. Ask again String clientIP = conProp.getProperty("CLIENTIP", "unknown-host"); serverLog.logInfo("HTTPD", "Wrong log-in for account 'admin' in http file handler for path '" + path + "' from host '" + clientIP + "'"); Integer attempts = (Integer) serverCore.bfHost.get(clientIP); if (attempts == null) serverCore.bfHost.put(clientIP, new Integer(1)); else serverCore.bfHost.put(clientIP, new Integer(attempts.intValue() + 1)); httpHeader headers = getDefaultHeaders(path); headers.put(httpHeader.WWW_AUTHENTICATE,"Basic realm=\"admin log-in\""); httpd.sendRespondHeader(conProp,out,httpVersion,401,headers); return; } } // parse arguments serverObjects args = new serverObjects(); int argc; if (argsString == null) { // no args here, maybe a POST with multipart extension int length = 0; //System.out.println("HEADER: " + requestHeader.toString()); // DEBUG if (method.equals(httpHeader.METHOD_POST)) { GZIPInputStream gzipBody = null; if (requestHeader.containsKey(httpHeader.CONTENT_LENGTH)) { length = Integer.parseInt((String) requestHeader.get(httpHeader.CONTENT_LENGTH)); } else if (requestHeader.gzip()) { length = -1; gzipBody = new GZIPInputStream(body); } // } else { // httpd.sendRespondError(conProp,out,4,403,null,"bad post values",null); // return; // } // if its a POST, it can be either multipart or as args in the body if ((requestHeader.containsKey(httpHeader.CONTENT_TYPE)) && (((String) requestHeader.get(httpHeader.CONTENT_TYPE)).toLowerCase().startsWith("multipart"))) { // parse multipart HashMap files = httpd.parseMultipart(requestHeader, args, (gzipBody!=null)?gzipBody:body, length); // integrate these files into the args if (files != null) { Iterator fit = files.entrySet().iterator(); Map.Entry entry; while (fit.hasNext()) { entry = (Map.Entry) fit.next(); args.put(((String) entry.getKey()) + "$file", entry.getValue()); } } argc = Integer.parseInt((String) requestHeader.get("ARGC")); } else { // parse args in body argc = httpd.parseArgs(args, (gzipBody!=null)?gzipBody:body, length); } } else { // no args argsString = null; args = null; argc = 0; } } else { // simple args in URL (stuff after the "?") argc = httpd.parseArgs(args, argsString); } // check for cross site scripting - attacks in request arguments if (argc > 0) { // check all values for occurrences of script values Enumeration e = args.elements(); // enumeration of values Object val; while (e.hasMoreElements()) { val = e.nextElement(); if ((val != null) && (val instanceof String) && (((String) val).indexOf("<script") >= 0)) { // deny request httpd.sendRespondError(conProp,out,4,403,null,"bad post values",null); return; } } } // we are finished with parsing // the result of value hand-over is in args and argc if (path.length() == 0) { httpd.sendRespondError(conProp,out,4,400,null,"Bad Request",null); out.flush(); return; } File targetClass=null; // locate the file if (!(path.startsWith("/"))) path = "/" + path; // attach leading slash // a different language can be desired (by i.e. ConfigBasic.html) than the one stored in the locale.language String localeSelection = switchboard.getConfig("locale.language","default"); if (args != null && (args.containsKey("language"))) { // TODO 9.11.06 Bost: a class with information about available languages is needed. // the indexOf(".") is just a workaround because there from ConfigLanguage.html commes "de.lng" and // from ConfigBasic.html comes just "de" in the "language" parameter localeSelection = args.get("language", localeSelection); if (localeSelection.indexOf(".") != -1) localeSelection = localeSelection.substring(0, localeSelection.indexOf(".")); } File targetFile = getLocalizedFile(path, localeSelection); String targetExt = conProp.getProperty("EXT",""); targetClass = rewriteClassFile(new File(htDefaultPath, path)); if (path.endsWith("/")) { String testpath; // attach default file name for (int i = 0; i < defaultFiles.length; i++) { testpath = path + defaultFiles[i]; targetFile = getOverlayedFile(testpath); targetClass=getOverlayedClass(testpath); if (targetFile.exists()) { path = testpath; break; } } //no defaultfile, send a dirlisting if(targetFile == null || !targetFile.exists()){ String dirlistFormat = (args==null)?"html":args.get("format","html"); targetExt = dirlistFormat; // this is needed to set the mime type correctly targetFile = getOverlayedFile("/htdocsdefault/dir." + dirlistFormat); targetClass=getOverlayedClass("/htdocsdefault/dir." + dirlistFormat); if(! (( targetFile != null && targetFile.exists()) && ( targetClass != null && targetClass.exists())) ){ httpd.sendRespondError(this.connectionProperties,out,3,500,"dir." + dirlistFormat + " or dir.class not found.",null,null); } } }else{ //XXX: you cannot share a .png/.gif file with a name like a class in htroot. if ( !(targetFile.exists()) && !((path.endsWith("png")||path.endsWith("gif")||path.endsWith(".stream"))&&targetClass!=null ) ){ targetFile = new File(htDocsPath, path); targetClass = rewriteClassFile(new File(htDocsPath, path)); } } //File targetClass = rewriteClassFile(targetFile); //We need tp here servletProperties tp = new servletProperties(); Date targetDate; boolean nocache = false; if ((targetClass != null) && (path.endsWith("png"))) { // call an image-servlet to produce an on-the-fly - generated image Object img = null; try { requestHeader.put(httpHeader.CONNECTION_PROP_CLIENTIP, conProp.getProperty("CLIENTIP")); requestHeader.put(httpHeader.CONNECTION_PROP_PATH, path); // in case that there are no args given, args = null or empty hashmap img = invokeServlet(targetClass, requestHeader, args); } catch (InvocationTargetException e) { this.theLogger.logSevere("INTERNAL ERROR: " + e.toString() + ":" + e.getMessage() + " target exception at " + targetClass + ": " + e.getTargetException().toString() + ":" + e.getTargetException().getMessage() + "; java.awt.graphicsenv='" + System.getProperty("java.awt.graphicsenv","") + "'",e); targetClass = null; } if (img == null) { // error with image generation; send file-not-found httpd.sendRespondError(this.connectionProperties,out,3,404,"File not Found",null,null); } else { if (img instanceof ymageMatrix) { ymageMatrix yp = (ymageMatrix) img; // send an image to client targetDate = new Date(System.currentTimeMillis()); nocache = true; String mimeType = mimeTable.getProperty(targetExt, "text/html"); // generate an byte array from the generated image serverByteBuffer baos = new serverByteBuffer(); // ymagePNGEncoderJDE jde = new // ymagePNGEncoderJDE((ymageMatrixPainter) yp, // ymagePNGEncoderJDE.FILTER_NONE, 0); // byte[] result = jde.pngEncode(); ImageIO.write(yp.getImage(), targetExt, baos); byte[] result = baos.toByteArray(); baos.close(); baos = null; // write the array to the client httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, 200, null, mimeType, result.length, targetDate, null, null, null, null, nocache); if (!method.equals(httpHeader.METHOD_HEAD)) { //Thread.sleep(200); // see below serverFileUtils.write(result, out); } } if (img instanceof Image) { Image i = (Image) img; // send an image to client targetDate = new Date(System.currentTimeMillis()); nocache = true; String mimeType = mimeTable.getProperty(targetExt, "text/html"); // generate an byte array from the generated image int width = i.getWidth(null); if (width < 0) width = 96; // bad hack int height = i.getHeight(null); if (height < 0) height = 96; // bad hack BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); bi.createGraphics().drawImage(i, 0, 0, width, height, null); serverByteBuffer baos = new serverByteBuffer(); ImageIO.write(bi, targetExt, baos); byte[] result = baos.toByteArray(); baos.close(); baos = null; // write the array to the client httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, 200, null, mimeType, result.length, targetDate, null, null, null, null, nocache); if (!method.equals(httpHeader.METHOD_HEAD)) { //Thread.sleep(200); // see below serverFileUtils.write(result, out); } } } } else if ((targetClass != null) && (path.endsWith(".stream"))) { // call rewrite-class requestHeader.put(httpHeader.CONNECTION_PROP_CLIENTIP, conProp.getProperty("CLIENTIP")); requestHeader.put(httpHeader.CONNECTION_PROP_PATH, path); requestHeader.put(httpHeader.CONNECTION_PROP_INPUTSTREAM, body); requestHeader.put(httpHeader.CONNECTION_PROP_OUTPUTSTREAM, out); httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, 200, null); // in case that there are no args given, args = null or empty hashmap /* servletProperties tp = (servlerObjects) */ invokeServlet(targetClass, requestHeader, args); this.forceConnectionClose(); return; } else if ((targetFile.exists()) && (targetFile.canRead())) { // we have found a file that can be written to the client // if this file uses templates, then we use the template // re-write - method to create an result String mimeType = mimeTable.getProperty(targetExt,"text/html"); boolean zipContent = requestHeader.acceptGzip() && httpd.shallTransportZipped("." + conProp.getProperty("EXT","")); if (path.endsWith("html") || path.endsWith("xml") || path.endsWith("rss") || path.endsWith("csv") || path.endsWith("pac") || path.endsWith("src") || path.endsWith("vcf") || path.endsWith("/") || path.equals("/robots.txt")) { /*targetFile = getLocalizedFile(path); if (!(targetFile.exists())) { // try to find that file in the htDocsPath File trialFile = new File(htDocsPath, path); if (trialFile.exists()) targetFile = trialFile; }*/ // call rewrite-class if (targetClass == null) { targetDate = new Date(targetFile.lastModified()); } else { // CGI-class: call the class to create a property for rewriting try { requestHeader.put(httpHeader.CONNECTION_PROP_CLIENTIP, conProp.getProperty("CLIENTIP")); requestHeader.put(httpHeader.CONNECTION_PROP_PATH, path); // in case that there are no args given, args = null or empty hashmap Object tmp = invokeServlet(targetClass, requestHeader, args); - if (tp == null) { + if (tmp == null) { // if no args given, then tp will be an empty Hashtable object (not null) tp = new servletProperties(); } else if (tmp instanceof servletProperties) { tp = (servletProperties) tmp; } else { tp = new servletProperties((serverObjects) tmp); } // check if the servlets requests authentification if (tp.containsKey(servletProperties.ACTION_AUTHENTICATE)) { // handle brute-force protection if (authorization != null) { String clientIP = conProp.getProperty("CLIENTIP", "unknown-host"); serverLog.logInfo("HTTPD", "dynamic log-in for account 'admin' in http file handler for path '" + path + "' from host '" + clientIP + "'"); Integer attempts = (Integer) serverCore.bfHost.get(clientIP); if (attempts == null) serverCore.bfHost.put(clientIP, new Integer(1)); else serverCore.bfHost.put(clientIP, new Integer(attempts.intValue() + 1)); } // send authentication request to browser httpHeader headers = getDefaultHeaders(path); headers.put(httpHeader.WWW_AUTHENTICATE,"Basic realm=\"" + tp.get(servletProperties.ACTION_AUTHENTICATE, "") + "\""); httpd.sendRespondHeader(conProp,out,httpVersion,401,headers); return; } else if (tp.containsKey(servletProperties.ACTION_LOCATION)) { String location = tp.get(servletProperties.ACTION_LOCATION, ""); if (location.length() == 0) location = path; httpHeader headers = getDefaultHeaders(path); headers.setCookieVector(tp.getOutgoingHeader().getCookieVector()); //put the cookies into the new header TODO: can we put all headerlines, without trouble? headers.put(httpHeader.LOCATION,location); httpd.sendRespondHeader(conProp,out,httpVersion,302,headers); return; } // add the application version, the uptime and the client name to every rewrite table tp.put(servletProperties.PEER_STAT_VERSION, switchboard.getConfig("version", "")); tp.put(servletProperties.PEER_STAT_UPTIME, ((System.currentTimeMillis() - Long.parseLong(switchboard.getConfig("startupTime","0"))) / 1000) / 60); // uptime in minutes tp.put(servletProperties.PEER_STAT_CLIENTNAME, switchboard.getConfig("peerName", "anomic")); //System.out.println("respond props: " + ((tp == null) ? "null" : tp.toString())); // debug } catch (InvocationTargetException e) { if (e.getCause() instanceof InterruptedException) { throw new InterruptedException(e.getCause().getMessage()); } this.theLogger.logSevere("INTERNAL ERROR: " + e.toString() + ":" + e.getMessage() + " target exception at " + targetClass + ": " + e.getTargetException().toString() + ":" + e.getTargetException().getMessage(),e); targetClass = null; throw e; } targetDate = new Date(System.currentTimeMillis()); nocache = true; } // read templates tp.putAll(templates); // rewrite the file InputStream fis = null; // read the file/template byte[] templateContent = null; if (useTemplateCache) { long fileSize = targetFile.length(); if (fileSize <= 512 * 1024) { // read from cache SoftReference ref = (SoftReference) templateCache.get(targetFile); if (ref != null) { templateContent = (byte[]) ref.get(); if (templateContent == null) templateCache.remove(targetFile); } if (templateContent == null) { // loading the content of the template file into // a byte array templateContent = serverFileUtils.read(targetFile); // storing the content into the cache ref = new SoftReference(templateContent); templateCache.put(targetFile, ref); if (this.theLogger.isLoggable(Level.FINEST)) this.theLogger.logFinest("Cache MISS for file " + targetFile); } else { if (this.theLogger.isLoggable(Level.FINEST)) this.theLogger.logFinest("Cache HIT for file " + targetFile); } // creating an inputstream needed by the template // rewrite function fis = new ByteArrayInputStream(templateContent); templateContent = null; } else { // read from file directly fis = new BufferedInputStream(new FileInputStream(targetFile)); } } else { fis = new BufferedInputStream(new FileInputStream(targetFile)); } // write the array to the client // we can do that either in standard mode (whole thing completely) or in chunked mode // since yacy clients do not understand chunked mode, we use this only for communication with the administrator boolean yacyClient = requestHeader.userAgent().startsWith("yacy"); boolean chunked = !method.equals(httpHeader.METHOD_HEAD) && !yacyClient && httpVersion.equals(httpHeader.HTTP_VERSION_1_1); if (chunked) { // send page in chunks and parse SSIs serverByteBuffer o = new serverByteBuffer(); // apply templates httpTemplate.writeTemplate(fis, o, tp, "-UNRESOLVED_PATTERN-".getBytes("UTF-8")); httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, 200, null, mimeType, -1, targetDate, null, tp.getOutgoingHeader(), null, "chunked", nocache); // send the content in chunked parts, see RFC 2616 section 3.6.1 httpChunkedOutputStream chos = new httpChunkedOutputStream(out); httpSSI.writeSSI(targetFile, o, chos); //chos.write(result); chos.finish(); } else { // send page as whole thing, SSIs are not possible String contentEncoding = (zipContent) ? "gzip" : null; // apply templates serverByteBuffer o = new serverByteBuffer(); if (zipContent) { GZIPOutputStream zippedOut = new GZIPOutputStream(o); httpTemplate.writeTemplate(fis, zippedOut, tp, "-UNRESOLVED_PATTERN-".getBytes("UTF-8")); zippedOut.finish(); zippedOut.flush(); zippedOut.close(); zippedOut = null; } else { httpTemplate.writeTemplate(fis, o, tp, "-UNRESOLVED_PATTERN-".getBytes("UTF-8")); } if (method.equals(httpHeader.METHOD_HEAD)) { httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, 200, null, mimeType, o.length(), targetDate, null, tp.getOutgoingHeader(), contentEncoding, null, nocache); } else { byte[] result = o.toByteArray(); // this interrupts streaming (bad idea!) httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, 200, null, mimeType, result.length, targetDate, null, tp.getOutgoingHeader(), contentEncoding, null, nocache); serverFileUtils.write(result, out); } } } else { // no html int statusCode = 200; int rangeStartOffset = 0; httpHeader header = new httpHeader(); // adding the accept ranges header header.put(httpHeader.ACCEPT_RANGES, "bytes"); // reading the files md5 hash if availabe and use it as ETAG of the resource String targetMD5 = null; File targetMd5File = new File(targetFile + ".md5"); try { if (targetMd5File.exists()) { //String description = null; targetMD5 = new String(serverFileUtils.read(targetMd5File)); pos = targetMD5.indexOf('\n'); if (pos >= 0) { //description = targetMD5.substring(pos + 1); targetMD5 = targetMD5.substring(0, pos); } // using the checksum as ETAG header header.put(httpHeader.ETAG, targetMD5); } } catch (IOException e) { e.printStackTrace(); } if (requestHeader.containsKey(httpHeader.RANGE)) { Object ifRange = requestHeader.ifRange(); if ((ifRange == null)|| (ifRange instanceof Date && targetFile.lastModified() == ((Date)ifRange).getTime()) || (ifRange instanceof String && ifRange.equals(targetMD5))) { String rangeHeaderVal = ((String) requestHeader.get(httpHeader.RANGE)).trim(); if (rangeHeaderVal.startsWith("bytes=")) { String rangesVal = rangeHeaderVal.substring("bytes=".length()); String[] ranges = rangesVal.split(","); if ((ranges.length == 1)&&(ranges[0].endsWith("-"))) { rangeStartOffset = Integer.valueOf(ranges[0].substring(0,ranges[0].length()-1)).intValue(); statusCode = 206; if (header == null) header = new httpHeader(); header.put(httpHeader.CONTENT_RANGE, "bytes " + rangeStartOffset + "-" + (targetFile.length()-1) + "/" + targetFile.length()); } } } } // write the file to the client targetDate = new Date(targetFile.lastModified()); long contentLength = (zipContent)?-1:targetFile.length()-rangeStartOffset; String contentEncoding = (zipContent)?"gzip":null; String transferEncoding = (!httpVersion.equals(httpHeader.HTTP_VERSION_1_1))?null:(zipContent)?"chunked":null; if (!httpVersion.equals(httpHeader.HTTP_VERSION_1_1) && zipContent) forceConnectionClose(); httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, statusCode, null, mimeType, contentLength, targetDate, null, header, contentEncoding, transferEncoding, nocache); if (!method.equals(httpHeader.METHOD_HEAD)) { httpChunkedOutputStream chunkedOut = null; GZIPOutputStream zipped = null; OutputStream newOut = out; if (transferEncoding != null) { chunkedOut = new httpChunkedOutputStream(newOut); newOut = chunkedOut; } if (contentEncoding != null) { zipped = new GZIPOutputStream(newOut); newOut = zipped; } serverFileUtils.copyRange(targetFile,newOut,rangeStartOffset); if (zipped != null) { zipped.flush(); zipped.finish(); } if (chunkedOut != null) { chunkedOut.finish(); } } // check mime type again using the result array: these are 'magics' // if (serverByteBuffer.equals(result, 1, "PNG".getBytes())) mimeType = mimeTable.getProperty("png","text/html"); // else if (serverByteBuffer.equals(result, 0, "GIF89".getBytes())) mimeType = mimeTable.getProperty("gif","text/html"); // else if (serverByteBuffer.equals(result, 6, "JFIF".getBytes())) mimeType = mimeTable.getProperty("jpg","text/html"); //System.out.print("MAGIC:"); for (int i = 0; i < 10; i++) System.out.print(Integer.toHexString((int) result[i]) + ","); System.out.println(); } } else { httpd.sendRespondError(conProp,out,3,404,"File not Found",null,null); return; } } catch (Exception e) { try { // doing some errorhandling ... int httpStatusCode = 400; String httpStatusText = null; StringBuffer errorMessage = new StringBuffer(); Exception errorExc = null; String errorMsg = e.getMessage(); if ( (e instanceof InterruptedException) || ((errorMsg != null) && (errorMsg.startsWith("Socket closed")) && (Thread.currentThread().isInterrupted())) ) { errorMessage.append("Interruption detected while processing query."); httpStatusCode = 503; } else { if ((errorMsg != null) && ( errorMsg.startsWith("Broken pipe") || errorMsg.startsWith("Connection reset") || errorMsg.startsWith("Software caused connection abort") )) { // client closed the connection, so we just end silently errorMessage.append("Client unexpectedly closed connection while processing query."); } else if ((errorMsg != null) && (errorMsg.startsWith("Connection timed out"))) { errorMessage.append("Connection timed out."); } else { errorMessage.append("Unexpected error while processing query."); httpStatusCode = 500; errorExc = e; } } errorMessage.append("\nSession: ").append(Thread.currentThread().getName()) .append("\nQuery: ").append(path) .append("\nClient: ").append(conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP,"unknown")) .append("\nReason: ").append(e.toString()); if (!conProp.containsKey(httpHeader.CONNECTION_PROP_PROXY_RESPOND_HEADER)) { // sending back an error message to the client // if we have not already send an http header httpd.sendRespondError(conProp,out, 4, httpStatusCode, httpStatusText, new String(errorMessage),errorExc); } else { // otherwise we close the connection this.forceConnectionClose(); } // if it is an unexpected error we log it if (httpStatusCode == 500) { this.theLogger.logWarning(new String(errorMessage),e); } } catch (Exception ee) { this.forceConnectionClose(); } } finally { try {out.flush();}catch (Exception e) {} if (((String)requestHeader.get(httpHeader.CONNECTION, "close")).indexOf("keep-alive") == -1) { // wait a little time until everything closes so that clients can read from the streams/sockets try {Thread.sleep(200);} catch (InterruptedException e) {} } } } public File getOverlayedClass(String path) { File targetClass; targetClass=rewriteClassFile(new File(htDefaultPath, path)); //works for default and localized files if(targetClass == null || !targetClass.exists()){ //works for htdocs targetClass=rewriteClassFile(new File(htDocsPath, path)); } return targetClass; } public File getOverlayedFile(String path) { File targetFile; targetFile = getLocalizedFile(path); if (!(targetFile.exists())){ targetFile = new File(htDocsPath, path); } return targetFile; } private void forceConnectionClose() { if (this.connectionProperties != null) { this.connectionProperties.setProperty(httpHeader.CONNECTION_PROP_PERSISTENT,"close"); } } private File rewriteClassFile(File template) { try { String f = template.getCanonicalPath(); int p = f.lastIndexOf("."); if (p < 0) return null; f = f.substring(0, p) + ".class"; //System.out.println("constructed class path " + f); File cf = new File(f); if (cf.exists()) return cf; return null; } catch (IOException e) { return null; } } private final Method rewriteMethod(File classFile) { Method m = null; // now make a class out of the stream try { if (useTemplateCache) { SoftReference ref = (SoftReference) templateMethodCache.get(classFile); if (ref != null) { m = (Method) ref.get(); if (m == null) { templateMethodCache.remove(classFile); } else { this.theLogger.logFine("Cache HIT for file " + classFile); return m; } } } //System.out.println("**DEBUG** loading class file " + classFile); Class c = provider.loadClass(classFile); Class[] params = new Class[] { httpHeader.class, serverObjects.class, serverSwitch.class }; m = c.getMethod("respond", params); if (useTemplateCache) { // storing the method into the cache SoftReference ref = new SoftReference(m); templateMethodCache.put(classFile,ref); this.theLogger.logFine("Cache MISS for file " + classFile); } } catch (ClassNotFoundException e) { System.out.println("INTERNAL ERROR: class " + classFile + " is missing:" + e.getMessage()); } catch (NoSuchMethodException e) { System.out.println("INTERNAL ERROR: method respond not found in class " + classFile + ": " + e.getMessage()); } //System.out.println("found method: " + m.toString()); return m; } public Object invokeServlet(File targetClass, httpHeader request, serverObjects args) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { Object result; if (safeServletsMode) synchronized (switchboard) { result = rewriteMethod(targetClass).invoke(null, new Object[] {request, args, switchboard}); } else { result = rewriteMethod(targetClass).invoke(null, new Object[] {request, args, switchboard}); } return result; } public void doConnect(Properties conProp, httpHeader requestHeader, InputStream clientIn, OutputStream clientOut) { throw new UnsupportedOperationException(); } }
true
true
public void doResponse(Properties conProp, httpHeader requestHeader, OutputStream out, InputStream body) { this.connectionProperties = conProp; String path = null; try { // getting some connection properties String method = conProp.getProperty(httpHeader.CONNECTION_PROP_METHOD); path = conProp.getProperty(httpHeader.CONNECTION_PROP_PATH); String argsString = conProp.getProperty(httpHeader.CONNECTION_PROP_ARGS); // is null if no args were given String httpVersion= conProp.getProperty(httpHeader.CONNECTION_PROP_HTTP_VER); // check hack attacks in path if (path.indexOf("..") >= 0) { httpd.sendRespondError(conProp,out,4,403,null,"Access not allowed",null); return; } // url decoding of path try { path = URLDecoder.decode(path, "UTF-8"); } catch (UnsupportedEncodingException e) { // This should never occur assert(false) : "UnsupportedEncodingException: " + e.getMessage(); } // check permission/granted access String authorization = (String) requestHeader.get(httpHeader.AUTHORIZATION); String adminAccountBase64MD5 = switchboard.getConfig(httpd.ADMIN_ACCOUNT_B64MD5, ""); int pos = path.lastIndexOf("."); if ((path.substring(0,(pos==-1)?path.length():pos)).endsWith("_p") && (adminAccountBase64MD5.length() != 0)) { //authentication required //userDB if(sb.userDB.hasAdminRight(authorization, conProp.getProperty("CLIENTIP"), requestHeader.getHeaderCookies())){ //Authentication successful. remove brute-force flag serverCore.bfHost.remove(conProp.getProperty("CLIENTIP")); //static }else if(authorization != null && httpd.staticAdminAuthenticated(authorization.trim().substring(6), switchboard)==4){ //Authentication successful. remove brute-force flag serverCore.bfHost.remove(conProp.getProperty("CLIENTIP")); //no auth }else if (authorization == null) { // no authorization given in response. Ask for that httpHeader headers = getDefaultHeaders(path); headers.put(httpHeader.WWW_AUTHENTICATE,"Basic realm=\"admin log-in\""); //httpd.sendRespondHeader(conProp,out,httpVersion,401,headers); servletProperties tp=new servletProperties(); tp.put("returnto", path); //TODO: separate errorpage Wrong Login / No Login httpd.sendRespondError(conProp, out, 5, 401, "Wrong Authentication", "", new File("proxymsg/authfail.inc"), tp, null, headers); return; } else { // a wrong authentication was given or the userDB user does not have admin access. Ask again String clientIP = conProp.getProperty("CLIENTIP", "unknown-host"); serverLog.logInfo("HTTPD", "Wrong log-in for account 'admin' in http file handler for path '" + path + "' from host '" + clientIP + "'"); Integer attempts = (Integer) serverCore.bfHost.get(clientIP); if (attempts == null) serverCore.bfHost.put(clientIP, new Integer(1)); else serverCore.bfHost.put(clientIP, new Integer(attempts.intValue() + 1)); httpHeader headers = getDefaultHeaders(path); headers.put(httpHeader.WWW_AUTHENTICATE,"Basic realm=\"admin log-in\""); httpd.sendRespondHeader(conProp,out,httpVersion,401,headers); return; } } // parse arguments serverObjects args = new serverObjects(); int argc; if (argsString == null) { // no args here, maybe a POST with multipart extension int length = 0; //System.out.println("HEADER: " + requestHeader.toString()); // DEBUG if (method.equals(httpHeader.METHOD_POST)) { GZIPInputStream gzipBody = null; if (requestHeader.containsKey(httpHeader.CONTENT_LENGTH)) { length = Integer.parseInt((String) requestHeader.get(httpHeader.CONTENT_LENGTH)); } else if (requestHeader.gzip()) { length = -1; gzipBody = new GZIPInputStream(body); } // } else { // httpd.sendRespondError(conProp,out,4,403,null,"bad post values",null); // return; // } // if its a POST, it can be either multipart or as args in the body if ((requestHeader.containsKey(httpHeader.CONTENT_TYPE)) && (((String) requestHeader.get(httpHeader.CONTENT_TYPE)).toLowerCase().startsWith("multipart"))) { // parse multipart HashMap files = httpd.parseMultipart(requestHeader, args, (gzipBody!=null)?gzipBody:body, length); // integrate these files into the args if (files != null) { Iterator fit = files.entrySet().iterator(); Map.Entry entry; while (fit.hasNext()) { entry = (Map.Entry) fit.next(); args.put(((String) entry.getKey()) + "$file", entry.getValue()); } } argc = Integer.parseInt((String) requestHeader.get("ARGC")); } else { // parse args in body argc = httpd.parseArgs(args, (gzipBody!=null)?gzipBody:body, length); } } else { // no args argsString = null; args = null; argc = 0; } } else { // simple args in URL (stuff after the "?") argc = httpd.parseArgs(args, argsString); } // check for cross site scripting - attacks in request arguments if (argc > 0) { // check all values for occurrences of script values Enumeration e = args.elements(); // enumeration of values Object val; while (e.hasMoreElements()) { val = e.nextElement(); if ((val != null) && (val instanceof String) && (((String) val).indexOf("<script") >= 0)) { // deny request httpd.sendRespondError(conProp,out,4,403,null,"bad post values",null); return; } } } // we are finished with parsing // the result of value hand-over is in args and argc if (path.length() == 0) { httpd.sendRespondError(conProp,out,4,400,null,"Bad Request",null); out.flush(); return; } File targetClass=null; // locate the file if (!(path.startsWith("/"))) path = "/" + path; // attach leading slash // a different language can be desired (by i.e. ConfigBasic.html) than the one stored in the locale.language String localeSelection = switchboard.getConfig("locale.language","default"); if (args != null && (args.containsKey("language"))) { // TODO 9.11.06 Bost: a class with information about available languages is needed. // the indexOf(".") is just a workaround because there from ConfigLanguage.html commes "de.lng" and // from ConfigBasic.html comes just "de" in the "language" parameter localeSelection = args.get("language", localeSelection); if (localeSelection.indexOf(".") != -1) localeSelection = localeSelection.substring(0, localeSelection.indexOf(".")); } File targetFile = getLocalizedFile(path, localeSelection); String targetExt = conProp.getProperty("EXT",""); targetClass = rewriteClassFile(new File(htDefaultPath, path)); if (path.endsWith("/")) { String testpath; // attach default file name for (int i = 0; i < defaultFiles.length; i++) { testpath = path + defaultFiles[i]; targetFile = getOverlayedFile(testpath); targetClass=getOverlayedClass(testpath); if (targetFile.exists()) { path = testpath; break; } } //no defaultfile, send a dirlisting if(targetFile == null || !targetFile.exists()){ String dirlistFormat = (args==null)?"html":args.get("format","html"); targetExt = dirlistFormat; // this is needed to set the mime type correctly targetFile = getOverlayedFile("/htdocsdefault/dir." + dirlistFormat); targetClass=getOverlayedClass("/htdocsdefault/dir." + dirlistFormat); if(! (( targetFile != null && targetFile.exists()) && ( targetClass != null && targetClass.exists())) ){ httpd.sendRespondError(this.connectionProperties,out,3,500,"dir." + dirlistFormat + " or dir.class not found.",null,null); } } }else{ //XXX: you cannot share a .png/.gif file with a name like a class in htroot. if ( !(targetFile.exists()) && !((path.endsWith("png")||path.endsWith("gif")||path.endsWith(".stream"))&&targetClass!=null ) ){ targetFile = new File(htDocsPath, path); targetClass = rewriteClassFile(new File(htDocsPath, path)); } } //File targetClass = rewriteClassFile(targetFile); //We need tp here servletProperties tp = new servletProperties(); Date targetDate; boolean nocache = false; if ((targetClass != null) && (path.endsWith("png"))) { // call an image-servlet to produce an on-the-fly - generated image Object img = null; try { requestHeader.put(httpHeader.CONNECTION_PROP_CLIENTIP, conProp.getProperty("CLIENTIP")); requestHeader.put(httpHeader.CONNECTION_PROP_PATH, path); // in case that there are no args given, args = null or empty hashmap img = invokeServlet(targetClass, requestHeader, args); } catch (InvocationTargetException e) { this.theLogger.logSevere("INTERNAL ERROR: " + e.toString() + ":" + e.getMessage() + " target exception at " + targetClass + ": " + e.getTargetException().toString() + ":" + e.getTargetException().getMessage() + "; java.awt.graphicsenv='" + System.getProperty("java.awt.graphicsenv","") + "'",e); targetClass = null; } if (img == null) { // error with image generation; send file-not-found httpd.sendRespondError(this.connectionProperties,out,3,404,"File not Found",null,null); } else { if (img instanceof ymageMatrix) { ymageMatrix yp = (ymageMatrix) img; // send an image to client targetDate = new Date(System.currentTimeMillis()); nocache = true; String mimeType = mimeTable.getProperty(targetExt, "text/html"); // generate an byte array from the generated image serverByteBuffer baos = new serverByteBuffer(); // ymagePNGEncoderJDE jde = new // ymagePNGEncoderJDE((ymageMatrixPainter) yp, // ymagePNGEncoderJDE.FILTER_NONE, 0); // byte[] result = jde.pngEncode(); ImageIO.write(yp.getImage(), targetExt, baos); byte[] result = baos.toByteArray(); baos.close(); baos = null; // write the array to the client httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, 200, null, mimeType, result.length, targetDate, null, null, null, null, nocache); if (!method.equals(httpHeader.METHOD_HEAD)) { //Thread.sleep(200); // see below serverFileUtils.write(result, out); } } if (img instanceof Image) { Image i = (Image) img; // send an image to client targetDate = new Date(System.currentTimeMillis()); nocache = true; String mimeType = mimeTable.getProperty(targetExt, "text/html"); // generate an byte array from the generated image int width = i.getWidth(null); if (width < 0) width = 96; // bad hack int height = i.getHeight(null); if (height < 0) height = 96; // bad hack BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); bi.createGraphics().drawImage(i, 0, 0, width, height, null); serverByteBuffer baos = new serverByteBuffer(); ImageIO.write(bi, targetExt, baos); byte[] result = baos.toByteArray(); baos.close(); baos = null; // write the array to the client httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, 200, null, mimeType, result.length, targetDate, null, null, null, null, nocache); if (!method.equals(httpHeader.METHOD_HEAD)) { //Thread.sleep(200); // see below serverFileUtils.write(result, out); } } } } else if ((targetClass != null) && (path.endsWith(".stream"))) { // call rewrite-class requestHeader.put(httpHeader.CONNECTION_PROP_CLIENTIP, conProp.getProperty("CLIENTIP")); requestHeader.put(httpHeader.CONNECTION_PROP_PATH, path); requestHeader.put(httpHeader.CONNECTION_PROP_INPUTSTREAM, body); requestHeader.put(httpHeader.CONNECTION_PROP_OUTPUTSTREAM, out); httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, 200, null); // in case that there are no args given, args = null or empty hashmap /* servletProperties tp = (servlerObjects) */ invokeServlet(targetClass, requestHeader, args); this.forceConnectionClose(); return; } else if ((targetFile.exists()) && (targetFile.canRead())) { // we have found a file that can be written to the client // if this file uses templates, then we use the template // re-write - method to create an result String mimeType = mimeTable.getProperty(targetExt,"text/html"); boolean zipContent = requestHeader.acceptGzip() && httpd.shallTransportZipped("." + conProp.getProperty("EXT","")); if (path.endsWith("html") || path.endsWith("xml") || path.endsWith("rss") || path.endsWith("csv") || path.endsWith("pac") || path.endsWith("src") || path.endsWith("vcf") || path.endsWith("/") || path.equals("/robots.txt")) { /*targetFile = getLocalizedFile(path); if (!(targetFile.exists())) { // try to find that file in the htDocsPath File trialFile = new File(htDocsPath, path); if (trialFile.exists()) targetFile = trialFile; }*/ // call rewrite-class if (targetClass == null) { targetDate = new Date(targetFile.lastModified()); } else { // CGI-class: call the class to create a property for rewriting try { requestHeader.put(httpHeader.CONNECTION_PROP_CLIENTIP, conProp.getProperty("CLIENTIP")); requestHeader.put(httpHeader.CONNECTION_PROP_PATH, path); // in case that there are no args given, args = null or empty hashmap Object tmp = invokeServlet(targetClass, requestHeader, args); if (tp == null) { // if no args given, then tp will be an empty Hashtable object (not null) tp = new servletProperties(); } else if (tmp instanceof servletProperties) { tp = (servletProperties) tmp; } else { tp = new servletProperties((serverObjects) tmp); } // check if the servlets requests authentification if (tp.containsKey(servletProperties.ACTION_AUTHENTICATE)) { // handle brute-force protection if (authorization != null) { String clientIP = conProp.getProperty("CLIENTIP", "unknown-host"); serverLog.logInfo("HTTPD", "dynamic log-in for account 'admin' in http file handler for path '" + path + "' from host '" + clientIP + "'"); Integer attempts = (Integer) serverCore.bfHost.get(clientIP); if (attempts == null) serverCore.bfHost.put(clientIP, new Integer(1)); else serverCore.bfHost.put(clientIP, new Integer(attempts.intValue() + 1)); } // send authentication request to browser httpHeader headers = getDefaultHeaders(path); headers.put(httpHeader.WWW_AUTHENTICATE,"Basic realm=\"" + tp.get(servletProperties.ACTION_AUTHENTICATE, "") + "\""); httpd.sendRespondHeader(conProp,out,httpVersion,401,headers); return; } else if (tp.containsKey(servletProperties.ACTION_LOCATION)) { String location = tp.get(servletProperties.ACTION_LOCATION, ""); if (location.length() == 0) location = path; httpHeader headers = getDefaultHeaders(path); headers.setCookieVector(tp.getOutgoingHeader().getCookieVector()); //put the cookies into the new header TODO: can we put all headerlines, without trouble? headers.put(httpHeader.LOCATION,location); httpd.sendRespondHeader(conProp,out,httpVersion,302,headers); return; } // add the application version, the uptime and the client name to every rewrite table tp.put(servletProperties.PEER_STAT_VERSION, switchboard.getConfig("version", "")); tp.put(servletProperties.PEER_STAT_UPTIME, ((System.currentTimeMillis() - Long.parseLong(switchboard.getConfig("startupTime","0"))) / 1000) / 60); // uptime in minutes tp.put(servletProperties.PEER_STAT_CLIENTNAME, switchboard.getConfig("peerName", "anomic")); //System.out.println("respond props: " + ((tp == null) ? "null" : tp.toString())); // debug } catch (InvocationTargetException e) { if (e.getCause() instanceof InterruptedException) { throw new InterruptedException(e.getCause().getMessage()); } this.theLogger.logSevere("INTERNAL ERROR: " + e.toString() + ":" + e.getMessage() + " target exception at " + targetClass + ": " + e.getTargetException().toString() + ":" + e.getTargetException().getMessage(),e); targetClass = null; throw e; } targetDate = new Date(System.currentTimeMillis()); nocache = true; } // read templates tp.putAll(templates); // rewrite the file InputStream fis = null; // read the file/template byte[] templateContent = null; if (useTemplateCache) { long fileSize = targetFile.length(); if (fileSize <= 512 * 1024) { // read from cache SoftReference ref = (SoftReference) templateCache.get(targetFile); if (ref != null) { templateContent = (byte[]) ref.get(); if (templateContent == null) templateCache.remove(targetFile); } if (templateContent == null) { // loading the content of the template file into // a byte array templateContent = serverFileUtils.read(targetFile); // storing the content into the cache ref = new SoftReference(templateContent); templateCache.put(targetFile, ref); if (this.theLogger.isLoggable(Level.FINEST)) this.theLogger.logFinest("Cache MISS for file " + targetFile); } else { if (this.theLogger.isLoggable(Level.FINEST)) this.theLogger.logFinest("Cache HIT for file " + targetFile); } // creating an inputstream needed by the template // rewrite function fis = new ByteArrayInputStream(templateContent); templateContent = null; } else { // read from file directly fis = new BufferedInputStream(new FileInputStream(targetFile)); } } else { fis = new BufferedInputStream(new FileInputStream(targetFile)); } // write the array to the client // we can do that either in standard mode (whole thing completely) or in chunked mode // since yacy clients do not understand chunked mode, we use this only for communication with the administrator boolean yacyClient = requestHeader.userAgent().startsWith("yacy"); boolean chunked = !method.equals(httpHeader.METHOD_HEAD) && !yacyClient && httpVersion.equals(httpHeader.HTTP_VERSION_1_1); if (chunked) { // send page in chunks and parse SSIs serverByteBuffer o = new serverByteBuffer(); // apply templates httpTemplate.writeTemplate(fis, o, tp, "-UNRESOLVED_PATTERN-".getBytes("UTF-8")); httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, 200, null, mimeType, -1, targetDate, null, tp.getOutgoingHeader(), null, "chunked", nocache); // send the content in chunked parts, see RFC 2616 section 3.6.1 httpChunkedOutputStream chos = new httpChunkedOutputStream(out); httpSSI.writeSSI(targetFile, o, chos); //chos.write(result); chos.finish(); } else { // send page as whole thing, SSIs are not possible String contentEncoding = (zipContent) ? "gzip" : null; // apply templates serverByteBuffer o = new serverByteBuffer(); if (zipContent) { GZIPOutputStream zippedOut = new GZIPOutputStream(o); httpTemplate.writeTemplate(fis, zippedOut, tp, "-UNRESOLVED_PATTERN-".getBytes("UTF-8")); zippedOut.finish(); zippedOut.flush(); zippedOut.close(); zippedOut = null; } else { httpTemplate.writeTemplate(fis, o, tp, "-UNRESOLVED_PATTERN-".getBytes("UTF-8")); } if (method.equals(httpHeader.METHOD_HEAD)) { httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, 200, null, mimeType, o.length(), targetDate, null, tp.getOutgoingHeader(), contentEncoding, null, nocache); } else { byte[] result = o.toByteArray(); // this interrupts streaming (bad idea!) httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, 200, null, mimeType, result.length, targetDate, null, tp.getOutgoingHeader(), contentEncoding, null, nocache); serverFileUtils.write(result, out); } } } else { // no html int statusCode = 200; int rangeStartOffset = 0; httpHeader header = new httpHeader(); // adding the accept ranges header header.put(httpHeader.ACCEPT_RANGES, "bytes"); // reading the files md5 hash if availabe and use it as ETAG of the resource String targetMD5 = null; File targetMd5File = new File(targetFile + ".md5"); try { if (targetMd5File.exists()) { //String description = null; targetMD5 = new String(serverFileUtils.read(targetMd5File)); pos = targetMD5.indexOf('\n'); if (pos >= 0) { //description = targetMD5.substring(pos + 1); targetMD5 = targetMD5.substring(0, pos); } // using the checksum as ETAG header header.put(httpHeader.ETAG, targetMD5); } } catch (IOException e) { e.printStackTrace(); } if (requestHeader.containsKey(httpHeader.RANGE)) { Object ifRange = requestHeader.ifRange(); if ((ifRange == null)|| (ifRange instanceof Date && targetFile.lastModified() == ((Date)ifRange).getTime()) || (ifRange instanceof String && ifRange.equals(targetMD5))) { String rangeHeaderVal = ((String) requestHeader.get(httpHeader.RANGE)).trim(); if (rangeHeaderVal.startsWith("bytes=")) { String rangesVal = rangeHeaderVal.substring("bytes=".length()); String[] ranges = rangesVal.split(","); if ((ranges.length == 1)&&(ranges[0].endsWith("-"))) { rangeStartOffset = Integer.valueOf(ranges[0].substring(0,ranges[0].length()-1)).intValue(); statusCode = 206; if (header == null) header = new httpHeader(); header.put(httpHeader.CONTENT_RANGE, "bytes " + rangeStartOffset + "-" + (targetFile.length()-1) + "/" + targetFile.length()); } } } } // write the file to the client targetDate = new Date(targetFile.lastModified()); long contentLength = (zipContent)?-1:targetFile.length()-rangeStartOffset; String contentEncoding = (zipContent)?"gzip":null; String transferEncoding = (!httpVersion.equals(httpHeader.HTTP_VERSION_1_1))?null:(zipContent)?"chunked":null; if (!httpVersion.equals(httpHeader.HTTP_VERSION_1_1) && zipContent) forceConnectionClose(); httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, statusCode, null, mimeType, contentLength, targetDate, null, header, contentEncoding, transferEncoding, nocache); if (!method.equals(httpHeader.METHOD_HEAD)) { httpChunkedOutputStream chunkedOut = null; GZIPOutputStream zipped = null; OutputStream newOut = out; if (transferEncoding != null) { chunkedOut = new httpChunkedOutputStream(newOut); newOut = chunkedOut; } if (contentEncoding != null) { zipped = new GZIPOutputStream(newOut); newOut = zipped; } serverFileUtils.copyRange(targetFile,newOut,rangeStartOffset); if (zipped != null) { zipped.flush(); zipped.finish(); } if (chunkedOut != null) { chunkedOut.finish(); } } // check mime type again using the result array: these are 'magics' // if (serverByteBuffer.equals(result, 1, "PNG".getBytes())) mimeType = mimeTable.getProperty("png","text/html"); // else if (serverByteBuffer.equals(result, 0, "GIF89".getBytes())) mimeType = mimeTable.getProperty("gif","text/html"); // else if (serverByteBuffer.equals(result, 6, "JFIF".getBytes())) mimeType = mimeTable.getProperty("jpg","text/html"); //System.out.print("MAGIC:"); for (int i = 0; i < 10; i++) System.out.print(Integer.toHexString((int) result[i]) + ","); System.out.println(); } } else { httpd.sendRespondError(conProp,out,3,404,"File not Found",null,null); return; } } catch (Exception e) { try { // doing some errorhandling ... int httpStatusCode = 400; String httpStatusText = null; StringBuffer errorMessage = new StringBuffer(); Exception errorExc = null; String errorMsg = e.getMessage(); if ( (e instanceof InterruptedException) || ((errorMsg != null) && (errorMsg.startsWith("Socket closed")) && (Thread.currentThread().isInterrupted())) ) { errorMessage.append("Interruption detected while processing query."); httpStatusCode = 503; } else { if ((errorMsg != null) && ( errorMsg.startsWith("Broken pipe") || errorMsg.startsWith("Connection reset") || errorMsg.startsWith("Software caused connection abort") )) { // client closed the connection, so we just end silently errorMessage.append("Client unexpectedly closed connection while processing query."); } else if ((errorMsg != null) && (errorMsg.startsWith("Connection timed out"))) { errorMessage.append("Connection timed out."); } else { errorMessage.append("Unexpected error while processing query."); httpStatusCode = 500; errorExc = e; } } errorMessage.append("\nSession: ").append(Thread.currentThread().getName()) .append("\nQuery: ").append(path) .append("\nClient: ").append(conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP,"unknown")) .append("\nReason: ").append(e.toString()); if (!conProp.containsKey(httpHeader.CONNECTION_PROP_PROXY_RESPOND_HEADER)) { // sending back an error message to the client // if we have not already send an http header httpd.sendRespondError(conProp,out, 4, httpStatusCode, httpStatusText, new String(errorMessage),errorExc); } else { // otherwise we close the connection this.forceConnectionClose(); } // if it is an unexpected error we log it if (httpStatusCode == 500) { this.theLogger.logWarning(new String(errorMessage),e); } } catch (Exception ee) { this.forceConnectionClose(); } } finally { try {out.flush();}catch (Exception e) {} if (((String)requestHeader.get(httpHeader.CONNECTION, "close")).indexOf("keep-alive") == -1) { // wait a little time until everything closes so that clients can read from the streams/sockets try {Thread.sleep(200);} catch (InterruptedException e) {} } } }
public void doResponse(Properties conProp, httpHeader requestHeader, OutputStream out, InputStream body) { this.connectionProperties = conProp; String path = null; try { // getting some connection properties String method = conProp.getProperty(httpHeader.CONNECTION_PROP_METHOD); path = conProp.getProperty(httpHeader.CONNECTION_PROP_PATH); String argsString = conProp.getProperty(httpHeader.CONNECTION_PROP_ARGS); // is null if no args were given String httpVersion= conProp.getProperty(httpHeader.CONNECTION_PROP_HTTP_VER); // check hack attacks in path if (path.indexOf("..") >= 0) { httpd.sendRespondError(conProp,out,4,403,null,"Access not allowed",null); return; } // url decoding of path try { path = URLDecoder.decode(path, "UTF-8"); } catch (UnsupportedEncodingException e) { // This should never occur assert(false) : "UnsupportedEncodingException: " + e.getMessage(); } // check permission/granted access String authorization = (String) requestHeader.get(httpHeader.AUTHORIZATION); String adminAccountBase64MD5 = switchboard.getConfig(httpd.ADMIN_ACCOUNT_B64MD5, ""); int pos = path.lastIndexOf("."); if ((path.substring(0,(pos==-1)?path.length():pos)).endsWith("_p") && (adminAccountBase64MD5.length() != 0)) { //authentication required //userDB if(sb.userDB.hasAdminRight(authorization, conProp.getProperty("CLIENTIP"), requestHeader.getHeaderCookies())){ //Authentication successful. remove brute-force flag serverCore.bfHost.remove(conProp.getProperty("CLIENTIP")); //static }else if(authorization != null && httpd.staticAdminAuthenticated(authorization.trim().substring(6), switchboard)==4){ //Authentication successful. remove brute-force flag serverCore.bfHost.remove(conProp.getProperty("CLIENTIP")); //no auth }else if (authorization == null) { // no authorization given in response. Ask for that httpHeader headers = getDefaultHeaders(path); headers.put(httpHeader.WWW_AUTHENTICATE,"Basic realm=\"admin log-in\""); //httpd.sendRespondHeader(conProp,out,httpVersion,401,headers); servletProperties tp=new servletProperties(); tp.put("returnto", path); //TODO: separate errorpage Wrong Login / No Login httpd.sendRespondError(conProp, out, 5, 401, "Wrong Authentication", "", new File("proxymsg/authfail.inc"), tp, null, headers); return; } else { // a wrong authentication was given or the userDB user does not have admin access. Ask again String clientIP = conProp.getProperty("CLIENTIP", "unknown-host"); serverLog.logInfo("HTTPD", "Wrong log-in for account 'admin' in http file handler for path '" + path + "' from host '" + clientIP + "'"); Integer attempts = (Integer) serverCore.bfHost.get(clientIP); if (attempts == null) serverCore.bfHost.put(clientIP, new Integer(1)); else serverCore.bfHost.put(clientIP, new Integer(attempts.intValue() + 1)); httpHeader headers = getDefaultHeaders(path); headers.put(httpHeader.WWW_AUTHENTICATE,"Basic realm=\"admin log-in\""); httpd.sendRespondHeader(conProp,out,httpVersion,401,headers); return; } } // parse arguments serverObjects args = new serverObjects(); int argc; if (argsString == null) { // no args here, maybe a POST with multipart extension int length = 0; //System.out.println("HEADER: " + requestHeader.toString()); // DEBUG if (method.equals(httpHeader.METHOD_POST)) { GZIPInputStream gzipBody = null; if (requestHeader.containsKey(httpHeader.CONTENT_LENGTH)) { length = Integer.parseInt((String) requestHeader.get(httpHeader.CONTENT_LENGTH)); } else if (requestHeader.gzip()) { length = -1; gzipBody = new GZIPInputStream(body); } // } else { // httpd.sendRespondError(conProp,out,4,403,null,"bad post values",null); // return; // } // if its a POST, it can be either multipart or as args in the body if ((requestHeader.containsKey(httpHeader.CONTENT_TYPE)) && (((String) requestHeader.get(httpHeader.CONTENT_TYPE)).toLowerCase().startsWith("multipart"))) { // parse multipart HashMap files = httpd.parseMultipart(requestHeader, args, (gzipBody!=null)?gzipBody:body, length); // integrate these files into the args if (files != null) { Iterator fit = files.entrySet().iterator(); Map.Entry entry; while (fit.hasNext()) { entry = (Map.Entry) fit.next(); args.put(((String) entry.getKey()) + "$file", entry.getValue()); } } argc = Integer.parseInt((String) requestHeader.get("ARGC")); } else { // parse args in body argc = httpd.parseArgs(args, (gzipBody!=null)?gzipBody:body, length); } } else { // no args argsString = null; args = null; argc = 0; } } else { // simple args in URL (stuff after the "?") argc = httpd.parseArgs(args, argsString); } // check for cross site scripting - attacks in request arguments if (argc > 0) { // check all values for occurrences of script values Enumeration e = args.elements(); // enumeration of values Object val; while (e.hasMoreElements()) { val = e.nextElement(); if ((val != null) && (val instanceof String) && (((String) val).indexOf("<script") >= 0)) { // deny request httpd.sendRespondError(conProp,out,4,403,null,"bad post values",null); return; } } } // we are finished with parsing // the result of value hand-over is in args and argc if (path.length() == 0) { httpd.sendRespondError(conProp,out,4,400,null,"Bad Request",null); out.flush(); return; } File targetClass=null; // locate the file if (!(path.startsWith("/"))) path = "/" + path; // attach leading slash // a different language can be desired (by i.e. ConfigBasic.html) than the one stored in the locale.language String localeSelection = switchboard.getConfig("locale.language","default"); if (args != null && (args.containsKey("language"))) { // TODO 9.11.06 Bost: a class with information about available languages is needed. // the indexOf(".") is just a workaround because there from ConfigLanguage.html commes "de.lng" and // from ConfigBasic.html comes just "de" in the "language" parameter localeSelection = args.get("language", localeSelection); if (localeSelection.indexOf(".") != -1) localeSelection = localeSelection.substring(0, localeSelection.indexOf(".")); } File targetFile = getLocalizedFile(path, localeSelection); String targetExt = conProp.getProperty("EXT",""); targetClass = rewriteClassFile(new File(htDefaultPath, path)); if (path.endsWith("/")) { String testpath; // attach default file name for (int i = 0; i < defaultFiles.length; i++) { testpath = path + defaultFiles[i]; targetFile = getOverlayedFile(testpath); targetClass=getOverlayedClass(testpath); if (targetFile.exists()) { path = testpath; break; } } //no defaultfile, send a dirlisting if(targetFile == null || !targetFile.exists()){ String dirlistFormat = (args==null)?"html":args.get("format","html"); targetExt = dirlistFormat; // this is needed to set the mime type correctly targetFile = getOverlayedFile("/htdocsdefault/dir." + dirlistFormat); targetClass=getOverlayedClass("/htdocsdefault/dir." + dirlistFormat); if(! (( targetFile != null && targetFile.exists()) && ( targetClass != null && targetClass.exists())) ){ httpd.sendRespondError(this.connectionProperties,out,3,500,"dir." + dirlistFormat + " or dir.class not found.",null,null); } } }else{ //XXX: you cannot share a .png/.gif file with a name like a class in htroot. if ( !(targetFile.exists()) && !((path.endsWith("png")||path.endsWith("gif")||path.endsWith(".stream"))&&targetClass!=null ) ){ targetFile = new File(htDocsPath, path); targetClass = rewriteClassFile(new File(htDocsPath, path)); } } //File targetClass = rewriteClassFile(targetFile); //We need tp here servletProperties tp = new servletProperties(); Date targetDate; boolean nocache = false; if ((targetClass != null) && (path.endsWith("png"))) { // call an image-servlet to produce an on-the-fly - generated image Object img = null; try { requestHeader.put(httpHeader.CONNECTION_PROP_CLIENTIP, conProp.getProperty("CLIENTIP")); requestHeader.put(httpHeader.CONNECTION_PROP_PATH, path); // in case that there are no args given, args = null or empty hashmap img = invokeServlet(targetClass, requestHeader, args); } catch (InvocationTargetException e) { this.theLogger.logSevere("INTERNAL ERROR: " + e.toString() + ":" + e.getMessage() + " target exception at " + targetClass + ": " + e.getTargetException().toString() + ":" + e.getTargetException().getMessage() + "; java.awt.graphicsenv='" + System.getProperty("java.awt.graphicsenv","") + "'",e); targetClass = null; } if (img == null) { // error with image generation; send file-not-found httpd.sendRespondError(this.connectionProperties,out,3,404,"File not Found",null,null); } else { if (img instanceof ymageMatrix) { ymageMatrix yp = (ymageMatrix) img; // send an image to client targetDate = new Date(System.currentTimeMillis()); nocache = true; String mimeType = mimeTable.getProperty(targetExt, "text/html"); // generate an byte array from the generated image serverByteBuffer baos = new serverByteBuffer(); // ymagePNGEncoderJDE jde = new // ymagePNGEncoderJDE((ymageMatrixPainter) yp, // ymagePNGEncoderJDE.FILTER_NONE, 0); // byte[] result = jde.pngEncode(); ImageIO.write(yp.getImage(), targetExt, baos); byte[] result = baos.toByteArray(); baos.close(); baos = null; // write the array to the client httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, 200, null, mimeType, result.length, targetDate, null, null, null, null, nocache); if (!method.equals(httpHeader.METHOD_HEAD)) { //Thread.sleep(200); // see below serverFileUtils.write(result, out); } } if (img instanceof Image) { Image i = (Image) img; // send an image to client targetDate = new Date(System.currentTimeMillis()); nocache = true; String mimeType = mimeTable.getProperty(targetExt, "text/html"); // generate an byte array from the generated image int width = i.getWidth(null); if (width < 0) width = 96; // bad hack int height = i.getHeight(null); if (height < 0) height = 96; // bad hack BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); bi.createGraphics().drawImage(i, 0, 0, width, height, null); serverByteBuffer baos = new serverByteBuffer(); ImageIO.write(bi, targetExt, baos); byte[] result = baos.toByteArray(); baos.close(); baos = null; // write the array to the client httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, 200, null, mimeType, result.length, targetDate, null, null, null, null, nocache); if (!method.equals(httpHeader.METHOD_HEAD)) { //Thread.sleep(200); // see below serverFileUtils.write(result, out); } } } } else if ((targetClass != null) && (path.endsWith(".stream"))) { // call rewrite-class requestHeader.put(httpHeader.CONNECTION_PROP_CLIENTIP, conProp.getProperty("CLIENTIP")); requestHeader.put(httpHeader.CONNECTION_PROP_PATH, path); requestHeader.put(httpHeader.CONNECTION_PROP_INPUTSTREAM, body); requestHeader.put(httpHeader.CONNECTION_PROP_OUTPUTSTREAM, out); httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, 200, null); // in case that there are no args given, args = null or empty hashmap /* servletProperties tp = (servlerObjects) */ invokeServlet(targetClass, requestHeader, args); this.forceConnectionClose(); return; } else if ((targetFile.exists()) && (targetFile.canRead())) { // we have found a file that can be written to the client // if this file uses templates, then we use the template // re-write - method to create an result String mimeType = mimeTable.getProperty(targetExt,"text/html"); boolean zipContent = requestHeader.acceptGzip() && httpd.shallTransportZipped("." + conProp.getProperty("EXT","")); if (path.endsWith("html") || path.endsWith("xml") || path.endsWith("rss") || path.endsWith("csv") || path.endsWith("pac") || path.endsWith("src") || path.endsWith("vcf") || path.endsWith("/") || path.equals("/robots.txt")) { /*targetFile = getLocalizedFile(path); if (!(targetFile.exists())) { // try to find that file in the htDocsPath File trialFile = new File(htDocsPath, path); if (trialFile.exists()) targetFile = trialFile; }*/ // call rewrite-class if (targetClass == null) { targetDate = new Date(targetFile.lastModified()); } else { // CGI-class: call the class to create a property for rewriting try { requestHeader.put(httpHeader.CONNECTION_PROP_CLIENTIP, conProp.getProperty("CLIENTIP")); requestHeader.put(httpHeader.CONNECTION_PROP_PATH, path); // in case that there are no args given, args = null or empty hashmap Object tmp = invokeServlet(targetClass, requestHeader, args); if (tmp == null) { // if no args given, then tp will be an empty Hashtable object (not null) tp = new servletProperties(); } else if (tmp instanceof servletProperties) { tp = (servletProperties) tmp; } else { tp = new servletProperties((serverObjects) tmp); } // check if the servlets requests authentification if (tp.containsKey(servletProperties.ACTION_AUTHENTICATE)) { // handle brute-force protection if (authorization != null) { String clientIP = conProp.getProperty("CLIENTIP", "unknown-host"); serverLog.logInfo("HTTPD", "dynamic log-in for account 'admin' in http file handler for path '" + path + "' from host '" + clientIP + "'"); Integer attempts = (Integer) serverCore.bfHost.get(clientIP); if (attempts == null) serverCore.bfHost.put(clientIP, new Integer(1)); else serverCore.bfHost.put(clientIP, new Integer(attempts.intValue() + 1)); } // send authentication request to browser httpHeader headers = getDefaultHeaders(path); headers.put(httpHeader.WWW_AUTHENTICATE,"Basic realm=\"" + tp.get(servletProperties.ACTION_AUTHENTICATE, "") + "\""); httpd.sendRespondHeader(conProp,out,httpVersion,401,headers); return; } else if (tp.containsKey(servletProperties.ACTION_LOCATION)) { String location = tp.get(servletProperties.ACTION_LOCATION, ""); if (location.length() == 0) location = path; httpHeader headers = getDefaultHeaders(path); headers.setCookieVector(tp.getOutgoingHeader().getCookieVector()); //put the cookies into the new header TODO: can we put all headerlines, without trouble? headers.put(httpHeader.LOCATION,location); httpd.sendRespondHeader(conProp,out,httpVersion,302,headers); return; } // add the application version, the uptime and the client name to every rewrite table tp.put(servletProperties.PEER_STAT_VERSION, switchboard.getConfig("version", "")); tp.put(servletProperties.PEER_STAT_UPTIME, ((System.currentTimeMillis() - Long.parseLong(switchboard.getConfig("startupTime","0"))) / 1000) / 60); // uptime in minutes tp.put(servletProperties.PEER_STAT_CLIENTNAME, switchboard.getConfig("peerName", "anomic")); //System.out.println("respond props: " + ((tp == null) ? "null" : tp.toString())); // debug } catch (InvocationTargetException e) { if (e.getCause() instanceof InterruptedException) { throw new InterruptedException(e.getCause().getMessage()); } this.theLogger.logSevere("INTERNAL ERROR: " + e.toString() + ":" + e.getMessage() + " target exception at " + targetClass + ": " + e.getTargetException().toString() + ":" + e.getTargetException().getMessage(),e); targetClass = null; throw e; } targetDate = new Date(System.currentTimeMillis()); nocache = true; } // read templates tp.putAll(templates); // rewrite the file InputStream fis = null; // read the file/template byte[] templateContent = null; if (useTemplateCache) { long fileSize = targetFile.length(); if (fileSize <= 512 * 1024) { // read from cache SoftReference ref = (SoftReference) templateCache.get(targetFile); if (ref != null) { templateContent = (byte[]) ref.get(); if (templateContent == null) templateCache.remove(targetFile); } if (templateContent == null) { // loading the content of the template file into // a byte array templateContent = serverFileUtils.read(targetFile); // storing the content into the cache ref = new SoftReference(templateContent); templateCache.put(targetFile, ref); if (this.theLogger.isLoggable(Level.FINEST)) this.theLogger.logFinest("Cache MISS for file " + targetFile); } else { if (this.theLogger.isLoggable(Level.FINEST)) this.theLogger.logFinest("Cache HIT for file " + targetFile); } // creating an inputstream needed by the template // rewrite function fis = new ByteArrayInputStream(templateContent); templateContent = null; } else { // read from file directly fis = new BufferedInputStream(new FileInputStream(targetFile)); } } else { fis = new BufferedInputStream(new FileInputStream(targetFile)); } // write the array to the client // we can do that either in standard mode (whole thing completely) or in chunked mode // since yacy clients do not understand chunked mode, we use this only for communication with the administrator boolean yacyClient = requestHeader.userAgent().startsWith("yacy"); boolean chunked = !method.equals(httpHeader.METHOD_HEAD) && !yacyClient && httpVersion.equals(httpHeader.HTTP_VERSION_1_1); if (chunked) { // send page in chunks and parse SSIs serverByteBuffer o = new serverByteBuffer(); // apply templates httpTemplate.writeTemplate(fis, o, tp, "-UNRESOLVED_PATTERN-".getBytes("UTF-8")); httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, 200, null, mimeType, -1, targetDate, null, tp.getOutgoingHeader(), null, "chunked", nocache); // send the content in chunked parts, see RFC 2616 section 3.6.1 httpChunkedOutputStream chos = new httpChunkedOutputStream(out); httpSSI.writeSSI(targetFile, o, chos); //chos.write(result); chos.finish(); } else { // send page as whole thing, SSIs are not possible String contentEncoding = (zipContent) ? "gzip" : null; // apply templates serverByteBuffer o = new serverByteBuffer(); if (zipContent) { GZIPOutputStream zippedOut = new GZIPOutputStream(o); httpTemplate.writeTemplate(fis, zippedOut, tp, "-UNRESOLVED_PATTERN-".getBytes("UTF-8")); zippedOut.finish(); zippedOut.flush(); zippedOut.close(); zippedOut = null; } else { httpTemplate.writeTemplate(fis, o, tp, "-UNRESOLVED_PATTERN-".getBytes("UTF-8")); } if (method.equals(httpHeader.METHOD_HEAD)) { httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, 200, null, mimeType, o.length(), targetDate, null, tp.getOutgoingHeader(), contentEncoding, null, nocache); } else { byte[] result = o.toByteArray(); // this interrupts streaming (bad idea!) httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, 200, null, mimeType, result.length, targetDate, null, tp.getOutgoingHeader(), contentEncoding, null, nocache); serverFileUtils.write(result, out); } } } else { // no html int statusCode = 200; int rangeStartOffset = 0; httpHeader header = new httpHeader(); // adding the accept ranges header header.put(httpHeader.ACCEPT_RANGES, "bytes"); // reading the files md5 hash if availabe and use it as ETAG of the resource String targetMD5 = null; File targetMd5File = new File(targetFile + ".md5"); try { if (targetMd5File.exists()) { //String description = null; targetMD5 = new String(serverFileUtils.read(targetMd5File)); pos = targetMD5.indexOf('\n'); if (pos >= 0) { //description = targetMD5.substring(pos + 1); targetMD5 = targetMD5.substring(0, pos); } // using the checksum as ETAG header header.put(httpHeader.ETAG, targetMD5); } } catch (IOException e) { e.printStackTrace(); } if (requestHeader.containsKey(httpHeader.RANGE)) { Object ifRange = requestHeader.ifRange(); if ((ifRange == null)|| (ifRange instanceof Date && targetFile.lastModified() == ((Date)ifRange).getTime()) || (ifRange instanceof String && ifRange.equals(targetMD5))) { String rangeHeaderVal = ((String) requestHeader.get(httpHeader.RANGE)).trim(); if (rangeHeaderVal.startsWith("bytes=")) { String rangesVal = rangeHeaderVal.substring("bytes=".length()); String[] ranges = rangesVal.split(","); if ((ranges.length == 1)&&(ranges[0].endsWith("-"))) { rangeStartOffset = Integer.valueOf(ranges[0].substring(0,ranges[0].length()-1)).intValue(); statusCode = 206; if (header == null) header = new httpHeader(); header.put(httpHeader.CONTENT_RANGE, "bytes " + rangeStartOffset + "-" + (targetFile.length()-1) + "/" + targetFile.length()); } } } } // write the file to the client targetDate = new Date(targetFile.lastModified()); long contentLength = (zipContent)?-1:targetFile.length()-rangeStartOffset; String contentEncoding = (zipContent)?"gzip":null; String transferEncoding = (!httpVersion.equals(httpHeader.HTTP_VERSION_1_1))?null:(zipContent)?"chunked":null; if (!httpVersion.equals(httpHeader.HTTP_VERSION_1_1) && zipContent) forceConnectionClose(); httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, statusCode, null, mimeType, contentLength, targetDate, null, header, contentEncoding, transferEncoding, nocache); if (!method.equals(httpHeader.METHOD_HEAD)) { httpChunkedOutputStream chunkedOut = null; GZIPOutputStream zipped = null; OutputStream newOut = out; if (transferEncoding != null) { chunkedOut = new httpChunkedOutputStream(newOut); newOut = chunkedOut; } if (contentEncoding != null) { zipped = new GZIPOutputStream(newOut); newOut = zipped; } serverFileUtils.copyRange(targetFile,newOut,rangeStartOffset); if (zipped != null) { zipped.flush(); zipped.finish(); } if (chunkedOut != null) { chunkedOut.finish(); } } // check mime type again using the result array: these are 'magics' // if (serverByteBuffer.equals(result, 1, "PNG".getBytes())) mimeType = mimeTable.getProperty("png","text/html"); // else if (serverByteBuffer.equals(result, 0, "GIF89".getBytes())) mimeType = mimeTable.getProperty("gif","text/html"); // else if (serverByteBuffer.equals(result, 6, "JFIF".getBytes())) mimeType = mimeTable.getProperty("jpg","text/html"); //System.out.print("MAGIC:"); for (int i = 0; i < 10; i++) System.out.print(Integer.toHexString((int) result[i]) + ","); System.out.println(); } } else { httpd.sendRespondError(conProp,out,3,404,"File not Found",null,null); return; } } catch (Exception e) { try { // doing some errorhandling ... int httpStatusCode = 400; String httpStatusText = null; StringBuffer errorMessage = new StringBuffer(); Exception errorExc = null; String errorMsg = e.getMessage(); if ( (e instanceof InterruptedException) || ((errorMsg != null) && (errorMsg.startsWith("Socket closed")) && (Thread.currentThread().isInterrupted())) ) { errorMessage.append("Interruption detected while processing query."); httpStatusCode = 503; } else { if ((errorMsg != null) && ( errorMsg.startsWith("Broken pipe") || errorMsg.startsWith("Connection reset") || errorMsg.startsWith("Software caused connection abort") )) { // client closed the connection, so we just end silently errorMessage.append("Client unexpectedly closed connection while processing query."); } else if ((errorMsg != null) && (errorMsg.startsWith("Connection timed out"))) { errorMessage.append("Connection timed out."); } else { errorMessage.append("Unexpected error while processing query."); httpStatusCode = 500; errorExc = e; } } errorMessage.append("\nSession: ").append(Thread.currentThread().getName()) .append("\nQuery: ").append(path) .append("\nClient: ").append(conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP,"unknown")) .append("\nReason: ").append(e.toString()); if (!conProp.containsKey(httpHeader.CONNECTION_PROP_PROXY_RESPOND_HEADER)) { // sending back an error message to the client // if we have not already send an http header httpd.sendRespondError(conProp,out, 4, httpStatusCode, httpStatusText, new String(errorMessage),errorExc); } else { // otherwise we close the connection this.forceConnectionClose(); } // if it is an unexpected error we log it if (httpStatusCode == 500) { this.theLogger.logWarning(new String(errorMessage),e); } } catch (Exception ee) { this.forceConnectionClose(); } } finally { try {out.flush();}catch (Exception e) {} if (((String)requestHeader.get(httpHeader.CONNECTION, "close")).indexOf("keep-alive") == -1) { // wait a little time until everything closes so that clients can read from the streams/sockets try {Thread.sleep(200);} catch (InterruptedException e) {} } } }
diff --git a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/net/internal/XMPPTransmitter.java b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/net/internal/XMPPTransmitter.java index 883ea5d28..26bfe9795 100644 --- a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/net/internal/XMPPTransmitter.java +++ b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/net/internal/XMPPTransmitter.java @@ -1,159 +1,150 @@ /* * DPP - Serious Distributed Pair Programming * (c) Freie Universität Berlin - Fachbereich Mathematik und Informatik - 2006 * (c) Riad Djemili - 2006 * * 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 1, 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ package de.fu_berlin.inf.dpp.net.internal; import java.io.IOException; import org.apache.log4j.Logger; import org.jivesoftware.smack.Connection; import org.jivesoftware.smack.packet.Message; import org.jivesoftware.smack.packet.Packet; import org.jivesoftware.smack.packet.PacketExtension; import de.fu_berlin.inf.dpp.annotations.Component; import de.fu_berlin.inf.dpp.net.ConnectionState; import de.fu_berlin.inf.dpp.net.IConnectionListener; import de.fu_berlin.inf.dpp.net.ITransmitter; import de.fu_berlin.inf.dpp.net.JID; import de.fu_berlin.inf.dpp.net.SarosNet; import de.fu_berlin.inf.dpp.util.Utils; /** * ITransmitter implementation using XMPP, IBB streams and Socks5 streams for * sending packet extensions and packets. */ @Component(module = "net") public class XMPPTransmitter implements ITransmitter, IConnectionListener { private static final Logger log = Logger.getLogger(XMPPTransmitter.class); /** size in bytes that a packet extension must exceed to be compressed */ private static final int PACKET_EXTENSION_COMPRESS_THRESHOLD = Integer .getInteger( "de.fu_berlin.inf.dpp.net.transmitter.PACKET_EXTENSION_COMPRESS_THRESHOLD", 32); private final DataTransferManager dataManager; private Connection connection; public XMPPTransmitter(DataTransferManager dataManager, SarosNet sarosNet) { sarosNet.addListener(this); this.dataManager = dataManager; } @Override public void sendToSessionUser(JID recipient, PacketExtension extension) throws IOException { sendToSessionUser(null, recipient, extension); } @Override public void sendToSessionUser(String connectionID, JID recipient, PacketExtension extension) throws IOException { /* * The TransferDescription can be created out of the session, the name * and namespace of the packet extension and standard values and thus * transparent to users of this method. */ TransferDescription transferDescription = TransferDescription .createCustomTransferDescription().setRecipient(recipient) // .setSender(set by DataTransferManager) .setType(extension.getElementName()) .setNamespace(extension.getNamespace()); byte[] data = extension.toXML().getBytes("UTF-8"); if (data.length > PACKET_EXTENSION_COMPRESS_THRESHOLD) transferDescription.setCompressContent(true); - try { - // recipient is included in the transfer description - if (connectionID == null) - dataManager.sendData(transferDescription, data); - else - dataManager.sendData(connectionID, transferDescription, data); + // recipient is included in the transfer description + if (connectionID == null) + dataManager.sendData(transferDescription, data); + else + dataManager.sendData(connectionID, transferDescription, data); - return; - } catch (IOException e) { - log.error( - "could not send packet extension through a direct connection to " - + Utils.prefix(recipient) + " (" - + Utils.formatByte(data.length) + ")", e); - throw e; - } } @Override public void sendMessageToUser(JID recipient, PacketExtension extension) { Message message = new Message(); message.addExtension(extension); message.setTo(recipient.toString()); assert recipient.toString().equals(message.getTo()); try { sendPacket(message); } catch (IOException e) { log.error("could not send message to " + Utils.prefix(recipient), e); } } @Override public synchronized void sendPacket(Packet packet) throws IOException { if (isConnectionInvalid()) throw new IOException("not connected to a XMPP server"); try { connection.sendPacket(packet); } catch (Exception e) { throw new IOException("could not send packet " + packet + " : " + e.getMessage(), e); } } /** * Determines if the connection can be used. Helper method for error * handling. * * @return false if the connection can be used, true otherwise. */ private synchronized boolean isConnectionInvalid() { return connection == null || !connection.isConnected(); } @Override public synchronized void connectionStateChanged(Connection connection, ConnectionState state) { switch (state) { case CONNECTING: this.connection = connection; break; case ERROR: case NOT_CONNECTED: this.connection = null; break; default: break; // NOP } } }
false
true
public void sendToSessionUser(String connectionID, JID recipient, PacketExtension extension) throws IOException { /* * The TransferDescription can be created out of the session, the name * and namespace of the packet extension and standard values and thus * transparent to users of this method. */ TransferDescription transferDescription = TransferDescription .createCustomTransferDescription().setRecipient(recipient) // .setSender(set by DataTransferManager) .setType(extension.getElementName()) .setNamespace(extension.getNamespace()); byte[] data = extension.toXML().getBytes("UTF-8"); if (data.length > PACKET_EXTENSION_COMPRESS_THRESHOLD) transferDescription.setCompressContent(true); try { // recipient is included in the transfer description if (connectionID == null) dataManager.sendData(transferDescription, data); else dataManager.sendData(connectionID, transferDescription, data); return; } catch (IOException e) { log.error( "could not send packet extension through a direct connection to " + Utils.prefix(recipient) + " (" + Utils.formatByte(data.length) + ")", e); throw e; } }
public void sendToSessionUser(String connectionID, JID recipient, PacketExtension extension) throws IOException { /* * The TransferDescription can be created out of the session, the name * and namespace of the packet extension and standard values and thus * transparent to users of this method. */ TransferDescription transferDescription = TransferDescription .createCustomTransferDescription().setRecipient(recipient) // .setSender(set by DataTransferManager) .setType(extension.getElementName()) .setNamespace(extension.getNamespace()); byte[] data = extension.toXML().getBytes("UTF-8"); if (data.length > PACKET_EXTENSION_COMPRESS_THRESHOLD) transferDescription.setCompressContent(true); // recipient is included in the transfer description if (connectionID == null) dataManager.sendData(transferDescription, data); else dataManager.sendData(connectionID, transferDescription, data); }
diff --git a/openjdk/sun/nio/ch/DotNetSelectorImpl.java b/openjdk/sun/nio/ch/DotNetSelectorImpl.java index ab6c1bb9..47ae5d3d 100644 --- a/openjdk/sun/nio/ch/DotNetSelectorImpl.java +++ b/openjdk/sun/nio/ch/DotNetSelectorImpl.java @@ -1,300 +1,301 @@ /* * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ // Parts Copyright (C) 2002-2007 Jeroen Frijters package sun.nio.ch; import cli.System.Net.Sockets.Socket; import cli.System.Net.Sockets.SocketException; import cli.System.Net.Sockets.AddressFamily; import cli.System.Net.Sockets.SocketType; import cli.System.Net.Sockets.ProtocolType; import cli.System.Net.Sockets.SelectMode; import cli.System.Collections.ArrayList; import java.io.IOException; import java.nio.channels.ClosedSelectorException; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.spi.AbstractSelectableChannel; import java.nio.channels.spi.AbstractSelector; import java.nio.channels.spi.SelectorProvider; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Set; final class DotNetSelectorImpl extends SelectorImpl { private Socket wakeupSourceFd; private ArrayList channelArray = new ArrayList(); private long updateCount = 0; // Lock for interrupt triggering and clearing private final Object interruptLock = new Object(); private volatile boolean interruptTriggered = false; // class for fdMap entries private final static class MapEntry { SelectionKeyImpl ski; long updateCount = 0; long clearedCount = 0; MapEntry(SelectionKeyImpl ski) { this.ski = ski; } } private final HashMap<Socket, MapEntry> fdMap = new HashMap<Socket, MapEntry>(); DotNetSelectorImpl(SelectorProvider sp) { super(sp); createWakeupSocket(); } protected int doSelect(long timeout) throws IOException { if (channelArray == null) throw new ClosedSelectorException(); processDeregisterQueue(); if (interruptTriggered) { resetWakeupSocket(); return 0; } ArrayList read = new ArrayList(); ArrayList write = new ArrayList(); ArrayList error = new ArrayList(); for (int i = 0; i < channelArray.get_Count(); i++) { SelectionKeyImpl ski = (SelectionKeyImpl)channelArray.get_Item(i); int ops = ski.interestOps(); if (ski.channel() instanceof SocketChannelImpl) { // TODO there's a race condition here... if (((SocketChannelImpl)ski.channel()).isConnected()) { ops &= SelectionKey.OP_READ | SelectionKey.OP_WRITE; } else { ops &= SelectionKey.OP_CONNECT; } } if ((ops & (SelectionKey.OP_READ | SelectionKey.OP_ACCEPT)) != 0) { read.Add(ski.getSocket()); } if ((ops & (SelectionKey.OP_WRITE | SelectionKey.OP_CONNECT)) != 0) { write.Add(ski.getSocket()); } if ((ops & SelectionKey.OP_CONNECT) != 0) { error.Add(ski.getSocket()); } } read.Add(wakeupSourceFd); try { begin(); int microSeconds = 1000 * (int)Math.min(Integer.MAX_VALUE / 1000, timeout); try { if (false) throw new SocketException(); - Socket.Select(read, write, error, microSeconds); + // FXBUG docs say that -1 is infinite timeout, but that doesn't appear to work + Socket.Select(read, write, error, timeout < 0 ? Integer.MAX_VALUE : microSeconds); } catch (SocketException _) { read.Clear(); write.Clear(); error.Clear(); } } finally { end(); } processDeregisterQueue(); int updated = updateSelectedKeys(read, write, error); // Done with poll(). Set wakeupSocket to nonsignaled for the next run. resetWakeupSocket(); return updated; } private int updateSelectedKeys(ArrayList read, ArrayList write, ArrayList error) { updateCount++; int keys = processFDSet(updateCount, read, PollArrayWrapper.POLLIN); keys += processFDSet(updateCount, write, PollArrayWrapper.POLLCONN | PollArrayWrapper.POLLOUT); keys += processFDSet(updateCount, error, PollArrayWrapper.POLLIN | PollArrayWrapper.POLLCONN | PollArrayWrapper.POLLOUT); return keys; } private int processFDSet(long updateCount, ArrayList sockets, int rOps) { int numKeysUpdated = 0; for (int i = 0; i < sockets.get_Count(); i++) { Socket desc = (Socket)sockets.get_Item(i); if (desc == wakeupSourceFd) { synchronized (interruptLock) { interruptTriggered = true; } continue; } MapEntry me = fdMap.get(desc); // If me is null, the key was deregistered in the previous // processDeregisterQueue. if (me == null) continue; SelectionKeyImpl sk = me.ski; if (selectedKeys.contains(sk)) { // Key in selected set if (me.clearedCount != updateCount) { if (sk.channel.translateAndSetReadyOps(rOps, sk) && (me.updateCount != updateCount)) { me.updateCount = updateCount; numKeysUpdated++; } } else { // The readyOps have been set; now add if (sk.channel.translateAndUpdateReadyOps(rOps, sk) && (me.updateCount != updateCount)) { me.updateCount = updateCount; numKeysUpdated++; } } me.clearedCount = updateCount; } else { // Key is not in selected set yet if (me.clearedCount != updateCount) { sk.channel.translateAndSetReadyOps(rOps, sk); if ((sk.nioReadyOps() & sk.nioInterestOps()) != 0) { selectedKeys.add(sk); me.updateCount = updateCount; numKeysUpdated++; } } else { // The readyOps have been set; now add sk.channel.translateAndUpdateReadyOps(rOps, sk); if ((sk.nioReadyOps() & sk.nioInterestOps()) != 0) { selectedKeys.add(sk); me.updateCount = updateCount; numKeysUpdated++; } } me.clearedCount = updateCount; } } return numKeysUpdated; } protected void implClose() throws IOException { if (channelArray != null) { // prevent further wakeup wakeup(); for (int i = 0; i < channelArray.get_Count(); i++) { // Deregister channels SelectionKeyImpl ski = (SelectionKeyImpl)channelArray.get_Item(i); deregister(ski); SelectableChannel selch = ski.channel(); if (!selch.isOpen() && !selch.isRegistered()) ((SelChImpl)selch).kill(); } selectedKeys = null; channelArray = null; } } protected void implRegister(SelectionKeyImpl ski) { channelArray.Add(ski); fdMap.put(ski.getSocket(), new MapEntry(ski)); keys.add(ski); } protected void implDereg(SelectionKeyImpl ski) throws IOException { channelArray.Remove(ski); fdMap.remove(ski.getSocket()); keys.remove(ski); selectedKeys.remove(ski); deregister(ski); SelectableChannel selch = ski.channel(); if (!selch.isOpen() && !selch.isRegistered()) { ((SelChImpl)selch).kill(); } } public Selector wakeup() { synchronized (interruptLock) { if (!interruptTriggered) { wakeupSourceFd.Close(); interruptTriggered = true; } } return this; } // Sets Windows wakeup socket to a non-signaled state. private void resetWakeupSocket() { synchronized (interruptLock) { if (interruptTriggered == false) return; createWakeupSocket(); interruptTriggered = false; } } private void createWakeupSocket() { wakeupSourceFd = new Socket(AddressFamily.wrap(AddressFamily.InterNetwork), SocketType.wrap(SocketType.Dgram), ProtocolType.wrap(ProtocolType.Udp)); } }
true
true
protected int doSelect(long timeout) throws IOException { if (channelArray == null) throw new ClosedSelectorException(); processDeregisterQueue(); if (interruptTriggered) { resetWakeupSocket(); return 0; } ArrayList read = new ArrayList(); ArrayList write = new ArrayList(); ArrayList error = new ArrayList(); for (int i = 0; i < channelArray.get_Count(); i++) { SelectionKeyImpl ski = (SelectionKeyImpl)channelArray.get_Item(i); int ops = ski.interestOps(); if (ski.channel() instanceof SocketChannelImpl) { // TODO there's a race condition here... if (((SocketChannelImpl)ski.channel()).isConnected()) { ops &= SelectionKey.OP_READ | SelectionKey.OP_WRITE; } else { ops &= SelectionKey.OP_CONNECT; } } if ((ops & (SelectionKey.OP_READ | SelectionKey.OP_ACCEPT)) != 0) { read.Add(ski.getSocket()); } if ((ops & (SelectionKey.OP_WRITE | SelectionKey.OP_CONNECT)) != 0) { write.Add(ski.getSocket()); } if ((ops & SelectionKey.OP_CONNECT) != 0) { error.Add(ski.getSocket()); } } read.Add(wakeupSourceFd); try { begin(); int microSeconds = 1000 * (int)Math.min(Integer.MAX_VALUE / 1000, timeout); try { if (false) throw new SocketException(); Socket.Select(read, write, error, microSeconds); } catch (SocketException _) { read.Clear(); write.Clear(); error.Clear(); } } finally { end(); } processDeregisterQueue(); int updated = updateSelectedKeys(read, write, error); // Done with poll(). Set wakeupSocket to nonsignaled for the next run. resetWakeupSocket(); return updated; }
protected int doSelect(long timeout) throws IOException { if (channelArray == null) throw new ClosedSelectorException(); processDeregisterQueue(); if (interruptTriggered) { resetWakeupSocket(); return 0; } ArrayList read = new ArrayList(); ArrayList write = new ArrayList(); ArrayList error = new ArrayList(); for (int i = 0; i < channelArray.get_Count(); i++) { SelectionKeyImpl ski = (SelectionKeyImpl)channelArray.get_Item(i); int ops = ski.interestOps(); if (ski.channel() instanceof SocketChannelImpl) { // TODO there's a race condition here... if (((SocketChannelImpl)ski.channel()).isConnected()) { ops &= SelectionKey.OP_READ | SelectionKey.OP_WRITE; } else { ops &= SelectionKey.OP_CONNECT; } } if ((ops & (SelectionKey.OP_READ | SelectionKey.OP_ACCEPT)) != 0) { read.Add(ski.getSocket()); } if ((ops & (SelectionKey.OP_WRITE | SelectionKey.OP_CONNECT)) != 0) { write.Add(ski.getSocket()); } if ((ops & SelectionKey.OP_CONNECT) != 0) { error.Add(ski.getSocket()); } } read.Add(wakeupSourceFd); try { begin(); int microSeconds = 1000 * (int)Math.min(Integer.MAX_VALUE / 1000, timeout); try { if (false) throw new SocketException(); // FXBUG docs say that -1 is infinite timeout, but that doesn't appear to work Socket.Select(read, write, error, timeout < 0 ? Integer.MAX_VALUE : microSeconds); } catch (SocketException _) { read.Clear(); write.Clear(); error.Clear(); } } finally { end(); } processDeregisterQueue(); int updated = updateSelectedKeys(read, write, error); // Done with poll(). Set wakeupSocket to nonsignaled for the next run. resetWakeupSocket(); return updated; }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickSettings.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickSettings.java index 56ecdbac..3638f498 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickSettings.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickSettings.java @@ -1,1799 +1,1803 @@ /* * Copyright (C) 2012 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.systemui.statusbar.phone; import com.android.internal.view.RotationPolicy; import com.android.internal.widget.LockPatternUtils; import com.android.systemui.R; import com.android.systemui.statusbar.phone.QuickSettingsModel.BluetoothState; import com.android.systemui.statusbar.phone.QuickSettingsModel.RSSIState; import com.android.systemui.statusbar.phone.QuickSettingsModel.State; import com.android.systemui.statusbar.phone.QuickSettingsModel.UserState; import com.android.systemui.statusbar.phone.QuickSettingsModel.WifiState; import com.android.systemui.statusbar.policy.BatteryController; import com.android.systemui.statusbar.policy.BluetoothController; import com.android.systemui.statusbar.policy.BrightnessController; import com.android.systemui.statusbar.policy.LocationController; import com.android.systemui.statusbar.policy.NetworkController; import com.android.systemui.statusbar.policy.Prefs; import com.android.systemui.statusbar.policy.ToggleSlider; import android.app.Activity; import android.app.ActivityManagerNative; import android.app.AlertDialog; import android.app.Dialog; import android.app.PendingIntent; import android.bluetooth.BluetoothAdapter; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.ContentResolver; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.UserInfo; import android.content.res.Resources; import android.database.ContentObserver; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.LevelListDrawable; import android.hardware.display.DisplayManager; import android.hardware.display.WifiDisplayStatus; import android.location.LocationManager; import android.nfc.NfcAdapter; import android.net.ConnectivityManager; import android.net.wifi.WifiManager; import android.net.Uri; import android.os.AsyncTask; import android.os.Handler; import android.os.RemoteException; import android.os.UserHandle; import android.os.UserManager; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.Profile; import android.provider.Settings; import android.provider.Settings.SettingNotFoundException; import android.telephony.TelephonyManager; import android.util.Log; import android.util.Pair; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.view.WindowManagerGlobal; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.android.internal.telephony.PhoneConstants; import com.android.systemui.aokp.AokpTarget; import java.io.File; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; /** * */ class QuickSettings { private static final String TAG = "QuickSettings"; public static final boolean SHOW_IME_TILE = false; private static final String TOGGLE_PIPE = "|"; private static final int USER_TILE = 0; private static final int BRIGHTNESS_TILE = 1; private static final int SETTINGS_TILE = 2; private static final int WIFI_TILE = 3; private static final int SIGNAL_TILE = 4; private static final int ROTATE_TILE = 5; private static final int CLOCK_TILE = 6; private static final int GPS_TILE = 7; private static final int IME_TILE = 8; private static final int BATTERY_TILE = 9; private static final int AIRPLANE_TILE = 10; private static final int BLUETOOTH_TILE = 11; private static final int SWAGGER_TILE = 12; private static final int VIBRATE_TILE = 13; private static final int SILENT_TILE = 14; private static final int FCHARGE_TILE = 15; private static final int SYNC_TILE = 16; private static final int NFC_TILE = 17; private static final int TORCH_TILE = 18; private static final int WIFI_TETHER_TILE = 19; private static final int USB_TETHER_TILE = 20; private static final int TWOG_TILE = 21; private static final int LTE_TILE = 22; private static final int FAV_CONTACT_TILE = 23; // private static final int BT_TETHER_TILE = 23; private static final int SOUND_STATE_TILE = 24; public static final String USER_TOGGLE = "USER"; public static final String BRIGHTNESS_TOGGLE = "BRIGHTNESS"; public static final String SETTINGS_TOGGLE = "SETTINGS"; public static final String WIFI_TOGGLE = "WIFI"; public static final String SIGNAL_TOGGLE = "SIGNAL"; public static final String ROTATE_TOGGLE = "ROTATE"; public static final String CLOCK_TOGGLE = "CLOCK"; public static final String GPS_TOGGLE = "GPS"; public static final String IME_TOGGLE = "IME"; public static final String BATTERY_TOGGLE = "BATTERY"; public static final String AIRPLANE_TOGGLE = "AIRPLANE_MODE"; public static final String BLUETOOTH_TOGGLE = "BLUETOOTH"; public static final String SWAGGER_TOGGLE = "SWAGGER"; public static final String VIBRATE_TOGGLE = "VIBRATE"; public static final String SILENT_TOGGLE = "SILENT"; public static final String FCHARGE_TOGGLE = "FCHARGE"; public static final String SYNC_TOGGLE = "SYNC"; public static final String NFC_TOGGLE = "NFC"; public static final String TORCH_TOGGLE = "TORCH"; public static final String WIFI_TETHER_TOGGLE = "WIFITETHER"; // public static final String BT_TETHER_TOGGLE = "BTTETHER"; public static final String USB_TETHER_TOGGLE = "USBTETHER"; public static final String TWOG_TOGGLE = "2G"; public static final String LTE_TOGGLE = "LTE"; public static final String FAV_CONTACT_TOGGLE = "FAVCONTACT"; public static final String SOUND_STATE_TOGGLE = "SOUNDSTATE"; private static final String DEFAULT_TOGGLES = "default"; private int mWifiApState = WifiManager.WIFI_AP_STATE_DISABLED; private int mWifiState = WifiManager.WIFI_STATE_DISABLED; private int mDataState = -1; private boolean usbTethered; private Context mContext; private PanelBar mBar; private QuickSettingsModel mModel; private ViewGroup mContainerView; private DisplayManager mDisplayManager; private WifiDisplayStatus mWifiDisplayStatus; private WifiManager wifiManager; private ConnectivityManager connManager; private LocationManager locationManager; private PhoneStatusBar mStatusBarService; private BluetoothState mBluetoothState; private TelephonyManager tm; private ConnectivityManager mConnService; private NfcAdapter mNfcAdapter; private AokpTarget mAokpTarget; private BrightnessController mBrightnessController; private BluetoothController mBluetoothController; private Dialog mBrightnessDialog; private int mBrightnessDialogShortTimeout; private int mBrightnessDialogLongTimeout; private AsyncTask<Void, Void, Pair<String, Drawable>> mUserInfoTask; private AsyncTask<Void, Void, Pair<String, Drawable>> mFavContactInfoTask; private LevelListDrawable mBatteryLevels; private LevelListDrawable mChargingBatteryLevels; boolean mTilesSetUp = false; private Handler mHandler; private ArrayList<String> toggles; private String userToggles = null; private long tacoSwagger = 0; private boolean tacoToggle = false; private int mTileTextSize = 12; private String mFastChargePath; private HashMap<String, Integer> toggleMap; private HashMap<String, Integer> getToggleMap() { if (toggleMap == null) { toggleMap = new HashMap<String, Integer>(); toggleMap.put(USER_TOGGLE, USER_TILE); toggleMap.put(BRIGHTNESS_TOGGLE, BRIGHTNESS_TILE); toggleMap.put(SETTINGS_TOGGLE, SETTINGS_TILE); toggleMap.put(WIFI_TOGGLE, WIFI_TILE); toggleMap.put(SIGNAL_TOGGLE, SIGNAL_TILE); toggleMap.put(ROTATE_TOGGLE, ROTATE_TILE); toggleMap.put(CLOCK_TOGGLE, CLOCK_TILE); toggleMap.put(GPS_TOGGLE, GPS_TILE); toggleMap.put(IME_TOGGLE, IME_TILE); toggleMap.put(BATTERY_TOGGLE, BATTERY_TILE); toggleMap.put(AIRPLANE_TOGGLE, AIRPLANE_TILE); toggleMap.put(BLUETOOTH_TOGGLE, BLUETOOTH_TILE); toggleMap.put(VIBRATE_TOGGLE, VIBRATE_TILE); toggleMap.put(SILENT_TOGGLE, SILENT_TILE); toggleMap.put(FCHARGE_TOGGLE, FCHARGE_TILE); toggleMap.put(SYNC_TOGGLE, SYNC_TILE); toggleMap.put(NFC_TOGGLE, NFC_TILE); toggleMap.put(TORCH_TOGGLE, TORCH_TILE); toggleMap.put(WIFI_TETHER_TOGGLE, WIFI_TETHER_TILE); toggleMap.put(USB_TETHER_TOGGLE, USB_TETHER_TILE); toggleMap.put(TWOG_TOGGLE, TWOG_TILE); toggleMap.put(LTE_TOGGLE, LTE_TILE); toggleMap.put(FAV_CONTACT_TOGGLE, FAV_CONTACT_TILE); toggleMap.put(SOUND_STATE_TOGGLE, SOUND_STATE_TILE); //toggleMap.put(BT_TETHER_TOGGLE, BT_TETHER_TILE); } return toggleMap; } private final RotationPolicy.RotationPolicyListener mRotationPolicyListener = new RotationPolicy.RotationPolicyListener() { @Override public void onChange() { mModel.onRotationLockChanged(); } }; public QuickSettings(Context context, QuickSettingsContainerView container) { mDisplayManager = (DisplayManager) context.getSystemService(Context.DISPLAY_SERVICE); mContext = context; mContainerView = container; mModel = new QuickSettingsModel(context); mWifiDisplayStatus = new WifiDisplayStatus(); wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE); tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); connManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE); locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE); mBluetoothState = new QuickSettingsModel.BluetoothState(); mHandler = new Handler(); mAokpTarget = new AokpTarget(mContext); Resources r = mContext.getResources(); mBatteryLevels = (LevelListDrawable) r.getDrawable(R.drawable.qs_sys_battery); mChargingBatteryLevels = (LevelListDrawable) r.getDrawable(R.drawable.qs_sys_battery_charging); mBrightnessDialogLongTimeout = r.getInteger(R.integer.quick_settings_brightness_dialog_long_timeout); mBrightnessDialogShortTimeout = r.getInteger(R.integer.quick_settings_brightness_dialog_short_timeout); mFastChargePath = r.getString(com.android.internal.R.string.config_fastChargePath); IntentFilter filter = new IntentFilter(); filter.addAction(DisplayManager.ACTION_WIFI_DISPLAY_STATUS_CHANGED); filter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED); filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); filter.addAction(Intent.ACTION_USER_SWITCHED); filter.addAction(WifiManager.WIFI_AP_STATE_CHANGED_ACTION); mContext.registerReceiver(mReceiver, filter); IntentFilter profileFilter = new IntentFilter(); profileFilter.addAction(ContactsContract.Intents.ACTION_PROFILE_CHANGED); profileFilter.addAction(Intent.ACTION_USER_INFO_CHANGED); mContext.registerReceiverAsUser(mProfileReceiver, UserHandle.ALL, profileFilter, null, null); new SettingsObserver(new Handler()).observe(); new SoundObserver(new Handler()).observe(); new NetworkModeObserver(new Handler()).observe(); } public void setBar(PanelBar bar) { mBar = bar; } public void setService(PhoneStatusBar phoneStatusBar) { mStatusBarService = phoneStatusBar; } public PhoneStatusBar getService() { return mStatusBarService; } public void setImeWindowStatus(boolean visible) { mModel.onImeWindowStatusChanged(visible); } public void setup(NetworkController networkController, BluetoothController bluetoothController, BatteryController batteryController, LocationController locationController) { mBluetoothController = bluetoothController; setupQuickSettings(); updateWifiDisplayStatus(); updateResources(); ArrayList<String> userTiles = getCustomUserTiles(); if (userTiles.contains(SIGNAL_TOGGLE) || userTiles.contains(WIFI_TOGGLE)) networkController.addNetworkSignalChangedCallback(mModel); if (userTiles.contains(BLUETOOTH_TOGGLE)) bluetoothController.addStateChangedCallback(mModel); if (userTiles.contains(BATTERY_TOGGLE)) batteryController.addStateChangedCallback(mModel); if (userTiles.contains(GPS_TOGGLE)) locationController.addStateChangedCallback(mModel); if (userTiles.contains(ROTATE_TOGGLE)) RotationPolicy.registerRotationPolicyListener(mContext, mRotationPolicyListener, UserHandle.USER_ALL); } private void queryForUserInformation() { Context currentUserContext = null; UserInfo userInfo = null; try { userInfo = ActivityManagerNative.getDefault().getCurrentUser(); currentUserContext = mContext.createPackageContextAsUser("android", 0, new UserHandle(userInfo.id)); } catch (NameNotFoundException e) { Log.e(TAG, "Couldn't create user context", e); throw new RuntimeException(e); } catch (RemoteException e) { Log.e(TAG, "Couldn't get user info", e); } final int userId = userInfo.id; final String userName = userInfo.name; final Context context = currentUserContext; mUserInfoTask = new AsyncTask<Void, Void, Pair<String, Drawable>>() { @Override protected Pair<String, Drawable> doInBackground(Void... params) { final UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE); // Fall back to the UserManager nickname if we can't read the // name from the local // profile below. String name = userName; Drawable avatar = null; Bitmap rawAvatar = um.getUserIcon(userId); if (rawAvatar != null) { avatar = new BitmapDrawable(mContext.getResources(), rawAvatar); } else { avatar = mContext.getResources().getDrawable(R.drawable.ic_qs_default_user); } // If it's a single-user device, get the profile name, since the // nickname is not // usually valid if (um.getUsers().size() <= 1) { // Try and read the display name from the local profile final Cursor cursor = context.getContentResolver().query( Profile.CONTENT_URI, new String[] { Phone._ID, Phone.DISPLAY_NAME }, null, null, null); if (cursor != null) { try { if (cursor.moveToFirst()) { name = cursor.getString(cursor.getColumnIndex(Phone.DISPLAY_NAME)); } } finally { cursor.close(); } } } return new Pair<String, Drawable>(name, avatar); } @Override protected void onPostExecute(Pair<String, Drawable> result) { super.onPostExecute(result); mModel.setUserTileInfo(result.first, result.second); mUserInfoTask = null; } }; mUserInfoTask.execute(); } private void queryForFavContactInformation() { mFavContactInfoTask = new AsyncTask<Void, Void, Pair<String, Drawable>>() { @Override protected Pair<String, Drawable> doInBackground(Void... params) { String name = ""; Drawable avatar = mContext.getResources().getDrawable(R.drawable.ic_qs_default_user); Bitmap rawAvatar = null; String lookupKey = Settings.System.getString(mContext.getContentResolver(), Settings.System.QUICK_TOGGLE_FAV_CONTACT); if (lookupKey != null && lookupKey.length() > 0) { Uri lookupUri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey); Uri res = ContactsContract.Contacts.lookupContact(mContext.getContentResolver(), lookupUri); String[] projection = new String[] { ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.Contacts.PHOTO_URI, ContactsContract.Contacts.LOOKUP_KEY}; final Cursor cursor = mContext.getContentResolver().query(res,projection,null,null,null); if (cursor != null) { try { if (cursor.moveToFirst()) { name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); } } finally { cursor.close(); } } InputStream input = ContactsContract.Contacts. openContactPhotoInputStream(mContext.getContentResolver(), res, true); if (input != null) { rawAvatar = BitmapFactory.decodeStream(input); } if (rawAvatar != null) { avatar = new BitmapDrawable(mContext.getResources(), rawAvatar); } } return new Pair<String, Drawable>(name, avatar); } @Override protected void onPostExecute(Pair<String, Drawable> result) { super.onPostExecute(result); mModel.setFavContactTileInfo(result.first, result.second); mFavContactInfoTask = null; } }; mFavContactInfoTask.execute(); } private void setupQuickSettings() { // Setup the tiles that we are going to be showing (including the // temporary ones) LayoutInflater inflater = LayoutInflater.from(mContext); addUserTiles(mContainerView, inflater); addTemporaryTiles(mContainerView, inflater); queryForUserInformation(); queryForFavContactInformation(); mTilesSetUp = true; } private void startSettingsActivity(String action) { Intent intent = new Intent(action); startSettingsActivity(intent); } private void startSettingsActivity(Intent intent) { startSettingsActivity(intent, true); } private void startSettingsActivity(Intent intent, boolean onlyProvisioned) { if (onlyProvisioned && !getService().isDeviceProvisioned()) return; try { // Dismiss the lock screen when Settings starts. ActivityManagerNative.getDefault().dismissKeyguardOnNextActivity(); } catch (RemoteException e) { } intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); mContext.startActivityAsUser(intent, new UserHandle(UserHandle.USER_CURRENT)); getService().animateCollapsePanels(); } private QuickSettingsTileView getTile(int tile, ViewGroup parent, LayoutInflater inflater) { final Resources r = mContext.getResources(); QuickSettingsTileView quick = null; switch (tile) { case USER_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_user, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mBar.collapseAllPanels(true); final UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE); if (um.getUsers(true).size() > 1) { try { WindowManagerGlobal.getWindowManagerService().lockNow(null); } catch (RemoteException e) { Log.e(TAG, "Couldn't show user switcher", e); } } else { Intent intent = ContactsContract.QuickContact.composeQuickContactsIntent( mContext, v, ContactsContract.Profile.CONTENT_URI, ContactsContract.QuickContact.MODE_LARGE, null); mContext.startActivityAsUser(intent, new UserHandle(UserHandle.USER_CURRENT)); } } }); mModel.addUserTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { UserState us = (UserState) state; ImageView iv = (ImageView) view.findViewById(R.id.user_imageview); TextView tv = (TextView) view.findViewById(R.id.user_textview); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); iv.setImageDrawable(us.avatar); view.setContentDescription(mContext.getString( R.string.accessibility_quick_settings_user, state.label)); } }); break; case CLOCK_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_time, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent("android.intent.action.MAIN"); intent.setComponent(ComponentName.unflattenFromString("com.android.deskclock.AlarmProvider")); intent.addCategory("android.intent.category.LAUNCHER"); startSettingsActivity(intent); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(Intent.ACTION_QUICK_CLOCK); return true; } }); mModel.addTimeTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State alarmState) { TextView tv = (TextView) view.findViewById(R.id.clock_textview); tv.setTextSize(1, mTileTextSize); } }); break; case SIGNAL_TILE: if (mModel.deviceSupportsTelephony()) { // Mobile Network state quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_rssi, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { connManager.setMobileDataEnabled(connManager.getMobileDataEnabled() ? false : true); String strData = connManager.getMobileDataEnabled() ? r.getString(R.string.quick_settings_data_off_label) : r.getString(R.string.quick_settings_data_on_label); Toast.makeText(mContext, strData, Toast.LENGTH_SHORT).show(); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { Intent intent = new Intent(); intent.setComponent(new ComponentName( "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity")); startSettingsActivity(intent); return true; } }); mModel.addRSSITile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { RSSIState rssiState = (RSSIState) state; ImageView iv = (ImageView) view.findViewById(R.id.rssi_image); ImageView iov = (ImageView) view.findViewById(R.id.rssi_overlay_image); TextView tv = (TextView) view.findViewById(R.id.rssi_textview); iv.setImageResource(rssiState.signalIconId); if (rssiState.dataTypeIconId > 0) { iov.setImageResource(rssiState.dataTypeIconId); } else { iov.setImageDrawable(null); } tv.setText(state.label); tv.setTextSize(1, mTileTextSize); view.setContentDescription(mContext.getResources().getString( R.string.accessibility_quick_settings_mobile, rssiState.signalContentDescription, rssiState.dataContentDescription, state.label)); } }); } break; case BRIGHTNESS_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_brightness, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mBar.collapseAllPanels(true); showBrightnessDialog(); } }); mModel.addBrightnessTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.brightness_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); dismissBrightnessDialog(mBrightnessDialogShortTimeout); } }); break; case SETTINGS_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_settings, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_SETTINGS); } }); mModel.addSettingsTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.settings_tileview); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } }); break; case WIFI_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_wifi, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mWifiState = wifiManager.getWifiState(); if (mWifiState == WifiManager.WIFI_STATE_DISABLED || mWifiState == WifiManager.WIFI_STATE_DISABLING) { changeWifiState(true); } else { changeWifiState(false); } mHandler.postDelayed(delayedRefresh, 1000); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_WIFI_SETTINGS); return true; } }); mModel.addWifiTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { WifiState wifiState = (WifiState) state; TextView tv = (TextView) view.findViewById(R.id.wifi_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, wifiState.iconId, 0, 0); tv.setText(wifiState.label); tv.setTextSize(1, mTileTextSize); view.setContentDescription(mContext.getString( R.string.accessibility_quick_settings_wifi, wifiState.signalContentDescription, (wifiState.connected) ? wifiState.label : "")); } }); break; case TWOG_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_twog, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { mDataState = Settings.Global.getInt(mContext.getContentResolver(), Settings.Global.PREFERRED_NETWORK_MODE); } catch (SettingNotFoundException e) { e.printStackTrace(); } if (mDataState == PhoneConstants.NT_MODE_GSM_ONLY) { tm.toggle2G(false); } else { tm.toggle2G(true); } mModel.refresh2gTile(); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_DATA_ROAMING_SETTINGS); return true; } }); mModel.add2gTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.twog_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } }); break; case LTE_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_lte, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { mDataState = Settings.Global.getInt(mContext.getContentResolver(), Settings.Global.PREFERRED_NETWORK_MODE); } catch (SettingNotFoundException e) { e.printStackTrace(); } if (mDataState == PhoneConstants.NT_MODE_LTE_CDMA_EVDO || mDataState == PhoneConstants.NT_MODE_GLOBAL) { tm.toggleLTE(false); } else { tm.toggleLTE(true); } mModel.refreshLTETile(); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS); return true; } }); mModel.addLTETile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.lte_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } }); break; case VIBRATE_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_vibrate, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mAokpTarget.launchAction(mAokpTarget.ACTION_VIB); mModel.refreshVibrateTile(); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_SOUND_SETTINGS); return true; } }); mModel.addVibrateTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.vibrate_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } }); break; case SILENT_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_silent, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mAokpTarget.launchAction(mAokpTarget.ACTION_SILENT); mModel.refreshSilentTile(); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_SOUND_SETTINGS); return true; } }); mModel.addSilentTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.silent_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } }); break; case SOUND_STATE_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_sound_state, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mAokpTarget.launchAction(mAokpTarget.ACTION_SILENT_VIB); mModel.refreshSoundStateTile(); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_SOUND_SETTINGS); return true; } }); mModel.addSoundStateTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.sound_state_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } }); break; case TORCH_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_torch, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mAokpTarget.launchAction(mAokpTarget.ACTION_TORCH); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { // maybe something here? return true; } }); mModel.addTorchTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.torch_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } }); break; case FCHARGE_TILE: if((mFastChargePath == null || mFastChargePath.isEmpty()) || !new File(mFastChargePath).exists()) { // config not set or config set and kernel doesn't support it? break; } quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_fcharge, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setFastCharge(!Prefs.getLastFastChargeState(mContext)); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { // What do we put here? return true; } }); mModel.addFChargeTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.fcharge_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } }); restoreFChargeState(); break; case WIFI_TETHER_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_wifi_tether, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mWifiApState = wifiManager.getWifiApState(); if (mWifiApState == WifiManager.WIFI_AP_STATE_DISABLED || mWifiApState == WifiManager.WIFI_AP_STATE_DISABLING) { changeWifiApState(true); } else { changeWifiApState(false); } mHandler.postDelayed(delayedRefresh, 1000); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { - startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS); + Intent intent = new Intent(); + intent.setComponent(new ComponentName("com.android.settings", "com.android.settings.Settings$TetherSettingsActivity")); + startSettingsActivity(intent); return true; } }); mModel.addWifiTetherTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.wifi_tether_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } }); break; case USB_TETHER_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_usb_tether, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean enabled = updateUsbState() ? false : true; if (connManager.setUsbTethering(enabled) == ConnectivityManager.TETHER_ERROR_NO_ERROR) { mHandler.postDelayed(delayedRefresh, 1000); } } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { - startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS); + Intent intent = new Intent(); + intent.setComponent(new ComponentName("com.android.settings", "com.android.settings.Settings$TetherSettingsActivity")); + startSettingsActivity(intent); return true; } }); mModel.addUSBTetherTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.usb_tether_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } }); break; case SYNC_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_sync, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean enabled = ContentResolver.getMasterSyncAutomatically(); ContentResolver.setMasterSyncAutomatically(enabled ? false : true); mModel.refreshSyncTile(); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_SYNC_SETTINGS); return true; } }); mModel.addSyncTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.sync_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } }); break; case NFC_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_nfc, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean enabled = false; if (mNfcAdapter == null) { mNfcAdapter = NfcAdapter.getDefaultAdapter(mContext); } try { enabled = mNfcAdapter.isEnabled(); if (enabled) { mNfcAdapter.disable(); } else { mNfcAdapter.enable(); } } catch (NullPointerException ex) { // we'll ignore this click } } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS); return true; } }); mModel.addNFCTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.nfc_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } }); break; case ROTATE_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_rotation_lock, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean locked = RotationPolicy.isRotationLocked(mContext); RotationPolicy.setRotationLock(mContext, !locked); } }); mModel.addRotationLockTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.rotation_lock_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } }); break; case BATTERY_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_battery, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startSettingsActivity(Intent.ACTION_POWER_USAGE_SUMMARY); } }); mModel.addBatteryTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { QuickSettingsModel.BatteryState batteryState = (QuickSettingsModel.BatteryState) state; TextView tv = (TextView) view.findViewById(R.id.battery_textview); ImageView iv = (ImageView) view.findViewById(R.id.battery_image); Drawable d = batteryState.pluggedIn ? mChargingBatteryLevels : mBatteryLevels; String t; if (batteryState.batteryLevel == 100) { t = mContext.getString(R.string.quick_settings_battery_charged_label); } else { t = batteryState.pluggedIn ? mContext.getString(R.string.quick_settings_battery_charging_label, batteryState.batteryLevel) : mContext.getString(R.string.status_bar_settings_battery_meter_format, batteryState.batteryLevel); } iv.setImageDrawable(d); iv.setImageLevel(batteryState.batteryLevel); tv.setText(t); tv.setTextSize(1, mTileTextSize); view.setContentDescription( mContext.getString(R.string.accessibility_quick_settings_battery, t)); } }); break; case AIRPLANE_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_airplane, inflater); mModel.addAirplaneModeTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.airplane_mode_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); String airplaneState = mContext.getString( (state.enabled) ? R.string.accessibility_desc_on : R.string.accessibility_desc_off); view.setContentDescription( mContext.getString(R.string.accessibility_quick_settings_airplane, airplaneState)); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } }); break; case BLUETOOTH_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_bluetooth, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); if (adapter.isEnabled()) { adapter.disable(); } else { adapter.enable(); } } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS); return true; } }); mModel.addBluetoothTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { BluetoothState bluetoothState = (BluetoothState) state; TextView tv = (TextView) view.findViewById(R.id.bluetooth_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); Resources r = mContext.getResources(); String label = state.label; /* * //TODO: Show connected bluetooth device label * Set<BluetoothDevice> btDevices = * mBluetoothController.getBondedBluetoothDevices(); if * (btDevices.size() == 1) { // Show the name of the * bluetooth device you are connected to label = * btDevices.iterator().next().getName(); } else if * (btDevices.size() > 1) { // Show a generic label * about the number of bluetooth devices label = * r.getString(R.string * .quick_settings_bluetooth_multiple_devices_label, * btDevices.size()); } */ view.setContentDescription(mContext.getString( R.string.accessibility_quick_settings_bluetooth, bluetoothState.stateContentDescription)); tv.setText(label); tv.setTextSize(1, mTileTextSize); } }); break; case GPS_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_location, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean gpsEnabled = Settings.Secure.isLocationProviderEnabled( mContext.getContentResolver(), LocationManager.GPS_PROVIDER); Settings.Secure.setLocationProviderEnabled(mContext.getContentResolver(), LocationManager.GPS_PROVIDER, gpsEnabled ? false : true); TextView tv = (TextView) v.findViewById(R.id.location_textview); tv.setText(gpsEnabled ? R.string.quick_settings_gps_off_label : R.string.quick_settings_gps_on_label); tv.setCompoundDrawablesWithIntrinsicBounds(0, gpsEnabled ? R.drawable.ic_qs_gps_off : R.drawable.ic_qs_gps_on, 0, 0); tv.setTextSize(1, mTileTextSize); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); return true; } }); mModel.addLocationTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { boolean gpsEnabled = Settings.Secure.isLocationProviderEnabled( mContext.getContentResolver(), LocationManager.GPS_PROVIDER); TextView tv = (TextView) view.findViewById(R.id.location_textview); tv.setText(gpsEnabled ? R.string.quick_settings_gps_on_label : R.string.quick_settings_gps_off_label); if (state.iconId == 0) { tv.setCompoundDrawablesWithIntrinsicBounds(0, gpsEnabled ? R.drawable.ic_qs_gps_on : R.drawable.ic_qs_gps_off, 0, 0); } else { tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); } tv.setTextSize(1, mTileTextSize); } }); break; case IME_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_ime, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { mBar.collapseAllPanels(true); Intent intent = new Intent(Settings.ACTION_SHOW_INPUT_METHOD_PICKER); PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0); pendingIntent.send(); } catch (Exception e) { } } }); mModel.addImeTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.ime_textview); if (state.label != null) { tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } } }); break; case FAV_CONTACT_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_user, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String lookupKey = Settings.System.getString(mContext.getContentResolver(), Settings.System.QUICK_TOGGLE_FAV_CONTACT); if (lookupKey != null && lookupKey.length() > 0) { mBar.collapseAllPanels(true); Uri lookupUri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey); Uri res = ContactsContract.Contacts.lookupContact(mContext.getContentResolver(), lookupUri); Intent intent = ContactsContract.QuickContact.composeQuickContactsIntent( mContext, v, res, ContactsContract.QuickContact.MODE_LARGE, null); mContext.startActivityAsUser(intent, new UserHandle(UserHandle.USER_CURRENT)); } } }); mModel.addFavContactTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { UserState us = (UserState) state; ImageView iv = (ImageView) view.findViewById(R.id.user_imageview); TextView tv = (TextView) view.findViewById(R.id.user_textview); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); iv.setImageDrawable(us.avatar); view.setContentDescription(mContext.getString( R.string.accessibility_quick_settings_user, state.label)); } }); break; } return quick; } private ArrayList<String> getCustomUserTiles() { ArrayList<String> tiles = new ArrayList<String>(); if (userToggles == null) return getDefaultTiles(); String[] splitter = userToggles.split("\\" + TOGGLE_PIPE); for (String toggle : splitter) { tiles.add(toggle); } return tiles; } private ArrayList<String> getDefaultTiles() { ArrayList<String> tiles = new ArrayList<String>(); tiles.add(USER_TOGGLE); tiles.add(BRIGHTNESS_TOGGLE); tiles.add(SETTINGS_TOGGLE); tiles.add(WIFI_TOGGLE); if (mModel.deviceSupportsTelephony()) { tiles.add(SIGNAL_TOGGLE); } if (mContext.getResources().getBoolean(R.bool.quick_settings_show_rotation_lock)) { tiles.add(ROTATE_TOGGLE); } tiles.add(BATTERY_TOGGLE); tiles.add(AIRPLANE_TOGGLE); if (mModel.deviceSupportsBluetooth()) { tiles.add(BLUETOOTH_TOGGLE); } return tiles; } private void addUserTiles(ViewGroup parent, LayoutInflater inflater) { if (parent.getChildCount() > 0) parent.removeAllViews(); toggles = getCustomUserTiles(); if (!toggles.get(0).equals("")) { for (String toggle : toggles) { View v = getTile(getToggleMap().get(toggle), parent, inflater); if(v != null) { parent.addView(v); } } } } private void addTemporaryTiles(final ViewGroup parent, final LayoutInflater inflater) { // Alarm tile QuickSettingsTileView alarmTile = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); alarmTile.setContent(R.layout.quick_settings_tile_alarm, inflater); alarmTile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO: Jump into the alarm application Intent intent = new Intent(); intent.setComponent(new ComponentName( "com.android.deskclock", "com.android.deskclock.AlarmClock")); startSettingsActivity(intent); } }); mModel.addAlarmTile(alarmTile, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State alarmState) { TextView tv = (TextView) view.findViewById(R.id.alarm_textview); tv.setText(alarmState.label); tv.setTextSize(1, mTileTextSize); view.setVisibility(alarmState.enabled ? View.VISIBLE : View.GONE); view.setContentDescription(mContext.getString( R.string.accessibility_quick_settings_alarm, alarmState.label)); } }); parent.addView(alarmTile); // Wifi Display QuickSettingsTileView wifiDisplayTile = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); wifiDisplayTile.setContent(R.layout.quick_settings_tile_wifi_display, inflater); wifiDisplayTile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_WIFI_DISPLAY_SETTINGS); } }); mModel.addWifiDisplayTile(wifiDisplayTile, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.wifi_display_textview); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); view.setVisibility(state.enabled ? View.VISIBLE : View.GONE); } }); parent.addView(wifiDisplayTile); // Bug reports QuickSettingsTileView bugreportTile = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); bugreportTile.setContent(R.layout.quick_settings_tile_bugreport, inflater); bugreportTile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mBar.collapseAllPanels(true); showBugreportDialog(); } }); mModel.addBugreportTile(bugreportTile, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { view.setVisibility(state.enabled ? View.VISIBLE : View.GONE); } }); parent.addView(bugreportTile); /* * QuickSettingsTileView mediaTile = (QuickSettingsTileView) * inflater.inflate(R.layout.quick_settings_tile, parent, false); * mediaTile.setContent(R.layout.quick_settings_tile_media, inflater); * parent.addView(mediaTile); QuickSettingsTileView imeTile = * (QuickSettingsTileView) * inflater.inflate(R.layout.quick_settings_tile, parent, false); * imeTile.setContent(R.layout.quick_settings_tile_ime, inflater); * imeTile.setOnClickListener(new View.OnClickListener() { * @Override public void onClick(View v) { parent.removeViewAt(0); } }); * parent.addView(imeTile); */ } void updateResources() { Resources r = mContext.getResources(); // Update the model mModel.updateResources(getCustomUserTiles()); ((QuickSettingsContainerView) mContainerView).updateResources(); mContainerView.requestLayout(); // Reset the dialog boolean isBrightnessDialogVisible = false; if (mBrightnessDialog != null) { removeAllBrightnessDialogCallbacks(); isBrightnessDialogVisible = mBrightnessDialog.isShowing(); mBrightnessDialog.dismiss(); } mBrightnessDialog = null; if (isBrightnessDialogVisible) { showBrightnessDialog(); } } private void removeAllBrightnessDialogCallbacks() { mHandler.removeCallbacks(mDismissBrightnessDialogRunnable); } private Runnable mDismissBrightnessDialogRunnable = new Runnable() { public void run() { if (mBrightnessDialog != null && mBrightnessDialog.isShowing()) { mBrightnessDialog.dismiss(); } removeAllBrightnessDialogCallbacks(); }; }; private void showBrightnessDialog() { if (mBrightnessDialog == null) { mBrightnessDialog = new Dialog(mContext); mBrightnessDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); mBrightnessDialog.setContentView(R.layout.quick_settings_brightness_dialog); mBrightnessDialog.setCanceledOnTouchOutside(true); mBrightnessController = new BrightnessController(mContext, (ImageView) mBrightnessDialog.findViewById(R.id.brightness_icon), (ToggleSlider) mBrightnessDialog.findViewById(R.id.brightness_slider)); mBrightnessController.addStateChangedCallback(mModel); mBrightnessDialog.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { mBrightnessController = null; } }); mBrightnessDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); mBrightnessDialog.getWindow().getAttributes().privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS; mBrightnessDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); } if (!mBrightnessDialog.isShowing()) { try { WindowManagerGlobal.getWindowManagerService().dismissKeyguard(); } catch (RemoteException e) { } mBrightnessDialog.show(); dismissBrightnessDialog(mBrightnessDialogLongTimeout); } } private void dismissBrightnessDialog(int timeout) { removeAllBrightnessDialogCallbacks(); if (mBrightnessDialog != null) { mHandler.postDelayed(mDismissBrightnessDialogRunnable, timeout); } } private void showBugreportDialog() { final AlertDialog.Builder builder = new AlertDialog.Builder(mContext); builder.setPositiveButton(com.android.internal.R.string.report, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (which == DialogInterface.BUTTON_POSITIVE) { // Add a little delay before executing, to give the // dialog a chance to go away before it takes a // screenshot. mHandler.postDelayed(new Runnable() { @Override public void run() { try { ActivityManagerNative.getDefault() .requestBugReport(); } catch (RemoteException e) { } } }, 500); } } }); builder.setMessage(com.android.internal.R.string.bugreport_message); builder.setTitle(com.android.internal.R.string.bugreport_title); builder.setCancelable(true); final Dialog dialog = builder.create(); dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); try { WindowManagerGlobal.getWindowManagerService().dismissKeyguard(); } catch (RemoteException e) { } dialog.show(); } private void updateWifiDisplayStatus() { mWifiDisplayStatus = mDisplayManager.getWifiDisplayStatus(); applyWifiDisplayStatus(); } private void applyWifiDisplayStatus() { mModel.onWifiDisplayStateChanged(mWifiDisplayStatus); } private void applyBluetoothStatus() { mModel.onBluetoothStateChange(mBluetoothState); } void reloadUserInfo() { if (mUserInfoTask != null) { mUserInfoTask.cancel(false); mUserInfoTask = null; } if (mTilesSetUp) { queryForUserInformation(); } } void reloadFavContactInfo() { if (mFavContactInfoTask != null) { mFavContactInfoTask.cancel(false); mFavContactInfoTask = null; } if (mTilesSetUp) { queryForFavContactInformation(); } } private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if (DisplayManager.ACTION_WIFI_DISPLAY_STATUS_CHANGED.equals(action)) { WifiDisplayStatus status = (WifiDisplayStatus) intent.getParcelableExtra( DisplayManager.EXTRA_WIFI_DISPLAY_STATUS); mWifiDisplayStatus = status; applyWifiDisplayStatus(); } else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) { int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR); mBluetoothState.enabled = (state == BluetoothAdapter.STATE_ON); applyBluetoothStatus(); } else if (BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED.equals(action)) { int status = intent.getIntExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE, BluetoothAdapter.STATE_DISCONNECTED); mBluetoothState.connected = (status == BluetoothAdapter.STATE_CONNECTED); applyBluetoothStatus(); } else if (Intent.ACTION_USER_SWITCHED.equals(action)) { reloadUserInfo(); reloadFavContactInfo(); } else if (WifiManager.WIFI_AP_STATE_CHANGED_ACTION.equals(action)) { mHandler.postDelayed(delayedRefresh, 1000); } } }; private final BroadcastReceiver mProfileReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if (ContactsContract.Intents.ACTION_PROFILE_CHANGED.equals(action) || Intent.ACTION_USER_INFO_CHANGED.equals(action)) { try { final int userId = ActivityManagerNative.getDefault().getCurrentUser().id; if (getSendingUserId() == userId) { reloadUserInfo(); reloadFavContactInfo(); } } catch (RemoteException e) { Log.e(TAG, "Couldn't get current user id for profile change", e); } } } }; private void setFastCharge(final boolean on) { Intent fastChargeIntent = new Intent("com.android.settings.ACTION_CHANGE_FCHARGE_STATE"); fastChargeIntent.setPackage("com.android.settings"); fastChargeIntent.putExtra("newState", on); mContext.sendBroadcast(fastChargeIntent); mHandler.postDelayed(new Runnable() { public void run() { mModel.refreshFChargeTile(); } }, 250); } private void changeWifiApState(final boolean desiredState) { if (wifiManager == null) { return; } AsyncTask.execute(new Runnable() { public void run() { int wifiState = wifiManager.getWifiState(); if (desiredState && ((wifiState == WifiManager.WIFI_STATE_ENABLING) || (wifiState == WifiManager.WIFI_STATE_ENABLED))) { wifiManager.setWifiEnabled(false); } wifiManager.setWifiApEnabled(null, desiredState); return; } }); } private void changeWifiState(final boolean desiredState) { if (wifiManager == null) { return; } AsyncTask.execute(new Runnable() { public void run() { int wifiApState = wifiManager.getWifiApState(); if (desiredState && ((wifiApState == WifiManager.WIFI_AP_STATE_ENABLING) || (wifiApState == WifiManager.WIFI_AP_STATE_ENABLED))) { wifiManager.setWifiApEnabled(null, false); } wifiManager.setWifiEnabled(desiredState); return; } }); } public boolean updateUsbState() { String[] mUsbRegexs = connManager.getTetherableUsbRegexs(); String[] tethered = connManager.getTetheredIfaces(); usbTethered = false; for (String s : tethered) { for (String regex : mUsbRegexs) { if (s.matches(regex)) { return true; } else { return false; } } } return false; } final Runnable delayedRefresh = new Runnable () { public void run() { mModel.refreshWifiTetherTile(); mModel.refreshUSBTetherTile(); } }; private void restoreFChargeState() { new AsyncTask<Void, Void, Boolean>() { @Override protected Boolean doInBackground(Void... params) { if(Prefs.getLastFastChargeState(mContext) && !mModel.isFastChargeOn()) { setFastCharge(true); } return null; } }.execute(); } void updateTileTextSize(int colnum) { // adjust Tile Text Size based on column count switch (colnum) { case 5: mTileTextSize = 8; break; case 4: mTileTextSize = 10; break; case 3: default: mTileTextSize = 12; break; } } private void updateSettings() { ContentResolver resolver = mContext.getContentResolver(); userToggles = Settings.System.getString(resolver, Settings.System.QUICK_TOGGLES); int columnCount = Settings.System.getInt(resolver, Settings.System.QUICK_TOGGLES_PER_ROW, mContext.getResources().getInteger(R.integer.quick_settings_num_columns)); ((QuickSettingsContainerView) mContainerView).setColumnCount(columnCount); updateTileTextSize(columnCount); setupQuickSettings(); updateWifiDisplayStatus(); updateResources(); reloadFavContactInfo(); mModel.refreshTorchTile(); } class SettingsObserver extends ContentObserver { SettingsObserver(Handler handler) { super(handler); } void observe() { ContentResolver resolver = mContext.getContentResolver(); resolver.registerContentObserver(Settings.System .getUriFor(Settings.System.QUICK_TOGGLES), false, this); resolver.registerContentObserver(Settings.System .getUriFor(Settings.System.QUICK_TOGGLES_PER_ROW), false, this); resolver.registerContentObserver(Settings.System .getUriFor(Settings.System.QUICK_TOGGLE_FAV_CONTACT), false, this); updateSettings(); } @Override public void onChange(boolean selfChange) { updateSettings(); } } class SoundObserver extends ContentObserver { SoundObserver(Handler handler) { super(handler); } void observe() { ContentResolver resolver = mContext.getContentResolver(); resolver.registerContentObserver(Settings.Global .getUriFor(Settings.Global.MODE_RINGER), false, this); mModel.refreshVibrateTile(); mModel.refreshSilentTile(); mModel.refreshSoundStateTile(); } @Override public void onChange(boolean selfChange) { mModel.refreshVibrateTile(); mModel.refreshSilentTile(); mModel.refreshSoundStateTile(); } } class NetworkModeObserver extends ContentObserver { NetworkModeObserver(Handler handler) { super(handler); } void observe() { ContentResolver resolver = mContext.getContentResolver(); resolver.registerContentObserver(Settings.Global .getUriFor(Settings.Global.PREFERRED_NETWORK_MODE), false, this); mModel.refresh2gTile(); mModel.refreshLTETile(); } @Override public void onChange(boolean selfChange) { mModel.refresh2gTile(); mModel.refreshLTETile(); } } }
false
true
private QuickSettingsTileView getTile(int tile, ViewGroup parent, LayoutInflater inflater) { final Resources r = mContext.getResources(); QuickSettingsTileView quick = null; switch (tile) { case USER_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_user, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mBar.collapseAllPanels(true); final UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE); if (um.getUsers(true).size() > 1) { try { WindowManagerGlobal.getWindowManagerService().lockNow(null); } catch (RemoteException e) { Log.e(TAG, "Couldn't show user switcher", e); } } else { Intent intent = ContactsContract.QuickContact.composeQuickContactsIntent( mContext, v, ContactsContract.Profile.CONTENT_URI, ContactsContract.QuickContact.MODE_LARGE, null); mContext.startActivityAsUser(intent, new UserHandle(UserHandle.USER_CURRENT)); } } }); mModel.addUserTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { UserState us = (UserState) state; ImageView iv = (ImageView) view.findViewById(R.id.user_imageview); TextView tv = (TextView) view.findViewById(R.id.user_textview); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); iv.setImageDrawable(us.avatar); view.setContentDescription(mContext.getString( R.string.accessibility_quick_settings_user, state.label)); } }); break; case CLOCK_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_time, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent("android.intent.action.MAIN"); intent.setComponent(ComponentName.unflattenFromString("com.android.deskclock.AlarmProvider")); intent.addCategory("android.intent.category.LAUNCHER"); startSettingsActivity(intent); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(Intent.ACTION_QUICK_CLOCK); return true; } }); mModel.addTimeTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State alarmState) { TextView tv = (TextView) view.findViewById(R.id.clock_textview); tv.setTextSize(1, mTileTextSize); } }); break; case SIGNAL_TILE: if (mModel.deviceSupportsTelephony()) { // Mobile Network state quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_rssi, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { connManager.setMobileDataEnabled(connManager.getMobileDataEnabled() ? false : true); String strData = connManager.getMobileDataEnabled() ? r.getString(R.string.quick_settings_data_off_label) : r.getString(R.string.quick_settings_data_on_label); Toast.makeText(mContext, strData, Toast.LENGTH_SHORT).show(); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { Intent intent = new Intent(); intent.setComponent(new ComponentName( "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity")); startSettingsActivity(intent); return true; } }); mModel.addRSSITile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { RSSIState rssiState = (RSSIState) state; ImageView iv = (ImageView) view.findViewById(R.id.rssi_image); ImageView iov = (ImageView) view.findViewById(R.id.rssi_overlay_image); TextView tv = (TextView) view.findViewById(R.id.rssi_textview); iv.setImageResource(rssiState.signalIconId); if (rssiState.dataTypeIconId > 0) { iov.setImageResource(rssiState.dataTypeIconId); } else { iov.setImageDrawable(null); } tv.setText(state.label); tv.setTextSize(1, mTileTextSize); view.setContentDescription(mContext.getResources().getString( R.string.accessibility_quick_settings_mobile, rssiState.signalContentDescription, rssiState.dataContentDescription, state.label)); } }); } break; case BRIGHTNESS_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_brightness, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mBar.collapseAllPanels(true); showBrightnessDialog(); } }); mModel.addBrightnessTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.brightness_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); dismissBrightnessDialog(mBrightnessDialogShortTimeout); } }); break; case SETTINGS_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_settings, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_SETTINGS); } }); mModel.addSettingsTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.settings_tileview); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } }); break; case WIFI_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_wifi, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mWifiState = wifiManager.getWifiState(); if (mWifiState == WifiManager.WIFI_STATE_DISABLED || mWifiState == WifiManager.WIFI_STATE_DISABLING) { changeWifiState(true); } else { changeWifiState(false); } mHandler.postDelayed(delayedRefresh, 1000); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_WIFI_SETTINGS); return true; } }); mModel.addWifiTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { WifiState wifiState = (WifiState) state; TextView tv = (TextView) view.findViewById(R.id.wifi_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, wifiState.iconId, 0, 0); tv.setText(wifiState.label); tv.setTextSize(1, mTileTextSize); view.setContentDescription(mContext.getString( R.string.accessibility_quick_settings_wifi, wifiState.signalContentDescription, (wifiState.connected) ? wifiState.label : "")); } }); break; case TWOG_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_twog, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { mDataState = Settings.Global.getInt(mContext.getContentResolver(), Settings.Global.PREFERRED_NETWORK_MODE); } catch (SettingNotFoundException e) { e.printStackTrace(); } if (mDataState == PhoneConstants.NT_MODE_GSM_ONLY) { tm.toggle2G(false); } else { tm.toggle2G(true); } mModel.refresh2gTile(); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_DATA_ROAMING_SETTINGS); return true; } }); mModel.add2gTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.twog_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } }); break; case LTE_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_lte, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { mDataState = Settings.Global.getInt(mContext.getContentResolver(), Settings.Global.PREFERRED_NETWORK_MODE); } catch (SettingNotFoundException e) { e.printStackTrace(); } if (mDataState == PhoneConstants.NT_MODE_LTE_CDMA_EVDO || mDataState == PhoneConstants.NT_MODE_GLOBAL) { tm.toggleLTE(false); } else { tm.toggleLTE(true); } mModel.refreshLTETile(); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS); return true; } }); mModel.addLTETile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.lte_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } }); break; case VIBRATE_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_vibrate, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mAokpTarget.launchAction(mAokpTarget.ACTION_VIB); mModel.refreshVibrateTile(); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_SOUND_SETTINGS); return true; } }); mModel.addVibrateTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.vibrate_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } }); break; case SILENT_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_silent, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mAokpTarget.launchAction(mAokpTarget.ACTION_SILENT); mModel.refreshSilentTile(); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_SOUND_SETTINGS); return true; } }); mModel.addSilentTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.silent_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } }); break; case SOUND_STATE_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_sound_state, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mAokpTarget.launchAction(mAokpTarget.ACTION_SILENT_VIB); mModel.refreshSoundStateTile(); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_SOUND_SETTINGS); return true; } }); mModel.addSoundStateTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.sound_state_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } }); break; case TORCH_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_torch, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mAokpTarget.launchAction(mAokpTarget.ACTION_TORCH); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { // maybe something here? return true; } }); mModel.addTorchTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.torch_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } }); break; case FCHARGE_TILE: if((mFastChargePath == null || mFastChargePath.isEmpty()) || !new File(mFastChargePath).exists()) { // config not set or config set and kernel doesn't support it? break; } quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_fcharge, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setFastCharge(!Prefs.getLastFastChargeState(mContext)); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { // What do we put here? return true; } }); mModel.addFChargeTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.fcharge_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } }); restoreFChargeState(); break; case WIFI_TETHER_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_wifi_tether, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mWifiApState = wifiManager.getWifiApState(); if (mWifiApState == WifiManager.WIFI_AP_STATE_DISABLED || mWifiApState == WifiManager.WIFI_AP_STATE_DISABLING) { changeWifiApState(true); } else { changeWifiApState(false); } mHandler.postDelayed(delayedRefresh, 1000); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS); return true; } }); mModel.addWifiTetherTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.wifi_tether_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } }); break; case USB_TETHER_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_usb_tether, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean enabled = updateUsbState() ? false : true; if (connManager.setUsbTethering(enabled) == ConnectivityManager.TETHER_ERROR_NO_ERROR) { mHandler.postDelayed(delayedRefresh, 1000); } } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS); return true; } }); mModel.addUSBTetherTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.usb_tether_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } }); break; case SYNC_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_sync, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean enabled = ContentResolver.getMasterSyncAutomatically(); ContentResolver.setMasterSyncAutomatically(enabled ? false : true); mModel.refreshSyncTile(); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_SYNC_SETTINGS); return true; } }); mModel.addSyncTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.sync_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } }); break; case NFC_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_nfc, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean enabled = false; if (mNfcAdapter == null) { mNfcAdapter = NfcAdapter.getDefaultAdapter(mContext); } try { enabled = mNfcAdapter.isEnabled(); if (enabled) { mNfcAdapter.disable(); } else { mNfcAdapter.enable(); } } catch (NullPointerException ex) { // we'll ignore this click } } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS); return true; } }); mModel.addNFCTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.nfc_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } }); break; case ROTATE_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_rotation_lock, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean locked = RotationPolicy.isRotationLocked(mContext); RotationPolicy.setRotationLock(mContext, !locked); } }); mModel.addRotationLockTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.rotation_lock_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } }); break; case BATTERY_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_battery, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startSettingsActivity(Intent.ACTION_POWER_USAGE_SUMMARY); } }); mModel.addBatteryTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { QuickSettingsModel.BatteryState batteryState = (QuickSettingsModel.BatteryState) state; TextView tv = (TextView) view.findViewById(R.id.battery_textview); ImageView iv = (ImageView) view.findViewById(R.id.battery_image); Drawable d = batteryState.pluggedIn ? mChargingBatteryLevels : mBatteryLevels; String t; if (batteryState.batteryLevel == 100) { t = mContext.getString(R.string.quick_settings_battery_charged_label); } else { t = batteryState.pluggedIn ? mContext.getString(R.string.quick_settings_battery_charging_label, batteryState.batteryLevel) : mContext.getString(R.string.status_bar_settings_battery_meter_format, batteryState.batteryLevel); } iv.setImageDrawable(d); iv.setImageLevel(batteryState.batteryLevel); tv.setText(t); tv.setTextSize(1, mTileTextSize); view.setContentDescription( mContext.getString(R.string.accessibility_quick_settings_battery, t)); } }); break; case AIRPLANE_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_airplane, inflater); mModel.addAirplaneModeTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.airplane_mode_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); String airplaneState = mContext.getString( (state.enabled) ? R.string.accessibility_desc_on : R.string.accessibility_desc_off); view.setContentDescription( mContext.getString(R.string.accessibility_quick_settings_airplane, airplaneState)); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } }); break; case BLUETOOTH_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_bluetooth, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); if (adapter.isEnabled()) { adapter.disable(); } else { adapter.enable(); } } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS); return true; } }); mModel.addBluetoothTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { BluetoothState bluetoothState = (BluetoothState) state; TextView tv = (TextView) view.findViewById(R.id.bluetooth_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); Resources r = mContext.getResources(); String label = state.label; /* * //TODO: Show connected bluetooth device label * Set<BluetoothDevice> btDevices = * mBluetoothController.getBondedBluetoothDevices(); if * (btDevices.size() == 1) { // Show the name of the * bluetooth device you are connected to label = * btDevices.iterator().next().getName(); } else if * (btDevices.size() > 1) { // Show a generic label * about the number of bluetooth devices label = * r.getString(R.string * .quick_settings_bluetooth_multiple_devices_label, * btDevices.size()); } */ view.setContentDescription(mContext.getString( R.string.accessibility_quick_settings_bluetooth, bluetoothState.stateContentDescription)); tv.setText(label); tv.setTextSize(1, mTileTextSize); } }); break; case GPS_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_location, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean gpsEnabled = Settings.Secure.isLocationProviderEnabled( mContext.getContentResolver(), LocationManager.GPS_PROVIDER); Settings.Secure.setLocationProviderEnabled(mContext.getContentResolver(), LocationManager.GPS_PROVIDER, gpsEnabled ? false : true); TextView tv = (TextView) v.findViewById(R.id.location_textview); tv.setText(gpsEnabled ? R.string.quick_settings_gps_off_label : R.string.quick_settings_gps_on_label); tv.setCompoundDrawablesWithIntrinsicBounds(0, gpsEnabled ? R.drawable.ic_qs_gps_off : R.drawable.ic_qs_gps_on, 0, 0); tv.setTextSize(1, mTileTextSize); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); return true; } }); mModel.addLocationTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { boolean gpsEnabled = Settings.Secure.isLocationProviderEnabled( mContext.getContentResolver(), LocationManager.GPS_PROVIDER); TextView tv = (TextView) view.findViewById(R.id.location_textview); tv.setText(gpsEnabled ? R.string.quick_settings_gps_on_label : R.string.quick_settings_gps_off_label); if (state.iconId == 0) { tv.setCompoundDrawablesWithIntrinsicBounds(0, gpsEnabled ? R.drawable.ic_qs_gps_on : R.drawable.ic_qs_gps_off, 0, 0); } else { tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); } tv.setTextSize(1, mTileTextSize); } }); break; case IME_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_ime, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { mBar.collapseAllPanels(true); Intent intent = new Intent(Settings.ACTION_SHOW_INPUT_METHOD_PICKER); PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0); pendingIntent.send(); } catch (Exception e) { } } }); mModel.addImeTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.ime_textview); if (state.label != null) { tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } } }); break; case FAV_CONTACT_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_user, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String lookupKey = Settings.System.getString(mContext.getContentResolver(), Settings.System.QUICK_TOGGLE_FAV_CONTACT); if (lookupKey != null && lookupKey.length() > 0) { mBar.collapseAllPanels(true); Uri lookupUri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey); Uri res = ContactsContract.Contacts.lookupContact(mContext.getContentResolver(), lookupUri); Intent intent = ContactsContract.QuickContact.composeQuickContactsIntent( mContext, v, res, ContactsContract.QuickContact.MODE_LARGE, null); mContext.startActivityAsUser(intent, new UserHandle(UserHandle.USER_CURRENT)); } } }); mModel.addFavContactTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { UserState us = (UserState) state; ImageView iv = (ImageView) view.findViewById(R.id.user_imageview); TextView tv = (TextView) view.findViewById(R.id.user_textview); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); iv.setImageDrawable(us.avatar); view.setContentDescription(mContext.getString( R.string.accessibility_quick_settings_user, state.label)); } }); break; } return quick; }
private QuickSettingsTileView getTile(int tile, ViewGroup parent, LayoutInflater inflater) { final Resources r = mContext.getResources(); QuickSettingsTileView quick = null; switch (tile) { case USER_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_user, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mBar.collapseAllPanels(true); final UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE); if (um.getUsers(true).size() > 1) { try { WindowManagerGlobal.getWindowManagerService().lockNow(null); } catch (RemoteException e) { Log.e(TAG, "Couldn't show user switcher", e); } } else { Intent intent = ContactsContract.QuickContact.composeQuickContactsIntent( mContext, v, ContactsContract.Profile.CONTENT_URI, ContactsContract.QuickContact.MODE_LARGE, null); mContext.startActivityAsUser(intent, new UserHandle(UserHandle.USER_CURRENT)); } } }); mModel.addUserTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { UserState us = (UserState) state; ImageView iv = (ImageView) view.findViewById(R.id.user_imageview); TextView tv = (TextView) view.findViewById(R.id.user_textview); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); iv.setImageDrawable(us.avatar); view.setContentDescription(mContext.getString( R.string.accessibility_quick_settings_user, state.label)); } }); break; case CLOCK_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_time, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent("android.intent.action.MAIN"); intent.setComponent(ComponentName.unflattenFromString("com.android.deskclock.AlarmProvider")); intent.addCategory("android.intent.category.LAUNCHER"); startSettingsActivity(intent); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(Intent.ACTION_QUICK_CLOCK); return true; } }); mModel.addTimeTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State alarmState) { TextView tv = (TextView) view.findViewById(R.id.clock_textview); tv.setTextSize(1, mTileTextSize); } }); break; case SIGNAL_TILE: if (mModel.deviceSupportsTelephony()) { // Mobile Network state quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_rssi, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { connManager.setMobileDataEnabled(connManager.getMobileDataEnabled() ? false : true); String strData = connManager.getMobileDataEnabled() ? r.getString(R.string.quick_settings_data_off_label) : r.getString(R.string.quick_settings_data_on_label); Toast.makeText(mContext, strData, Toast.LENGTH_SHORT).show(); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { Intent intent = new Intent(); intent.setComponent(new ComponentName( "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity")); startSettingsActivity(intent); return true; } }); mModel.addRSSITile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { RSSIState rssiState = (RSSIState) state; ImageView iv = (ImageView) view.findViewById(R.id.rssi_image); ImageView iov = (ImageView) view.findViewById(R.id.rssi_overlay_image); TextView tv = (TextView) view.findViewById(R.id.rssi_textview); iv.setImageResource(rssiState.signalIconId); if (rssiState.dataTypeIconId > 0) { iov.setImageResource(rssiState.dataTypeIconId); } else { iov.setImageDrawable(null); } tv.setText(state.label); tv.setTextSize(1, mTileTextSize); view.setContentDescription(mContext.getResources().getString( R.string.accessibility_quick_settings_mobile, rssiState.signalContentDescription, rssiState.dataContentDescription, state.label)); } }); } break; case BRIGHTNESS_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_brightness, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mBar.collapseAllPanels(true); showBrightnessDialog(); } }); mModel.addBrightnessTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.brightness_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); dismissBrightnessDialog(mBrightnessDialogShortTimeout); } }); break; case SETTINGS_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_settings, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_SETTINGS); } }); mModel.addSettingsTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.settings_tileview); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } }); break; case WIFI_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_wifi, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mWifiState = wifiManager.getWifiState(); if (mWifiState == WifiManager.WIFI_STATE_DISABLED || mWifiState == WifiManager.WIFI_STATE_DISABLING) { changeWifiState(true); } else { changeWifiState(false); } mHandler.postDelayed(delayedRefresh, 1000); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_WIFI_SETTINGS); return true; } }); mModel.addWifiTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { WifiState wifiState = (WifiState) state; TextView tv = (TextView) view.findViewById(R.id.wifi_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, wifiState.iconId, 0, 0); tv.setText(wifiState.label); tv.setTextSize(1, mTileTextSize); view.setContentDescription(mContext.getString( R.string.accessibility_quick_settings_wifi, wifiState.signalContentDescription, (wifiState.connected) ? wifiState.label : "")); } }); break; case TWOG_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_twog, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { mDataState = Settings.Global.getInt(mContext.getContentResolver(), Settings.Global.PREFERRED_NETWORK_MODE); } catch (SettingNotFoundException e) { e.printStackTrace(); } if (mDataState == PhoneConstants.NT_MODE_GSM_ONLY) { tm.toggle2G(false); } else { tm.toggle2G(true); } mModel.refresh2gTile(); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_DATA_ROAMING_SETTINGS); return true; } }); mModel.add2gTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.twog_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } }); break; case LTE_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_lte, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { mDataState = Settings.Global.getInt(mContext.getContentResolver(), Settings.Global.PREFERRED_NETWORK_MODE); } catch (SettingNotFoundException e) { e.printStackTrace(); } if (mDataState == PhoneConstants.NT_MODE_LTE_CDMA_EVDO || mDataState == PhoneConstants.NT_MODE_GLOBAL) { tm.toggleLTE(false); } else { tm.toggleLTE(true); } mModel.refreshLTETile(); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS); return true; } }); mModel.addLTETile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.lte_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } }); break; case VIBRATE_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_vibrate, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mAokpTarget.launchAction(mAokpTarget.ACTION_VIB); mModel.refreshVibrateTile(); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_SOUND_SETTINGS); return true; } }); mModel.addVibrateTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.vibrate_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } }); break; case SILENT_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_silent, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mAokpTarget.launchAction(mAokpTarget.ACTION_SILENT); mModel.refreshSilentTile(); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_SOUND_SETTINGS); return true; } }); mModel.addSilentTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.silent_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } }); break; case SOUND_STATE_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_sound_state, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mAokpTarget.launchAction(mAokpTarget.ACTION_SILENT_VIB); mModel.refreshSoundStateTile(); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_SOUND_SETTINGS); return true; } }); mModel.addSoundStateTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.sound_state_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } }); break; case TORCH_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_torch, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mAokpTarget.launchAction(mAokpTarget.ACTION_TORCH); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { // maybe something here? return true; } }); mModel.addTorchTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.torch_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } }); break; case FCHARGE_TILE: if((mFastChargePath == null || mFastChargePath.isEmpty()) || !new File(mFastChargePath).exists()) { // config not set or config set and kernel doesn't support it? break; } quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_fcharge, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setFastCharge(!Prefs.getLastFastChargeState(mContext)); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { // What do we put here? return true; } }); mModel.addFChargeTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.fcharge_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } }); restoreFChargeState(); break; case WIFI_TETHER_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_wifi_tether, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mWifiApState = wifiManager.getWifiApState(); if (mWifiApState == WifiManager.WIFI_AP_STATE_DISABLED || mWifiApState == WifiManager.WIFI_AP_STATE_DISABLING) { changeWifiApState(true); } else { changeWifiApState(false); } mHandler.postDelayed(delayedRefresh, 1000); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { Intent intent = new Intent(); intent.setComponent(new ComponentName("com.android.settings", "com.android.settings.Settings$TetherSettingsActivity")); startSettingsActivity(intent); return true; } }); mModel.addWifiTetherTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.wifi_tether_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } }); break; case USB_TETHER_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_usb_tether, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean enabled = updateUsbState() ? false : true; if (connManager.setUsbTethering(enabled) == ConnectivityManager.TETHER_ERROR_NO_ERROR) { mHandler.postDelayed(delayedRefresh, 1000); } } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { Intent intent = new Intent(); intent.setComponent(new ComponentName("com.android.settings", "com.android.settings.Settings$TetherSettingsActivity")); startSettingsActivity(intent); return true; } }); mModel.addUSBTetherTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.usb_tether_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } }); break; case SYNC_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_sync, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean enabled = ContentResolver.getMasterSyncAutomatically(); ContentResolver.setMasterSyncAutomatically(enabled ? false : true); mModel.refreshSyncTile(); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_SYNC_SETTINGS); return true; } }); mModel.addSyncTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.sync_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } }); break; case NFC_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_nfc, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean enabled = false; if (mNfcAdapter == null) { mNfcAdapter = NfcAdapter.getDefaultAdapter(mContext); } try { enabled = mNfcAdapter.isEnabled(); if (enabled) { mNfcAdapter.disable(); } else { mNfcAdapter.enable(); } } catch (NullPointerException ex) { // we'll ignore this click } } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS); return true; } }); mModel.addNFCTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.nfc_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } }); break; case ROTATE_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_rotation_lock, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean locked = RotationPolicy.isRotationLocked(mContext); RotationPolicy.setRotationLock(mContext, !locked); } }); mModel.addRotationLockTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.rotation_lock_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } }); break; case BATTERY_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_battery, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startSettingsActivity(Intent.ACTION_POWER_USAGE_SUMMARY); } }); mModel.addBatteryTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { QuickSettingsModel.BatteryState batteryState = (QuickSettingsModel.BatteryState) state; TextView tv = (TextView) view.findViewById(R.id.battery_textview); ImageView iv = (ImageView) view.findViewById(R.id.battery_image); Drawable d = batteryState.pluggedIn ? mChargingBatteryLevels : mBatteryLevels; String t; if (batteryState.batteryLevel == 100) { t = mContext.getString(R.string.quick_settings_battery_charged_label); } else { t = batteryState.pluggedIn ? mContext.getString(R.string.quick_settings_battery_charging_label, batteryState.batteryLevel) : mContext.getString(R.string.status_bar_settings_battery_meter_format, batteryState.batteryLevel); } iv.setImageDrawable(d); iv.setImageLevel(batteryState.batteryLevel); tv.setText(t); tv.setTextSize(1, mTileTextSize); view.setContentDescription( mContext.getString(R.string.accessibility_quick_settings_battery, t)); } }); break; case AIRPLANE_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_airplane, inflater); mModel.addAirplaneModeTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.airplane_mode_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); String airplaneState = mContext.getString( (state.enabled) ? R.string.accessibility_desc_on : R.string.accessibility_desc_off); view.setContentDescription( mContext.getString(R.string.accessibility_quick_settings_airplane, airplaneState)); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } }); break; case BLUETOOTH_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_bluetooth, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); if (adapter.isEnabled()) { adapter.disable(); } else { adapter.enable(); } } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS); return true; } }); mModel.addBluetoothTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { BluetoothState bluetoothState = (BluetoothState) state; TextView tv = (TextView) view.findViewById(R.id.bluetooth_textview); tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); Resources r = mContext.getResources(); String label = state.label; /* * //TODO: Show connected bluetooth device label * Set<BluetoothDevice> btDevices = * mBluetoothController.getBondedBluetoothDevices(); if * (btDevices.size() == 1) { // Show the name of the * bluetooth device you are connected to label = * btDevices.iterator().next().getName(); } else if * (btDevices.size() > 1) { // Show a generic label * about the number of bluetooth devices label = * r.getString(R.string * .quick_settings_bluetooth_multiple_devices_label, * btDevices.size()); } */ view.setContentDescription(mContext.getString( R.string.accessibility_quick_settings_bluetooth, bluetoothState.stateContentDescription)); tv.setText(label); tv.setTextSize(1, mTileTextSize); } }); break; case GPS_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_location, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean gpsEnabled = Settings.Secure.isLocationProviderEnabled( mContext.getContentResolver(), LocationManager.GPS_PROVIDER); Settings.Secure.setLocationProviderEnabled(mContext.getContentResolver(), LocationManager.GPS_PROVIDER, gpsEnabled ? false : true); TextView tv = (TextView) v.findViewById(R.id.location_textview); tv.setText(gpsEnabled ? R.string.quick_settings_gps_off_label : R.string.quick_settings_gps_on_label); tv.setCompoundDrawablesWithIntrinsicBounds(0, gpsEnabled ? R.drawable.ic_qs_gps_off : R.drawable.ic_qs_gps_on, 0, 0); tv.setTextSize(1, mTileTextSize); } }); quick.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { startSettingsActivity(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); return true; } }); mModel.addLocationTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { boolean gpsEnabled = Settings.Secure.isLocationProviderEnabled( mContext.getContentResolver(), LocationManager.GPS_PROVIDER); TextView tv = (TextView) view.findViewById(R.id.location_textview); tv.setText(gpsEnabled ? R.string.quick_settings_gps_on_label : R.string.quick_settings_gps_off_label); if (state.iconId == 0) { tv.setCompoundDrawablesWithIntrinsicBounds(0, gpsEnabled ? R.drawable.ic_qs_gps_on : R.drawable.ic_qs_gps_off, 0, 0); } else { tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0); } tv.setTextSize(1, mTileTextSize); } }); break; case IME_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_ime, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { mBar.collapseAllPanels(true); Intent intent = new Intent(Settings.ACTION_SHOW_INPUT_METHOD_PICKER); PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0); pendingIntent.send(); } catch (Exception e) { } } }); mModel.addImeTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { TextView tv = (TextView) view.findViewById(R.id.ime_textview); if (state.label != null) { tv.setText(state.label); tv.setTextSize(1, mTileTextSize); } } }); break; case FAV_CONTACT_TILE: quick = (QuickSettingsTileView) inflater.inflate(R.layout.quick_settings_tile, parent, false); quick.setContent(R.layout.quick_settings_tile_user, inflater); quick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String lookupKey = Settings.System.getString(mContext.getContentResolver(), Settings.System.QUICK_TOGGLE_FAV_CONTACT); if (lookupKey != null && lookupKey.length() > 0) { mBar.collapseAllPanels(true); Uri lookupUri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey); Uri res = ContactsContract.Contacts.lookupContact(mContext.getContentResolver(), lookupUri); Intent intent = ContactsContract.QuickContact.composeQuickContactsIntent( mContext, v, res, ContactsContract.QuickContact.MODE_LARGE, null); mContext.startActivityAsUser(intent, new UserHandle(UserHandle.USER_CURRENT)); } } }); mModel.addFavContactTile(quick, new QuickSettingsModel.RefreshCallback() { @Override public void refreshView(QuickSettingsTileView view, State state) { UserState us = (UserState) state; ImageView iv = (ImageView) view.findViewById(R.id.user_imageview); TextView tv = (TextView) view.findViewById(R.id.user_textview); tv.setText(state.label); tv.setTextSize(1, mTileTextSize); iv.setImageDrawable(us.avatar); view.setContentDescription(mContext.getString( R.string.accessibility_quick_settings_user, state.label)); } }); break; } return quick; }
diff --git a/src/cs5625/deferred/scenegraph/Mesh.java b/src/cs5625/deferred/scenegraph/Mesh.java index d045212..3a0130b 100644 --- a/src/cs5625/deferred/scenegraph/Mesh.java +++ b/src/cs5625/deferred/scenegraph/Mesh.java @@ -1,428 +1,434 @@ package cs5625.deferred.scenegraph; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.util.HashMap; import javax.media.opengl.GL2; import javax.vecmath.GMatrix; import javax.vecmath.Matrix3d; import javax.vecmath.GVector; import javax.vecmath.Vector3f; import com.jogamp.common.nio.Buffers; import cs5625.deferred.materials.BlinnPhongMaterial; import cs5625.deferred.materials.Material; import cs5625.deferred.misc.OpenGLResourceObject; /** * Mesh.java * * The Mesh abstract class represents a mesh of n-gons, where n is specified by the subclass. * * Written for Cornell CS 5625 (Interactive Computer Graphics). * Copyright (c) 2012, Computer Science Department, Cornell University. * * @author Asher Dunn (ad488) * @date 2012-04-06 */ public abstract class Mesh implements OpenGLResourceObject { protected static float EPS = 1e-7f; /* Material and name of this mesh. */ private Material mMaterial = new BlinnPhongMaterial(); private String mName = ""; /* Buffers to hold vertex and polygon index data. Buffer formats are * described in the comments for the getter and setter methods, * farther down the file. */ protected FloatBuffer mVertexData, mNormalData, mTexCoordData; protected IntBuffer mPolygonData, mEdgeData; /** * Map of generic vertex attribute name -> generic vertex attribute buffer. The number of elements in * each buffer must match the number of vertices; each buffer's dimensionality (float, vec2, vec3, vec4) * will be inferred based on its size. */ public HashMap<String, FloatBuffer> vertexAttribData = new HashMap<String, FloatBuffer>(); /** * Implemented by subclasses to specify how many vertices per polygon this type of mesh has. */ public abstract int getVerticesPerPolygon(); /** * Implemented by subclasses to calculate surface tangent vectors based on the vertices, * normals, and texture coordinates of this mesh. * * The output is a 4-vector for each vertex, storing the handedness in the w component. Bitangents * can be computed from normals and tangents as `cross(normal, tangent.xyz) * tangent.w`. */ public abstract FloatBuffer calculateTangentVectors(); /** * Computes the tangent and bitangent vectors of triangle with vertex indices (i1, i2, i3). * using the idea described in http://www.terathon.com/code/tangent.html * * The computed tangent vectors should be accumulated in the array tan1[], and the * computed bitangent vectors should be accumulated in the array tan2[]. */ protected void computeAndAccumulateTangentVectors(int i1, int i2, int i3, float tan1[], float[] tan2) { /* Get vertex coordinates of this triangle. */ Vector3f p0 = new Vector3f(mVertexData.get(3 * i1 + 0), mVertexData.get(3 * i1 + 1), mVertexData.get(3 * i1 + 2)); Vector3f p1 = new Vector3f(mVertexData.get(3 * i2 + 0), mVertexData.get(3 * i2 + 1), mVertexData.get(3 * i2 + 2)); Vector3f p2 = new Vector3f(mVertexData.get(3 * i3 + 0), mVertexData.get(3 * i3 + 1), mVertexData.get(3 * i3 + 2)); /* Get texture coordinates of this triangle. */ float u1 = mTexCoordData.get(2 * i1 + 0); float v1 = mTexCoordData.get(2 * i1 + 1); float u2 = mTexCoordData.get(2 * i2 + 0); float v2 = mTexCoordData.get(2 * i2 + 1); float u3 = mTexCoordData.get(2 * i3 + 0); float v3 = mTexCoordData.get(2 * i3 + 1); /* Get positions of vertices relative to the first vertex. */ Vector3f q1 = new Vector3f(); Vector3f q2 = new Vector3f(); q1.sub(p1, p0); q2.sub(p2, p0); /* TODO PA1: Construct the Q matrix */ GMatrix matQ = new GMatrix(2, 3); double[] temp1 = {q1.x, q1.y, q1.z}; double[] temp2 = {q2.x, q2.y, q2.z}; matQ.setRow(0, temp1); matQ.setRow(1, temp2); /* Get texture coordinates relative to the first vertex. */ float s1 = u2 - u1; float s2 = u3 - u1; float t1 = v2 - v1; float t2 = v3 - v1; /* This can happen because of (1) missing texture * (2) broken texture coordinates, so we skip it. */ if (Math.abs(s1 * t2 - s2 * t1) < EPS) { return; } /* TODO PA1: Construct the inverse (s,t) matrix, and compute * tangent and bitangent vectors as explained on Lengyel's site. */ GVector tangent = new GVector(3); GVector bi_tangent = new GVector(3); GMatrix matST = new GMatrix(2,2); double[] temp3 = {s1, t1}; double[] temp4 = {s2, t2}; matST.setRow(0, temp3); matST.setRow(1, temp4); matST.invert(); + //System.out.println(matST.getNumCol()); + //System.out.println(matST.getNumRow()); + //System.out.println(matQ.getNumCol()); + //System.out.println(matQ.getNumRow()); - matST.mul(matQ); - matST.getRow(0, tangent); - matST.getRow(1, bi_tangent); + GMatrix matTB = new GMatrix(2,3); + matTB.mul(matST, matQ); + //matST.mulTransposeRight(matST, matQ); + matTB.getRow(0, tangent); + matTB.getRow(1, bi_tangent); /* Accumulate into temporary arrays. */ tan1[3 * i1 + 0] += tangent.getElement(0); tan1[3 * i1 + 1] += tangent.getElement(1); tan1[3 * i1 + 2] += tangent.getElement(2); tan1[3 * i2 + 0] += tangent.getElement(0); tan1[3 * i2 + 1] += tangent.getElement(1); tan1[3 * i2 + 2] += tangent.getElement(2); tan1[3 * i3 + 0] += tangent.getElement(0); tan1[3 * i3 + 1] += tangent.getElement(1); tan1[3 * i3 + 2] += tangent.getElement(2); tan2[3 * i1 + 0] += bi_tangent.getElement(0); tan2[3 * i1 + 1] += bi_tangent.getElement(1); tan2[3 * i1 + 2] += bi_tangent.getElement(2); tan2[3 * i2 + 0] += bi_tangent.getElement(0); tan2[3 * i2 + 1] += bi_tangent.getElement(1); tan2[3 * i2 + 2] += bi_tangent.getElement(2); tan2[3 * i3 + 0] += bi_tangent.getElement(0); tan2[3 * i3 + 1] += bi_tangent.getElement(1); tan2[3 * i3 + 2] += bi_tangent.getElement(2); } /** * Averages and normalizes all tangent vectors, previously accumulated by computeAndAccumulateTangentVectors() * for every triangle. The input arrays tan1 and tan2 should be the same arrays, passed to the above function. * * The output is a 4-vector for each vertex, storing the handedness in the w component. Bitangents * can be computed from normals and tangents as `cross(normal, tangent.xyz) * tangent.w`. */ protected FloatBuffer averageAndNormalizeAllTangentVectors(float tan1[], float[] tan2) { /* Allocate result buffer and loop over vertices. */ FloatBuffer result = Buffers.newDirectFloatBuffer(4 * getVertexCount()); for (int vIndex = 0; vIndex < getVertexCount(); ++vIndex) { /* Get vertex normal. */ Vector3f normal = new Vector3f(mNormalData.get(3 * vIndex + 0), mNormalData.get(3 * vIndex + 1), mNormalData.get(3 * vIndex + 2)); normal.normalize(); /* Get tentative tangent and bitangent vectors at this vertex. */ Vector3f tangent = new Vector3f(tan1[3 * vIndex + 0], tan1[3 * vIndex + 1], tan1[3 * vIndex + 2]); Vector3f bitangent = new Vector3f(tan2[3 * vIndex + 0], tan2[3 * vIndex + 1], tan2[3 * vIndex + 2]); /* If the tangent is the zero vector, then there were no valid texture coordinates, * so we generate a tangent space starting from an arbitrary vector: e.g. (1, 0, 0) */ if (tangent.length() < EPS) { /* This computes 'n cross (1, 0, 0)' */ tangent = new Vector3f(0, normal.z, -normal.y); /* If this coincides with the normal, pick (0, 1, 0) */ if (tangent.length() < EPS) { /* This computes 'n cross (0, 1, 0)' */ tangent = new Vector3f(-normal.z, 0, normal.x); } /* Make sure this is all zeros as well */ bitangent = new Vector3f(0, 0, 0); } tangent.normalize(); bitangent.normalize(); /* TODO PA1: Orthogonalize and normalize (aka. create orthonormal basis), based on * the current normal and tangent vectors, as explained on Lengyel's site. */ Vector3f tangent_orth = new Vector3f(); Vector3f temp = new Vector3f(); temp.set(normal); double dot = temp.dot(tangent); temp.scale((float) dot); tangent_orth.sub(tangent, temp); Vector3f bitangent_orth = new Vector3f(); Vector3f temp2 = new Vector3f(); temp2.set(tangent_orth); double dot2 = temp2.dot(bitangent); temp2.scale((float) dot2); temp2.scale(1 / temp2.lengthSquared()); Vector3f temp3 = new Vector3f(); temp3.set(normal); double dot3 = temp3.dot(bitangent); temp3.scale((float) dot3); Vector3f temp4 = new Vector3f(); temp4.sub(temp3, temp2); bitangent_orth.sub(bitangent, temp3); Matrix3d mat = new Matrix3d((double)tangent_orth.x, (double)tangent_orth.y, (double)tangent_orth.z, (double)bitangent_orth.x, (double)bitangent_orth.y, (double)bitangent_orth.z, (double)normal.x, (double)normal.y, (double)normal.z); double determinant = mat.determinant(); tangent_orth.normalize(); bitangent_orth.normalize(); /* TODO PA1: Compute handedness of bitangent, as explained on Lengyel's site. */ float handedness = 1.0f; handedness = (float) (determinant / Math.abs(determinant)); /* Store the normalized result in the first 3 components, and the handedness in the last one */ result.put(4 * vIndex + 0, tangent_orth.x); result.put(4 * vIndex + 1, tangent_orth.y); result.put(4 * vIndex + 2, tangent_orth.z); result.put(4 * vIndex + 3, handedness); } return result; } /** * Creates a shallow copy of the given mesh (it will share references to all member data). * This allows us to do useful things like create many instances of some object with * different names and materials but only one set of float buffers for all instances. */ public abstract Mesh clone(); /** * Returns the name of this mesh, which can be specified by a model file or set in code. * Meshes can be retrieved by name out of a `Geometry` object. */ public String getName() { return mName; } /** * Sets the name of this mesh. */ public void setName(String name) { mName = name; } /** * Returns the material used to render this mesh. */ public Material getMaterial() { return mMaterial; } /** * Sets the material used to render this mesh. Must not be null. */ public void setMaterial(Material mat) { mMaterial = mat; } /** * Returns the number of vertices in this mesh. * * This is computed from the size of the vertex data buffer. */ public int getVertexCount() { if (mVertexData == null) { return 0; } else { return mVertexData.capacity() / 3; } } /** * Returns vertex data buffer. Format is 3 floats per vertex, tightly * packed: {x1, y1, z1, x2, y2, z2, ...}. */ public FloatBuffer getVertexData() { return mVertexData; } /** * Sets the vertex data buffer. Format must be 3 floats per vertex, tightly * packed: {x1, y1, z1, x2, y2, z2, ...}. */ public void setVertexData(FloatBuffer vertices) { mVertexData = vertices; } /** * Returns normal data buffer. Format is 3 floats per normal, tightly * packed: {x1, y1, z1, x2, y2, z2, ...}. */ public FloatBuffer getNormalData() { return mNormalData; } /** * Sets normal data buffer. Format must be 3 floats per normal, tightly * packed: {x1, y1, z1, x2, y2, z2, ...}. */ public void setNormalData(FloatBuffer normals) { mNormalData = normals; } /** * Returns texture coordinate data buffer. Format is 2 floats per texcoord, * tightly packed: {u1, v1, u2, v2, ...}. */ public FloatBuffer getTexCoordData() { return mTexCoordData; } /** * Sets texture coordinate data buffer. Format is 2 floats per texcoord, * tightly packed: {u1, v1, u2, v2, ...}. */ public void setTexCoordData(FloatBuffer texcoords) { mTexCoordData = texcoords; } /** * Returns the number of polygons in this mesh. * * This is calculated based on the size of the polygon index buffer and the size of * polygons from the subclass. */ public int getPolygonCount() { if (mPolygonData == null) { return 0; } else { return mPolygonData.capacity() / getVerticesPerPolygon(); } } /** * Returns polygon index buffer. Format is `getVerticesPerPolygon()` ints per polygon * specifying the vertex indices of that polygon in counterclockwise winding order. * For example, for triangles: {i11, i12, i13, i21, i22, i23, ...}. */ public IntBuffer getPolygonData() { return mPolygonData; } /** * Sets the polygon index buffer. Format Must be `getVerticesPerPolygon()` ints per polygon * specifying the vertices of that polygon. */ public void setPolygonData(IntBuffer polys) { mPolygonData = polys; } /** * Returns the edge index buffer. Format is the same as the polygon buffer (with only * 2 indices per edge, of course). The edge buffer is not automatically initialized to all * edges in the mesh; it might contain a subset of edges, depending on the application. */ public IntBuffer getEdgeData() { return mEdgeData; } /** * Sets edge index buffer. Format is the same as the polygon index buffer (with * only 2 indices per edge, of course). */ public void setEdgeData(IntBuffer edges) { mEdgeData = edges; } /** * Releases OpenGL resources owned by this mesh or its material. */ public void releaseGPUResources(GL2 gl) { mMaterial.releaseGPUResources(gl); } }
false
true
protected void computeAndAccumulateTangentVectors(int i1, int i2, int i3, float tan1[], float[] tan2) { /* Get vertex coordinates of this triangle. */ Vector3f p0 = new Vector3f(mVertexData.get(3 * i1 + 0), mVertexData.get(3 * i1 + 1), mVertexData.get(3 * i1 + 2)); Vector3f p1 = new Vector3f(mVertexData.get(3 * i2 + 0), mVertexData.get(3 * i2 + 1), mVertexData.get(3 * i2 + 2)); Vector3f p2 = new Vector3f(mVertexData.get(3 * i3 + 0), mVertexData.get(3 * i3 + 1), mVertexData.get(3 * i3 + 2)); /* Get texture coordinates of this triangle. */ float u1 = mTexCoordData.get(2 * i1 + 0); float v1 = mTexCoordData.get(2 * i1 + 1); float u2 = mTexCoordData.get(2 * i2 + 0); float v2 = mTexCoordData.get(2 * i2 + 1); float u3 = mTexCoordData.get(2 * i3 + 0); float v3 = mTexCoordData.get(2 * i3 + 1); /* Get positions of vertices relative to the first vertex. */ Vector3f q1 = new Vector3f(); Vector3f q2 = new Vector3f(); q1.sub(p1, p0); q2.sub(p2, p0); /* TODO PA1: Construct the Q matrix */ GMatrix matQ = new GMatrix(2, 3); double[] temp1 = {q1.x, q1.y, q1.z}; double[] temp2 = {q2.x, q2.y, q2.z}; matQ.setRow(0, temp1); matQ.setRow(1, temp2); /* Get texture coordinates relative to the first vertex. */ float s1 = u2 - u1; float s2 = u3 - u1; float t1 = v2 - v1; float t2 = v3 - v1; /* This can happen because of (1) missing texture * (2) broken texture coordinates, so we skip it. */ if (Math.abs(s1 * t2 - s2 * t1) < EPS) { return; } /* TODO PA1: Construct the inverse (s,t) matrix, and compute * tangent and bitangent vectors as explained on Lengyel's site. */ GVector tangent = new GVector(3); GVector bi_tangent = new GVector(3); GMatrix matST = new GMatrix(2,2); double[] temp3 = {s1, t1}; double[] temp4 = {s2, t2}; matST.setRow(0, temp3); matST.setRow(1, temp4); matST.invert(); matST.mul(matQ); matST.getRow(0, tangent); matST.getRow(1, bi_tangent); /* Accumulate into temporary arrays. */ tan1[3 * i1 + 0] += tangent.getElement(0); tan1[3 * i1 + 1] += tangent.getElement(1); tan1[3 * i1 + 2] += tangent.getElement(2); tan1[3 * i2 + 0] += tangent.getElement(0); tan1[3 * i2 + 1] += tangent.getElement(1); tan1[3 * i2 + 2] += tangent.getElement(2); tan1[3 * i3 + 0] += tangent.getElement(0); tan1[3 * i3 + 1] += tangent.getElement(1); tan1[3 * i3 + 2] += tangent.getElement(2); tan2[3 * i1 + 0] += bi_tangent.getElement(0); tan2[3 * i1 + 1] += bi_tangent.getElement(1); tan2[3 * i1 + 2] += bi_tangent.getElement(2); tan2[3 * i2 + 0] += bi_tangent.getElement(0); tan2[3 * i2 + 1] += bi_tangent.getElement(1); tan2[3 * i2 + 2] += bi_tangent.getElement(2); tan2[3 * i3 + 0] += bi_tangent.getElement(0); tan2[3 * i3 + 1] += bi_tangent.getElement(1); tan2[3 * i3 + 2] += bi_tangent.getElement(2); }
protected void computeAndAccumulateTangentVectors(int i1, int i2, int i3, float tan1[], float[] tan2) { /* Get vertex coordinates of this triangle. */ Vector3f p0 = new Vector3f(mVertexData.get(3 * i1 + 0), mVertexData.get(3 * i1 + 1), mVertexData.get(3 * i1 + 2)); Vector3f p1 = new Vector3f(mVertexData.get(3 * i2 + 0), mVertexData.get(3 * i2 + 1), mVertexData.get(3 * i2 + 2)); Vector3f p2 = new Vector3f(mVertexData.get(3 * i3 + 0), mVertexData.get(3 * i3 + 1), mVertexData.get(3 * i3 + 2)); /* Get texture coordinates of this triangle. */ float u1 = mTexCoordData.get(2 * i1 + 0); float v1 = mTexCoordData.get(2 * i1 + 1); float u2 = mTexCoordData.get(2 * i2 + 0); float v2 = mTexCoordData.get(2 * i2 + 1); float u3 = mTexCoordData.get(2 * i3 + 0); float v3 = mTexCoordData.get(2 * i3 + 1); /* Get positions of vertices relative to the first vertex. */ Vector3f q1 = new Vector3f(); Vector3f q2 = new Vector3f(); q1.sub(p1, p0); q2.sub(p2, p0); /* TODO PA1: Construct the Q matrix */ GMatrix matQ = new GMatrix(2, 3); double[] temp1 = {q1.x, q1.y, q1.z}; double[] temp2 = {q2.x, q2.y, q2.z}; matQ.setRow(0, temp1); matQ.setRow(1, temp2); /* Get texture coordinates relative to the first vertex. */ float s1 = u2 - u1; float s2 = u3 - u1; float t1 = v2 - v1; float t2 = v3 - v1; /* This can happen because of (1) missing texture * (2) broken texture coordinates, so we skip it. */ if (Math.abs(s1 * t2 - s2 * t1) < EPS) { return; } /* TODO PA1: Construct the inverse (s,t) matrix, and compute * tangent and bitangent vectors as explained on Lengyel's site. */ GVector tangent = new GVector(3); GVector bi_tangent = new GVector(3); GMatrix matST = new GMatrix(2,2); double[] temp3 = {s1, t1}; double[] temp4 = {s2, t2}; matST.setRow(0, temp3); matST.setRow(1, temp4); matST.invert(); //System.out.println(matST.getNumCol()); //System.out.println(matST.getNumRow()); //System.out.println(matQ.getNumCol()); //System.out.println(matQ.getNumRow()); GMatrix matTB = new GMatrix(2,3); matTB.mul(matST, matQ); //matST.mulTransposeRight(matST, matQ); matTB.getRow(0, tangent); matTB.getRow(1, bi_tangent); /* Accumulate into temporary arrays. */ tan1[3 * i1 + 0] += tangent.getElement(0); tan1[3 * i1 + 1] += tangent.getElement(1); tan1[3 * i1 + 2] += tangent.getElement(2); tan1[3 * i2 + 0] += tangent.getElement(0); tan1[3 * i2 + 1] += tangent.getElement(1); tan1[3 * i2 + 2] += tangent.getElement(2); tan1[3 * i3 + 0] += tangent.getElement(0); tan1[3 * i3 + 1] += tangent.getElement(1); tan1[3 * i3 + 2] += tangent.getElement(2); tan2[3 * i1 + 0] += bi_tangent.getElement(0); tan2[3 * i1 + 1] += bi_tangent.getElement(1); tan2[3 * i1 + 2] += bi_tangent.getElement(2); tan2[3 * i2 + 0] += bi_tangent.getElement(0); tan2[3 * i2 + 1] += bi_tangent.getElement(1); tan2[3 * i2 + 2] += bi_tangent.getElement(2); tan2[3 * i3 + 0] += bi_tangent.getElement(0); tan2[3 * i3 + 1] += bi_tangent.getElement(1); tan2[3 * i3 + 2] += bi_tangent.getElement(2); }
diff --git a/src/com/herocraftonline/dev/heroes/inventory/InventoryChecker.java b/src/com/herocraftonline/dev/heroes/inventory/InventoryChecker.java index ee67fbec..970d45a3 100644 --- a/src/com/herocraftonline/dev/heroes/inventory/InventoryChecker.java +++ b/src/com/herocraftonline/dev/heroes/inventory/InventoryChecker.java @@ -1,175 +1,175 @@ package com.herocraftonline.dev.heroes.inventory; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import com.herocraftonline.dev.heroes.Heroes; import com.herocraftonline.dev.heroes.classes.HeroClass; import com.herocraftonline.dev.heroes.classes.HeroClass.WeaponItems; import com.herocraftonline.dev.heroes.persistence.Hero; import com.herocraftonline.dev.heroes.util.MaterialUtil; import com.herocraftonline.dev.heroes.util.Messaging; public class InventoryChecker { private Heroes plugin; private boolean allowHats = false; public InventoryChecker(Heroes plugin) { this.plugin = plugin; this.allowHats = plugin.getConfigManager().getProperties().allowHats; } public void checkInventory(Player p) { PlayerInventory inv = p.getInventory(); Hero h = plugin.getHeroManager().getHero(p); HeroClass hc = h.getHeroClass(); int removedCount = 0; int count = 0; String item; if (inv.getHelmet() != null && inv.getHelmet().getTypeId() != 0 && !allowHats) { item = inv.getHelmet().getType().toString(); - if (!hc.getAllowedArmor().contains(item)) { + if (!hc.getAllowedArmor().contains(item) && !hc.getAllowedArmor().contains("*")) { if (moveItem(p, -1, inv.getHelmet())) { removedCount++; } inv.setHelmet(null); count++; } } if (inv.getChestplate() != null && inv.getChestplate().getTypeId() != 0) { item = inv.getChestplate().getType().toString(); - if (!hc.getAllowedArmor().contains(item)) { + if (!hc.getAllowedArmor().contains(item) && !hc.getAllowedArmor().contains("*")) { if (moveItem(p, -1, inv.getChestplate())) { removedCount++; } inv.setChestplate(null); count++; } } if (inv.getLeggings() != null && inv.getLeggings().getTypeId() != 0) { item = inv.getLeggings().getType().toString(); - if (!hc.getAllowedArmor().contains(item)) { + if (!hc.getAllowedArmor().contains(item) && !hc.getAllowedArmor().contains("*")) { if (moveItem(p, -1, inv.getLeggings())) { removedCount++; } inv.setLeggings(null); count++; } } if (inv.getBoots() != null && inv.getBoots().getTypeId() != 0) { item = inv.getBoots().getType().toString(); - if (!hc.getAllowedArmor().contains(item)) { + if (!hc.getAllowedArmor().contains(item) && !hc.getAllowedArmor().contains("*")) { if (moveItem(p, -1, inv.getBoots())) { removedCount++; } inv.setBoots(null); count++; } } for (int i = 0; i < 9; i++) { ItemStack itemStack = inv.getItem(i); String itemType = itemStack.getType().toString(); // Perform a check to see if what we have is a Weapon. if (!itemType.equalsIgnoreCase("BOW")) { try { WeaponItems.valueOf(itemType.substring(itemType.indexOf("_") + 1, itemType.length())); } catch (IllegalArgumentException e1) { continue; } } if (!hc.getAllowedWeapons().contains(itemType)) { if (moveItem(p, i, itemStack)) { removedCount++; } count++; } } // If items were removed from the Players inventory then we need to alert them of such event. if (removedCount > 0) { Messaging.send(p, "$1 have been removed from your inventory due to class restrictions.", removedCount + " Items"); Messaging.send(p, "Please make space in your inventory then type '$1'", "/heroes recoveritems"); } // If any items were removed or moved in the inventory then we need to make sure the Client is in Sync. if (count > 0) { syncInventory(p); } } /** * Check the given Players inventory for any Armor or Weapons which are restricted. * * @param name */ public void checkInventory(String name) { Player player = Bukkit.getServer().getPlayer(name); if (player != null) { checkInventory(player); } } /** * Grab the first empty INVENTORY SLOT, skips the Hotbar. * * @param p * @return */ public int firstEmpty(Player p) { ItemStack[] inventory = p.getInventory().getContents(); for (int i = 9; i < inventory.length; i++) { if (inventory[i] == null) { return i; } } return -1; } /** * Move the selected Item to an available slot, if a slot does not exist then we remove it from the inventory. * * @param p * @param slot * @param item * @return */ public boolean moveItem(Player p, int slot, ItemStack item) { PlayerInventory inv = p.getInventory(); Hero h = plugin.getHeroManager().getHero(p); int empty = firstEmpty(p); if (empty == -1) { h.addRecoveryItem(item); if (slot != -1) { inv.setItem(slot, null); } return true; } else { inv.setItem(empty, item); if (slot != -1) { inv.setItem(slot, null); } Messaging.send(p, "You are not trained to use a $1.", MaterialUtil.getFriendlyName(item.getType())); return false; } } /** * Synchronize the Clients Inventory with the Server. This is dealt during a scheduler so it happens after ANY * changes are made. * Synchronizing during changes often results in the client losing Sync. * * @param player */ public void syncInventory(final Player player) { plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @SuppressWarnings("deprecation") public void run() { player.updateInventory(); } }); } }
false
true
public void checkInventory(Player p) { PlayerInventory inv = p.getInventory(); Hero h = plugin.getHeroManager().getHero(p); HeroClass hc = h.getHeroClass(); int removedCount = 0; int count = 0; String item; if (inv.getHelmet() != null && inv.getHelmet().getTypeId() != 0 && !allowHats) { item = inv.getHelmet().getType().toString(); if (!hc.getAllowedArmor().contains(item)) { if (moveItem(p, -1, inv.getHelmet())) { removedCount++; } inv.setHelmet(null); count++; } } if (inv.getChestplate() != null && inv.getChestplate().getTypeId() != 0) { item = inv.getChestplate().getType().toString(); if (!hc.getAllowedArmor().contains(item)) { if (moveItem(p, -1, inv.getChestplate())) { removedCount++; } inv.setChestplate(null); count++; } } if (inv.getLeggings() != null && inv.getLeggings().getTypeId() != 0) { item = inv.getLeggings().getType().toString(); if (!hc.getAllowedArmor().contains(item)) { if (moveItem(p, -1, inv.getLeggings())) { removedCount++; } inv.setLeggings(null); count++; } } if (inv.getBoots() != null && inv.getBoots().getTypeId() != 0) { item = inv.getBoots().getType().toString(); if (!hc.getAllowedArmor().contains(item)) { if (moveItem(p, -1, inv.getBoots())) { removedCount++; } inv.setBoots(null); count++; } } for (int i = 0; i < 9; i++) { ItemStack itemStack = inv.getItem(i); String itemType = itemStack.getType().toString(); // Perform a check to see if what we have is a Weapon. if (!itemType.equalsIgnoreCase("BOW")) { try { WeaponItems.valueOf(itemType.substring(itemType.indexOf("_") + 1, itemType.length())); } catch (IllegalArgumentException e1) { continue; } } if (!hc.getAllowedWeapons().contains(itemType)) { if (moveItem(p, i, itemStack)) { removedCount++; } count++; } } // If items were removed from the Players inventory then we need to alert them of such event. if (removedCount > 0) { Messaging.send(p, "$1 have been removed from your inventory due to class restrictions.", removedCount + " Items"); Messaging.send(p, "Please make space in your inventory then type '$1'", "/heroes recoveritems"); } // If any items were removed or moved in the inventory then we need to make sure the Client is in Sync. if (count > 0) { syncInventory(p); } }
public void checkInventory(Player p) { PlayerInventory inv = p.getInventory(); Hero h = plugin.getHeroManager().getHero(p); HeroClass hc = h.getHeroClass(); int removedCount = 0; int count = 0; String item; if (inv.getHelmet() != null && inv.getHelmet().getTypeId() != 0 && !allowHats) { item = inv.getHelmet().getType().toString(); if (!hc.getAllowedArmor().contains(item) && !hc.getAllowedArmor().contains("*")) { if (moveItem(p, -1, inv.getHelmet())) { removedCount++; } inv.setHelmet(null); count++; } } if (inv.getChestplate() != null && inv.getChestplate().getTypeId() != 0) { item = inv.getChestplate().getType().toString(); if (!hc.getAllowedArmor().contains(item) && !hc.getAllowedArmor().contains("*")) { if (moveItem(p, -1, inv.getChestplate())) { removedCount++; } inv.setChestplate(null); count++; } } if (inv.getLeggings() != null && inv.getLeggings().getTypeId() != 0) { item = inv.getLeggings().getType().toString(); if (!hc.getAllowedArmor().contains(item) && !hc.getAllowedArmor().contains("*")) { if (moveItem(p, -1, inv.getLeggings())) { removedCount++; } inv.setLeggings(null); count++; } } if (inv.getBoots() != null && inv.getBoots().getTypeId() != 0) { item = inv.getBoots().getType().toString(); if (!hc.getAllowedArmor().contains(item) && !hc.getAllowedArmor().contains("*")) { if (moveItem(p, -1, inv.getBoots())) { removedCount++; } inv.setBoots(null); count++; } } for (int i = 0; i < 9; i++) { ItemStack itemStack = inv.getItem(i); String itemType = itemStack.getType().toString(); // Perform a check to see if what we have is a Weapon. if (!itemType.equalsIgnoreCase("BOW")) { try { WeaponItems.valueOf(itemType.substring(itemType.indexOf("_") + 1, itemType.length())); } catch (IllegalArgumentException e1) { continue; } } if (!hc.getAllowedWeapons().contains(itemType)) { if (moveItem(p, i, itemStack)) { removedCount++; } count++; } } // If items were removed from the Players inventory then we need to alert them of such event. if (removedCount > 0) { Messaging.send(p, "$1 have been removed from your inventory due to class restrictions.", removedCount + " Items"); Messaging.send(p, "Please make space in your inventory then type '$1'", "/heroes recoveritems"); } // If any items were removed or moved in the inventory then we need to make sure the Client is in Sync. if (count > 0) { syncInventory(p); } }
diff --git a/src/main/java/nl/lolmen/apply/Main.java b/src/main/java/nl/lolmen/apply/Main.java index 05df5c2..18b9ef9 100644 --- a/src/main/java/nl/lolmen/apply/Main.java +++ b/src/main/java/nl/lolmen/apply/Main.java @@ -1,414 +1,414 @@ package nl.lolmen.apply; import java.io.File; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.logging.Logger; import nl.lolmen.apply.Applicant.todo; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.java.JavaPlugin; import ru.tehkode.permissions.PermissionManager; import ru.tehkode.permissions.bukkit.PermissionsEx; public class Main extends JavaPlugin{ public Logger log; private PermissionManager perm; public HashMap<String, Applicant> list = new HashMap<String, Applicant>(); private HashMap<String, String> lookingat = new HashMap<String, String>(); private Settings set; private MySQL mysql; public void onDisable() { this.mysql.close(); } public void onEnable() { this.log = this.getLogger(); new File("plugins/Apply/").mkdir(); //new File("plugins/Apply/apps/").mkdir(); this.checkPerm(); this.set = new Settings(); this.getServer().getPluginManager().registerEvents(new Listeners(this), this); this.mysql = new MySQL( this.set.getHost(), this.set.getPort(), this.set.getUsername(), this.set.getPassword(), this.set.getDatabase(), this.set.getTable()); } protected MySQL getMySQL(){ return this.mysql; } protected Settings getSettings(){ return this.set; } private void checkPerm() { Plugin test = this.getServer().getPluginManager().getPlugin("PermissionsEx"); if(test != null){ this.perm = PermissionsEx.getPermissionManager(); this.log.info("Permissions Plugin found! (PEX)"); }else{ this.log.info("PEX not found! Disabling!"); this.getServer().getPluginManager().disablePlugin(this); } } public boolean onCommand(CommandSender sender, Command cmd, String str, String[] args){ if(!cmd.getName().equalsIgnoreCase("apply")){ return false; } if(sender.hasPermission("apply.check")){ //has permission to check other's applications if(args.length == 0){ ResultSet set = this.mysql.executeQuery("SELECT * FROM " + this.set.getTable() + " WHERE promoted = 0 ORDER BY player" ); if(set == null){ sender.sendMessage("It seems there was an error.. Check the logs."); return true; } try{ while(set.next()){ if(this.list.containsKey(set.getString("player"))){ //is still busy continue; } sender.sendMessage(ChatColor.RED + "IGN: " + ChatColor.WHITE + set.getString("player")); sender.sendMessage(ChatColor.RED + "Banned: " + ChatColor.WHITE + set.getString("banned")); sender.sendMessage(ChatColor.RED + "Good at: " + ChatColor.WHITE + set.getString("goodat")); sender.sendMessage(ChatColor.RED + "Name: " + ChatColor.WHITE + set.getString("name")); sender.sendMessage(ChatColor.RED + "Age: " + ChatColor.WHITE + set.getString("age")); sender.sendMessage(ChatColor.RED + "Country: " + ChatColor.WHITE + set.getString("country")); sender.sendMessage("Accept with /apply accept Reject with /apply deny"); this.lookingat.put(sender.getName(), set.getString("player")); return true; } sender.sendMessage("No players to apply!"); return true; }catch(Exception e){ sender.sendMessage("An error occured while reading the application!"); e.printStackTrace(); return true; } } if(args[0].equalsIgnoreCase("accept")){ if(!this.lookingat.containsKey(sender.getName())){ sender.sendMessage("You have to see someone's application first. /apply"); return true; } String player = this.lookingat.get(sender.getName()); ResultSet set = this.mysql.executeQuery("SELECT * FROM " + this.set.getTable() + " WHERE player='" + player + "'"); if(set == null){ sender.sendMessage("Well that's just weird.. " + player + " is not in the database O.o"); return true; } try { while(set.next()){ if(set.getInt("promoted") == 1){ sender.sendMessage("Someone else already promoted him: " + set.getString("promoter")); return true; } this.mysql.executeQuery("UPDATE " + this.set.getTable() + " SET promoter='" + sender.getName() + "', promoted=1 WHERE player='" + player + "'"); if(!this.perm.getUser(player).inGroup("Non-Applied")){ sender.sendMessage("He's not in the non-applied group anymore apparently!"); return true; } this.getServer().dispatchCommand(this.getServer().getConsoleSender(), "pex promote " + player + " Main"); Player prom = this.getServer().getPlayer(player); if(prom == null || !prom.isOnline()){ return true; } prom.sendMessage(ChatColor.RED + "You have been promoted by " + ChatColor.GREEN + sender.getName() + "!"); this.lookingat.remove(sender.getName()); return true; } sender.sendMessage("Well that's just weird.. " + player + " is not in the database O.o"); return true; } catch (SQLException e) { sender.sendMessage("An error occured while reading the application!"); e.printStackTrace(); return true; } } if(args[0].equalsIgnoreCase("deny") || args[0].equalsIgnoreCase("reject")){ if(!this.lookingat.containsKey(sender.getName())){ sender.sendMessage("You have to see someone's application first. /apply"); return true; } String player = this.lookingat.get(sender.getName()); ResultSet set = this.mysql.executeQuery("SELECT * FROM " + this.set.getTable() + " WHERE player='" + player + "'"); if(set == null){ sender.sendMessage("Well that's just weird.. " + player + " is not in the database O.o"); return true; } try { while(set.next()){ if(set.getInt("promoted") == 1 || !this.perm.getUser(player).inGroup("Non-Applied")){ sender.sendMessage("Someone else already promoted him: " + set.getString("promoter")); return true; } this.mysql.executeQuery("DELETE FROM " + this.set.getTable() + " WHERE player='" + player + "'"); if(!this.perm.getUser(player).inGroup("Non-Applied")){ sender.sendMessage("He's not in the non-applied group anymore apparently!"); return true; } Player prom = this.getServer().getPlayer(player); if(prom == null || !prom.isOnline()){ return true; } prom.sendMessage(ChatColor.RED + "Your application has been rejected, please apply again!"); this.lookingat.remove(sender.getName()); return true; } sender.sendMessage("Well that's just weird.. " + player + " is not in the database O.o"); return true; } catch (SQLException e) { sender.sendMessage("An error occured while reading the application!"); e.printStackTrace(); return true; } } if(args[0].equalsIgnoreCase("lookup")){ if(args.length == 1){ sender.sendMessage("ERR: args. Correct usage: /apply lookup <player>"); return true; } String player = args[1]; if(this.getServer().getPlayer(player)!=null){ player = this.getServer().getPlayer(player).getName(); } ResultSet set = this.mysql.executeQuery("SELECT * FROM " + this.set.getTable() + " WHERE player='" + player + "' LIMIT 1"); if(set == null){ sender.sendMessage("This query returned null, sorry!"); return true; } try { while(set.next()){ sender.sendMessage(ChatColor.RED + "IGN: " + ChatColor.WHITE + set.getString("player")); sender.sendMessage(ChatColor.RED + "Banned: " + ChatColor.WHITE + set.getString("banned")); sender.sendMessage(ChatColor.RED + "Good at: " + ChatColor.WHITE + set.getString("goodat")); sender.sendMessage(ChatColor.RED + "Name: " + ChatColor.WHITE + set.getString("name")); sender.sendMessage(ChatColor.RED + "Age: " + ChatColor.WHITE + set.getString("age")); sender.sendMessage(ChatColor.RED + "Country: " + ChatColor.WHITE + set.getString("country")); sender.sendMessage(ChatColor.RED + "Promoted: " + ChatColor.WHITE + (set.getInt("promoted") == 0 ? "false" : "true")); - sender.sendMessage(ChatColor.RED + "Promoter: " + ChatColor.WHITE + (set.getString("promoter").equals(null) ? "no-one" : set.getString("promoter"))); + sender.sendMessage(ChatColor.RED + "Promoter: " + ChatColor.WHITE + (set.getString("promoter") == null ? "no-one" : set.getString("promoter"))); return true; } sender.sendMessage("Player " + player + " apparently isn't in the database!"); return true; } catch (SQLException e) { e.printStackTrace(); sender.sendMessage("An error occured while reading the application!"); return true; } } sender.sendMessage("Unknown Apply command: /apply " + args[0]); return true; } //It's a normal player doing the command if(args.length == 0){ if(this.list.containsKey(sender.getName())){ //Confirms the data sender.sendMessage("Last thing you need to know: the rules."); this.list.get(sender.getName()).sendRules(); this.list.remove(sender.getName()); return true; } //check if he already applied ResultSet set = this.getMySQL().executeQuery("SELECT * FROM " + this.getSettings().getTable() + " WHERE player='" + sender.getName() + "' LIMIT 1"); if(set == null){ sender.sendMessage("The query is null, sorry!"); return true; } try { while(set.next()){ if(set.getInt("promoted") == 1){ //Already promoted sender.sendMessage("You've already applied, and have been promoted by " + (set.getString("promoter").equals(null) ? "no-one" : set.getString("promoter"))); return true; } sender.sendMessage("To apply, find a [Apply] sign!"); return true; } if(this.perm.getUser(sender.getName()).inGroup("Non-Applied")){ sender.sendMessage("To apply, find a [Apply] sign!"); return true; } sender.sendMessage("You've already been promoted, but we've got no clue how :O"); return true; } catch (SQLException e) { e.printStackTrace(); sender.sendMessage("Something went terribly wrong while reading the data!"); return true; } } if(args[0].equalsIgnoreCase("reject")){ if(this.list.containsKey(sender.getName())){ sender.sendMessage("We've reset your application, you can now try again!"); Applicant c = this.list.get(sender.getName()); c.setNext(todo.GOODAT); sender.sendMessage("So, what are you good at?"); return true; } sender.sendMessage("What's there to reject?"); return true; } /* if(str.equalsIgnoreCase("apply")){ if(sender instanceof Player){ final Player p = (Player)sender; if(args.length == 1){ if(perm.getUser(p).inGroup("owner") || perm.getUser(p).inGroup("Admins") || perm.getUser(p).inGroup("Moderator")){ String get = args[0]; if(get.equalsIgnoreCase("accept") || get.equalsIgnoreCase("deny")){ if(lookingat.containsKey(p)){ String at = lookingat.get(p); if(get.equalsIgnoreCase("accept")){ if(perm.getUser(at).inGroup("applied")){ sender.sendMessage("Someone already applied him!"); lookingat.remove(p); return true; } getServer().dispatchCommand(getServer().getConsoleSender(), "pex promote " + at); getServer().broadcastMessage(ChatColor.RED + at + ChatColor.WHITE + " is now a " + ChatColor.GREEN + "Citizen! " + ChatColor.WHITE + "Hooray!"); lookingat.remove(p); new File("plugins/Apply/apps/" + at + ".txt").delete(); return true; }else if(get.equalsIgnoreCase("deny") || get.equalsIgnoreCase("reject") ){ getServer().broadcastMessage(at + " had his Citizen application rejected. Try again!"); new File("plugins/Apply/apps/" + at + ".txt").delete(); lookingat.remove(p); return true; }else if (get.equalsIgnoreCase("next")){ File[] ar = new File("plugins/Apply/apps/").listFiles(); if(ar.length == 0){ sender.sendMessage("Someone else already did it.. No-one next!"); return true; } if(ar.length == 1){ sender.sendMessage("Only 1 to apply.. Sorry!"); return true; } try{ File use = ar[1]; Properties prop = new Properties(); FileInputStream in = new FileInputStream(use); prosender.load(in); sender.sendMessage(ChatColor.RED + "IGN: " + ChatColor.WHITE + prosender.getProperty("IGN")); sender.sendMessage(ChatColor.RED + "Banned: " + ChatColor.WHITE + prosender.getProperty("banned")); sender.sendMessage(ChatColor.RED + "Good at: " + ChatColor.WHITE + prosender.getProperty("goodat")); sender.sendMessage(ChatColor.RED + "Name: " + ChatColor.WHITE + prosender.getProperty("name")); sender.sendMessage(ChatColor.RED + "Age: " + ChatColor.WHITE + prosender.getProperty("age")); sender.sendMessage(ChatColor.RED + "Country: " + ChatColor.WHITE + prosender.getProperty("country")); sender.sendMessage("Accept with /apply accept"); lookingat.put(p, prosender.getProperty("IGN")); in.close(); return true; }catch(Exception e){ e.printStackTrace(); } }else{ sender.sendMessage("Unknown command.. Sorry!"); return true; } } } } } if(sender.hasPermission("apply.apply")){ if(perm.getUser(p).inGroup("owner") || perm.getUser(p).inGroup("Admins") || perm.getUser(p).inGroup("Moderator")){ File[] ar = new File("plugins/Apply/apps/").listFiles(); if(ar.length == 0){ sender.sendMessage(ChatColor.GREEN + "No-one to apply!"); return true; } try { File process = ar[0]; Properties prop = new Properties(); FileInputStream in = new FileInputStream(process); prosender.load(in); sender.sendMessage(ChatColor.RED + "IGN: " + ChatColor.WHITE + prosender.getProperty("IGN")); sender.sendMessage(ChatColor.RED + "Banned: " + ChatColor.WHITE + prosender.getProperty("banned")); sender.sendMessage(ChatColor.RED + "Good at: " + ChatColor.WHITE + prosender.getProperty("goodat")); sender.sendMessage(ChatColor.RED + "Name: " + ChatColor.WHITE + prosender.getProperty("name")); sender.sendMessage(ChatColor.RED + "Age: " + ChatColor.WHITE + prosender.getProperty("age")); sender.sendMessage(ChatColor.RED + "Country: " + ChatColor.WHITE + prosender.getProperty("country")); sender.sendMessage("Accept with /apply accept"); lookingat.put(p, prosender.getProperty("IGN")); in.close(); return true; } catch (Exception e) { e.printStackTrace(); sender.sendMessage("File Error."); return true; } } sender.sendMessage("Why would you want to apply " + ChatColor.RED + "again?"); return true; } if(list.containsKey(p)){ Applicant c = list.get(p); if(c.getNext().equals(todo.CONFIRM)){ if(args.length == 0){ sender.sendMessage("Last thing: These are the rules."); c.sendRules(); c.save(); getServer().getScheduler().scheduleAsyncDelayedTask(this, new Runnable(){ public void run() { list.remove(p); } }, 320L); list.remove(p); for(Player pl: getServer().getOnlinePlayers()){ if(perm.getUser(p).inGroup("owner") || perm.getUser(p).inGroup("Moderator") || perm.getUser(p).inGroup("Admins")){ pl.sendMessage(sender.getName() + " finished the application progress."); } } return true; }else if(args[0].equalsIgnoreCase("reset")){ c.setNext(todo.GOODAT); sender.sendMessage("Okay, we'll start from the beginnning. " + ChatColor.RED + "What are you good at?"); return true; }else{ sender.sendMessage("Did you mean " + ChatColor.RED + "/apply " + ChatColor.WHITE + "or "+ ChatColor.RED + "/apply reset?"); return true; } }else{ sender.sendMessage("You have to answer the questions first!"); return true; } } //Check if already applied, but not yet made Citizen if(new File("plugins/Apply/apps/" + ((Player)sender).getName() + ".txt").exists()){ sender.sendMessage(ChatColor.RED + "You already applied! " + ChatColor.WHITE + " A Moderator will look at it soon."); return true; }else{ Applicant c = new Applicant(this, (Player)sender); c.start(); list.put(((Player)sender), c); return true; } }else{ sender.sendMessage("Huh?!? Ur not a player :O"); return true; } }*/ return false; } }
true
true
public boolean onCommand(CommandSender sender, Command cmd, String str, String[] args){ if(!cmd.getName().equalsIgnoreCase("apply")){ return false; } if(sender.hasPermission("apply.check")){ //has permission to check other's applications if(args.length == 0){ ResultSet set = this.mysql.executeQuery("SELECT * FROM " + this.set.getTable() + " WHERE promoted = 0 ORDER BY player" ); if(set == null){ sender.sendMessage("It seems there was an error.. Check the logs."); return true; } try{ while(set.next()){ if(this.list.containsKey(set.getString("player"))){ //is still busy continue; } sender.sendMessage(ChatColor.RED + "IGN: " + ChatColor.WHITE + set.getString("player")); sender.sendMessage(ChatColor.RED + "Banned: " + ChatColor.WHITE + set.getString("banned")); sender.sendMessage(ChatColor.RED + "Good at: " + ChatColor.WHITE + set.getString("goodat")); sender.sendMessage(ChatColor.RED + "Name: " + ChatColor.WHITE + set.getString("name")); sender.sendMessage(ChatColor.RED + "Age: " + ChatColor.WHITE + set.getString("age")); sender.sendMessage(ChatColor.RED + "Country: " + ChatColor.WHITE + set.getString("country")); sender.sendMessage("Accept with /apply accept Reject with /apply deny"); this.lookingat.put(sender.getName(), set.getString("player")); return true; } sender.sendMessage("No players to apply!"); return true; }catch(Exception e){ sender.sendMessage("An error occured while reading the application!"); e.printStackTrace(); return true; } } if(args[0].equalsIgnoreCase("accept")){ if(!this.lookingat.containsKey(sender.getName())){ sender.sendMessage("You have to see someone's application first. /apply"); return true; } String player = this.lookingat.get(sender.getName()); ResultSet set = this.mysql.executeQuery("SELECT * FROM " + this.set.getTable() + " WHERE player='" + player + "'"); if(set == null){ sender.sendMessage("Well that's just weird.. " + player + " is not in the database O.o"); return true; } try { while(set.next()){ if(set.getInt("promoted") == 1){ sender.sendMessage("Someone else already promoted him: " + set.getString("promoter")); return true; } this.mysql.executeQuery("UPDATE " + this.set.getTable() + " SET promoter='" + sender.getName() + "', promoted=1 WHERE player='" + player + "'"); if(!this.perm.getUser(player).inGroup("Non-Applied")){ sender.sendMessage("He's not in the non-applied group anymore apparently!"); return true; } this.getServer().dispatchCommand(this.getServer().getConsoleSender(), "pex promote " + player + " Main"); Player prom = this.getServer().getPlayer(player); if(prom == null || !prom.isOnline()){ return true; } prom.sendMessage(ChatColor.RED + "You have been promoted by " + ChatColor.GREEN + sender.getName() + "!"); this.lookingat.remove(sender.getName()); return true; } sender.sendMessage("Well that's just weird.. " + player + " is not in the database O.o"); return true; } catch (SQLException e) { sender.sendMessage("An error occured while reading the application!"); e.printStackTrace(); return true; } } if(args[0].equalsIgnoreCase("deny") || args[0].equalsIgnoreCase("reject")){ if(!this.lookingat.containsKey(sender.getName())){ sender.sendMessage("You have to see someone's application first. /apply"); return true; } String player = this.lookingat.get(sender.getName()); ResultSet set = this.mysql.executeQuery("SELECT * FROM " + this.set.getTable() + " WHERE player='" + player + "'"); if(set == null){ sender.sendMessage("Well that's just weird.. " + player + " is not in the database O.o"); return true; } try { while(set.next()){ if(set.getInt("promoted") == 1 || !this.perm.getUser(player).inGroup("Non-Applied")){ sender.sendMessage("Someone else already promoted him: " + set.getString("promoter")); return true; } this.mysql.executeQuery("DELETE FROM " + this.set.getTable() + " WHERE player='" + player + "'"); if(!this.perm.getUser(player).inGroup("Non-Applied")){ sender.sendMessage("He's not in the non-applied group anymore apparently!"); return true; } Player prom = this.getServer().getPlayer(player); if(prom == null || !prom.isOnline()){ return true; } prom.sendMessage(ChatColor.RED + "Your application has been rejected, please apply again!"); this.lookingat.remove(sender.getName()); return true; } sender.sendMessage("Well that's just weird.. " + player + " is not in the database O.o"); return true; } catch (SQLException e) { sender.sendMessage("An error occured while reading the application!"); e.printStackTrace(); return true; } } if(args[0].equalsIgnoreCase("lookup")){ if(args.length == 1){ sender.sendMessage("ERR: args. Correct usage: /apply lookup <player>"); return true; } String player = args[1]; if(this.getServer().getPlayer(player)!=null){ player = this.getServer().getPlayer(player).getName(); } ResultSet set = this.mysql.executeQuery("SELECT * FROM " + this.set.getTable() + " WHERE player='" + player + "' LIMIT 1"); if(set == null){ sender.sendMessage("This query returned null, sorry!"); return true; } try { while(set.next()){ sender.sendMessage(ChatColor.RED + "IGN: " + ChatColor.WHITE + set.getString("player")); sender.sendMessage(ChatColor.RED + "Banned: " + ChatColor.WHITE + set.getString("banned")); sender.sendMessage(ChatColor.RED + "Good at: " + ChatColor.WHITE + set.getString("goodat")); sender.sendMessage(ChatColor.RED + "Name: " + ChatColor.WHITE + set.getString("name")); sender.sendMessage(ChatColor.RED + "Age: " + ChatColor.WHITE + set.getString("age")); sender.sendMessage(ChatColor.RED + "Country: " + ChatColor.WHITE + set.getString("country")); sender.sendMessage(ChatColor.RED + "Promoted: " + ChatColor.WHITE + (set.getInt("promoted") == 0 ? "false" : "true")); sender.sendMessage(ChatColor.RED + "Promoter: " + ChatColor.WHITE + (set.getString("promoter").equals(null) ? "no-one" : set.getString("promoter"))); return true; } sender.sendMessage("Player " + player + " apparently isn't in the database!"); return true; } catch (SQLException e) { e.printStackTrace(); sender.sendMessage("An error occured while reading the application!"); return true; } } sender.sendMessage("Unknown Apply command: /apply " + args[0]); return true; } //It's a normal player doing the command if(args.length == 0){ if(this.list.containsKey(sender.getName())){ //Confirms the data sender.sendMessage("Last thing you need to know: the rules."); this.list.get(sender.getName()).sendRules(); this.list.remove(sender.getName()); return true; } //check if he already applied ResultSet set = this.getMySQL().executeQuery("SELECT * FROM " + this.getSettings().getTable() + " WHERE player='" + sender.getName() + "' LIMIT 1"); if(set == null){ sender.sendMessage("The query is null, sorry!"); return true; } try { while(set.next()){ if(set.getInt("promoted") == 1){ //Already promoted sender.sendMessage("You've already applied, and have been promoted by " + (set.getString("promoter").equals(null) ? "no-one" : set.getString("promoter"))); return true; } sender.sendMessage("To apply, find a [Apply] sign!"); return true; } if(this.perm.getUser(sender.getName()).inGroup("Non-Applied")){ sender.sendMessage("To apply, find a [Apply] sign!"); return true; } sender.sendMessage("You've already been promoted, but we've got no clue how :O"); return true; } catch (SQLException e) { e.printStackTrace(); sender.sendMessage("Something went terribly wrong while reading the data!"); return true; } } if(args[0].equalsIgnoreCase("reject")){ if(this.list.containsKey(sender.getName())){ sender.sendMessage("We've reset your application, you can now try again!"); Applicant c = this.list.get(sender.getName()); c.setNext(todo.GOODAT); sender.sendMessage("So, what are you good at?"); return true; } sender.sendMessage("What's there to reject?"); return true; } /* if(str.equalsIgnoreCase("apply")){ if(sender instanceof Player){ final Player p = (Player)sender; if(args.length == 1){ if(perm.getUser(p).inGroup("owner") || perm.getUser(p).inGroup("Admins") || perm.getUser(p).inGroup("Moderator")){ String get = args[0]; if(get.equalsIgnoreCase("accept") || get.equalsIgnoreCase("deny")){ if(lookingat.containsKey(p)){ String at = lookingat.get(p); if(get.equalsIgnoreCase("accept")){ if(perm.getUser(at).inGroup("applied")){ sender.sendMessage("Someone already applied him!"); lookingat.remove(p); return true; } getServer().dispatchCommand(getServer().getConsoleSender(), "pex promote " + at); getServer().broadcastMessage(ChatColor.RED + at + ChatColor.WHITE + " is now a " + ChatColor.GREEN + "Citizen! " + ChatColor.WHITE + "Hooray!"); lookingat.remove(p); new File("plugins/Apply/apps/" + at + ".txt").delete(); return true; }else if(get.equalsIgnoreCase("deny") || get.equalsIgnoreCase("reject") ){ getServer().broadcastMessage(at + " had his Citizen application rejected. Try again!"); new File("plugins/Apply/apps/" + at + ".txt").delete(); lookingat.remove(p); return true; }else if (get.equalsIgnoreCase("next")){ File[] ar = new File("plugins/Apply/apps/").listFiles(); if(ar.length == 0){ sender.sendMessage("Someone else already did it.. No-one next!"); return true; } if(ar.length == 1){ sender.sendMessage("Only 1 to apply.. Sorry!"); return true; } try{ File use = ar[1]; Properties prop = new Properties(); FileInputStream in = new FileInputStream(use); prosender.load(in); sender.sendMessage(ChatColor.RED + "IGN: " + ChatColor.WHITE + prosender.getProperty("IGN")); sender.sendMessage(ChatColor.RED + "Banned: " + ChatColor.WHITE + prosender.getProperty("banned")); sender.sendMessage(ChatColor.RED + "Good at: " + ChatColor.WHITE + prosender.getProperty("goodat")); sender.sendMessage(ChatColor.RED + "Name: " + ChatColor.WHITE + prosender.getProperty("name")); sender.sendMessage(ChatColor.RED + "Age: " + ChatColor.WHITE + prosender.getProperty("age")); sender.sendMessage(ChatColor.RED + "Country: " + ChatColor.WHITE + prosender.getProperty("country")); sender.sendMessage("Accept with /apply accept"); lookingat.put(p, prosender.getProperty("IGN")); in.close(); return true; }catch(Exception e){ e.printStackTrace(); } }else{ sender.sendMessage("Unknown command.. Sorry!"); return true; } } } } } if(sender.hasPermission("apply.apply")){ if(perm.getUser(p).inGroup("owner") || perm.getUser(p).inGroup("Admins") || perm.getUser(p).inGroup("Moderator")){ File[] ar = new File("plugins/Apply/apps/").listFiles(); if(ar.length == 0){ sender.sendMessage(ChatColor.GREEN + "No-one to apply!"); return true; } try { File process = ar[0]; Properties prop = new Properties(); FileInputStream in = new FileInputStream(process); prosender.load(in); sender.sendMessage(ChatColor.RED + "IGN: " + ChatColor.WHITE + prosender.getProperty("IGN")); sender.sendMessage(ChatColor.RED + "Banned: " + ChatColor.WHITE + prosender.getProperty("banned")); sender.sendMessage(ChatColor.RED + "Good at: " + ChatColor.WHITE + prosender.getProperty("goodat")); sender.sendMessage(ChatColor.RED + "Name: " + ChatColor.WHITE + prosender.getProperty("name")); sender.sendMessage(ChatColor.RED + "Age: " + ChatColor.WHITE + prosender.getProperty("age")); sender.sendMessage(ChatColor.RED + "Country: " + ChatColor.WHITE + prosender.getProperty("country")); sender.sendMessage("Accept with /apply accept"); lookingat.put(p, prosender.getProperty("IGN")); in.close(); return true; } catch (Exception e) { e.printStackTrace(); sender.sendMessage("File Error."); return true; } } sender.sendMessage("Why would you want to apply " + ChatColor.RED + "again?"); return true; } if(list.containsKey(p)){ Applicant c = list.get(p); if(c.getNext().equals(todo.CONFIRM)){ if(args.length == 0){ sender.sendMessage("Last thing: These are the rules."); c.sendRules(); c.save(); getServer().getScheduler().scheduleAsyncDelayedTask(this, new Runnable(){ public void run() { list.remove(p); } }, 320L); list.remove(p); for(Player pl: getServer().getOnlinePlayers()){ if(perm.getUser(p).inGroup("owner") || perm.getUser(p).inGroup("Moderator") || perm.getUser(p).inGroup("Admins")){ pl.sendMessage(sender.getName() + " finished the application progress."); } } return true; }else if(args[0].equalsIgnoreCase("reset")){ c.setNext(todo.GOODAT); sender.sendMessage("Okay, we'll start from the beginnning. " + ChatColor.RED + "What are you good at?"); return true; }else{ sender.sendMessage("Did you mean " + ChatColor.RED + "/apply " + ChatColor.WHITE + "or "+ ChatColor.RED + "/apply reset?"); return true; } }else{ sender.sendMessage("You have to answer the questions first!"); return true; } } //Check if already applied, but not yet made Citizen if(new File("plugins/Apply/apps/" + ((Player)sender).getName() + ".txt").exists()){ sender.sendMessage(ChatColor.RED + "You already applied! " + ChatColor.WHITE + " A Moderator will look at it soon."); return true; }else{ Applicant c = new Applicant(this, (Player)sender); c.start(); list.put(((Player)sender), c); return true; } }else{ sender.sendMessage("Huh?!? Ur not a player :O"); return true; } }*/ return false; }
public boolean onCommand(CommandSender sender, Command cmd, String str, String[] args){ if(!cmd.getName().equalsIgnoreCase("apply")){ return false; } if(sender.hasPermission("apply.check")){ //has permission to check other's applications if(args.length == 0){ ResultSet set = this.mysql.executeQuery("SELECT * FROM " + this.set.getTable() + " WHERE promoted = 0 ORDER BY player" ); if(set == null){ sender.sendMessage("It seems there was an error.. Check the logs."); return true; } try{ while(set.next()){ if(this.list.containsKey(set.getString("player"))){ //is still busy continue; } sender.sendMessage(ChatColor.RED + "IGN: " + ChatColor.WHITE + set.getString("player")); sender.sendMessage(ChatColor.RED + "Banned: " + ChatColor.WHITE + set.getString("banned")); sender.sendMessage(ChatColor.RED + "Good at: " + ChatColor.WHITE + set.getString("goodat")); sender.sendMessage(ChatColor.RED + "Name: " + ChatColor.WHITE + set.getString("name")); sender.sendMessage(ChatColor.RED + "Age: " + ChatColor.WHITE + set.getString("age")); sender.sendMessage(ChatColor.RED + "Country: " + ChatColor.WHITE + set.getString("country")); sender.sendMessage("Accept with /apply accept Reject with /apply deny"); this.lookingat.put(sender.getName(), set.getString("player")); return true; } sender.sendMessage("No players to apply!"); return true; }catch(Exception e){ sender.sendMessage("An error occured while reading the application!"); e.printStackTrace(); return true; } } if(args[0].equalsIgnoreCase("accept")){ if(!this.lookingat.containsKey(sender.getName())){ sender.sendMessage("You have to see someone's application first. /apply"); return true; } String player = this.lookingat.get(sender.getName()); ResultSet set = this.mysql.executeQuery("SELECT * FROM " + this.set.getTable() + " WHERE player='" + player + "'"); if(set == null){ sender.sendMessage("Well that's just weird.. " + player + " is not in the database O.o"); return true; } try { while(set.next()){ if(set.getInt("promoted") == 1){ sender.sendMessage("Someone else already promoted him: " + set.getString("promoter")); return true; } this.mysql.executeQuery("UPDATE " + this.set.getTable() + " SET promoter='" + sender.getName() + "', promoted=1 WHERE player='" + player + "'"); if(!this.perm.getUser(player).inGroup("Non-Applied")){ sender.sendMessage("He's not in the non-applied group anymore apparently!"); return true; } this.getServer().dispatchCommand(this.getServer().getConsoleSender(), "pex promote " + player + " Main"); Player prom = this.getServer().getPlayer(player); if(prom == null || !prom.isOnline()){ return true; } prom.sendMessage(ChatColor.RED + "You have been promoted by " + ChatColor.GREEN + sender.getName() + "!"); this.lookingat.remove(sender.getName()); return true; } sender.sendMessage("Well that's just weird.. " + player + " is not in the database O.o"); return true; } catch (SQLException e) { sender.sendMessage("An error occured while reading the application!"); e.printStackTrace(); return true; } } if(args[0].equalsIgnoreCase("deny") || args[0].equalsIgnoreCase("reject")){ if(!this.lookingat.containsKey(sender.getName())){ sender.sendMessage("You have to see someone's application first. /apply"); return true; } String player = this.lookingat.get(sender.getName()); ResultSet set = this.mysql.executeQuery("SELECT * FROM " + this.set.getTable() + " WHERE player='" + player + "'"); if(set == null){ sender.sendMessage("Well that's just weird.. " + player + " is not in the database O.o"); return true; } try { while(set.next()){ if(set.getInt("promoted") == 1 || !this.perm.getUser(player).inGroup("Non-Applied")){ sender.sendMessage("Someone else already promoted him: " + set.getString("promoter")); return true; } this.mysql.executeQuery("DELETE FROM " + this.set.getTable() + " WHERE player='" + player + "'"); if(!this.perm.getUser(player).inGroup("Non-Applied")){ sender.sendMessage("He's not in the non-applied group anymore apparently!"); return true; } Player prom = this.getServer().getPlayer(player); if(prom == null || !prom.isOnline()){ return true; } prom.sendMessage(ChatColor.RED + "Your application has been rejected, please apply again!"); this.lookingat.remove(sender.getName()); return true; } sender.sendMessage("Well that's just weird.. " + player + " is not in the database O.o"); return true; } catch (SQLException e) { sender.sendMessage("An error occured while reading the application!"); e.printStackTrace(); return true; } } if(args[0].equalsIgnoreCase("lookup")){ if(args.length == 1){ sender.sendMessage("ERR: args. Correct usage: /apply lookup <player>"); return true; } String player = args[1]; if(this.getServer().getPlayer(player)!=null){ player = this.getServer().getPlayer(player).getName(); } ResultSet set = this.mysql.executeQuery("SELECT * FROM " + this.set.getTable() + " WHERE player='" + player + "' LIMIT 1"); if(set == null){ sender.sendMessage("This query returned null, sorry!"); return true; } try { while(set.next()){ sender.sendMessage(ChatColor.RED + "IGN: " + ChatColor.WHITE + set.getString("player")); sender.sendMessage(ChatColor.RED + "Banned: " + ChatColor.WHITE + set.getString("banned")); sender.sendMessage(ChatColor.RED + "Good at: " + ChatColor.WHITE + set.getString("goodat")); sender.sendMessage(ChatColor.RED + "Name: " + ChatColor.WHITE + set.getString("name")); sender.sendMessage(ChatColor.RED + "Age: " + ChatColor.WHITE + set.getString("age")); sender.sendMessage(ChatColor.RED + "Country: " + ChatColor.WHITE + set.getString("country")); sender.sendMessage(ChatColor.RED + "Promoted: " + ChatColor.WHITE + (set.getInt("promoted") == 0 ? "false" : "true")); sender.sendMessage(ChatColor.RED + "Promoter: " + ChatColor.WHITE + (set.getString("promoter") == null ? "no-one" : set.getString("promoter"))); return true; } sender.sendMessage("Player " + player + " apparently isn't in the database!"); return true; } catch (SQLException e) { e.printStackTrace(); sender.sendMessage("An error occured while reading the application!"); return true; } } sender.sendMessage("Unknown Apply command: /apply " + args[0]); return true; } //It's a normal player doing the command if(args.length == 0){ if(this.list.containsKey(sender.getName())){ //Confirms the data sender.sendMessage("Last thing you need to know: the rules."); this.list.get(sender.getName()).sendRules(); this.list.remove(sender.getName()); return true; } //check if he already applied ResultSet set = this.getMySQL().executeQuery("SELECT * FROM " + this.getSettings().getTable() + " WHERE player='" + sender.getName() + "' LIMIT 1"); if(set == null){ sender.sendMessage("The query is null, sorry!"); return true; } try { while(set.next()){ if(set.getInt("promoted") == 1){ //Already promoted sender.sendMessage("You've already applied, and have been promoted by " + (set.getString("promoter").equals(null) ? "no-one" : set.getString("promoter"))); return true; } sender.sendMessage("To apply, find a [Apply] sign!"); return true; } if(this.perm.getUser(sender.getName()).inGroup("Non-Applied")){ sender.sendMessage("To apply, find a [Apply] sign!"); return true; } sender.sendMessage("You've already been promoted, but we've got no clue how :O"); return true; } catch (SQLException e) { e.printStackTrace(); sender.sendMessage("Something went terribly wrong while reading the data!"); return true; } } if(args[0].equalsIgnoreCase("reject")){ if(this.list.containsKey(sender.getName())){ sender.sendMessage("We've reset your application, you can now try again!"); Applicant c = this.list.get(sender.getName()); c.setNext(todo.GOODAT); sender.sendMessage("So, what are you good at?"); return true; } sender.sendMessage("What's there to reject?"); return true; } /* if(str.equalsIgnoreCase("apply")){ if(sender instanceof Player){ final Player p = (Player)sender; if(args.length == 1){ if(perm.getUser(p).inGroup("owner") || perm.getUser(p).inGroup("Admins") || perm.getUser(p).inGroup("Moderator")){ String get = args[0]; if(get.equalsIgnoreCase("accept") || get.equalsIgnoreCase("deny")){ if(lookingat.containsKey(p)){ String at = lookingat.get(p); if(get.equalsIgnoreCase("accept")){ if(perm.getUser(at).inGroup("applied")){ sender.sendMessage("Someone already applied him!"); lookingat.remove(p); return true; } getServer().dispatchCommand(getServer().getConsoleSender(), "pex promote " + at); getServer().broadcastMessage(ChatColor.RED + at + ChatColor.WHITE + " is now a " + ChatColor.GREEN + "Citizen! " + ChatColor.WHITE + "Hooray!"); lookingat.remove(p); new File("plugins/Apply/apps/" + at + ".txt").delete(); return true; }else if(get.equalsIgnoreCase("deny") || get.equalsIgnoreCase("reject") ){ getServer().broadcastMessage(at + " had his Citizen application rejected. Try again!"); new File("plugins/Apply/apps/" + at + ".txt").delete(); lookingat.remove(p); return true; }else if (get.equalsIgnoreCase("next")){ File[] ar = new File("plugins/Apply/apps/").listFiles(); if(ar.length == 0){ sender.sendMessage("Someone else already did it.. No-one next!"); return true; } if(ar.length == 1){ sender.sendMessage("Only 1 to apply.. Sorry!"); return true; } try{ File use = ar[1]; Properties prop = new Properties(); FileInputStream in = new FileInputStream(use); prosender.load(in); sender.sendMessage(ChatColor.RED + "IGN: " + ChatColor.WHITE + prosender.getProperty("IGN")); sender.sendMessage(ChatColor.RED + "Banned: " + ChatColor.WHITE + prosender.getProperty("banned")); sender.sendMessage(ChatColor.RED + "Good at: " + ChatColor.WHITE + prosender.getProperty("goodat")); sender.sendMessage(ChatColor.RED + "Name: " + ChatColor.WHITE + prosender.getProperty("name")); sender.sendMessage(ChatColor.RED + "Age: " + ChatColor.WHITE + prosender.getProperty("age")); sender.sendMessage(ChatColor.RED + "Country: " + ChatColor.WHITE + prosender.getProperty("country")); sender.sendMessage("Accept with /apply accept"); lookingat.put(p, prosender.getProperty("IGN")); in.close(); return true; }catch(Exception e){ e.printStackTrace(); } }else{ sender.sendMessage("Unknown command.. Sorry!"); return true; } } } } } if(sender.hasPermission("apply.apply")){ if(perm.getUser(p).inGroup("owner") || perm.getUser(p).inGroup("Admins") || perm.getUser(p).inGroup("Moderator")){ File[] ar = new File("plugins/Apply/apps/").listFiles(); if(ar.length == 0){ sender.sendMessage(ChatColor.GREEN + "No-one to apply!"); return true; } try { File process = ar[0]; Properties prop = new Properties(); FileInputStream in = new FileInputStream(process); prosender.load(in); sender.sendMessage(ChatColor.RED + "IGN: " + ChatColor.WHITE + prosender.getProperty("IGN")); sender.sendMessage(ChatColor.RED + "Banned: " + ChatColor.WHITE + prosender.getProperty("banned")); sender.sendMessage(ChatColor.RED + "Good at: " + ChatColor.WHITE + prosender.getProperty("goodat")); sender.sendMessage(ChatColor.RED + "Name: " + ChatColor.WHITE + prosender.getProperty("name")); sender.sendMessage(ChatColor.RED + "Age: " + ChatColor.WHITE + prosender.getProperty("age")); sender.sendMessage(ChatColor.RED + "Country: " + ChatColor.WHITE + prosender.getProperty("country")); sender.sendMessage("Accept with /apply accept"); lookingat.put(p, prosender.getProperty("IGN")); in.close(); return true; } catch (Exception e) { e.printStackTrace(); sender.sendMessage("File Error."); return true; } } sender.sendMessage("Why would you want to apply " + ChatColor.RED + "again?"); return true; } if(list.containsKey(p)){ Applicant c = list.get(p); if(c.getNext().equals(todo.CONFIRM)){ if(args.length == 0){ sender.sendMessage("Last thing: These are the rules."); c.sendRules(); c.save(); getServer().getScheduler().scheduleAsyncDelayedTask(this, new Runnable(){ public void run() { list.remove(p); } }, 320L); list.remove(p); for(Player pl: getServer().getOnlinePlayers()){ if(perm.getUser(p).inGroup("owner") || perm.getUser(p).inGroup("Moderator") || perm.getUser(p).inGroup("Admins")){ pl.sendMessage(sender.getName() + " finished the application progress."); } } return true; }else if(args[0].equalsIgnoreCase("reset")){ c.setNext(todo.GOODAT); sender.sendMessage("Okay, we'll start from the beginnning. " + ChatColor.RED + "What are you good at?"); return true; }else{ sender.sendMessage("Did you mean " + ChatColor.RED + "/apply " + ChatColor.WHITE + "or "+ ChatColor.RED + "/apply reset?"); return true; } }else{ sender.sendMessage("You have to answer the questions first!"); return true; } } //Check if already applied, but not yet made Citizen if(new File("plugins/Apply/apps/" + ((Player)sender).getName() + ".txt").exists()){ sender.sendMessage(ChatColor.RED + "You already applied! " + ChatColor.WHITE + " A Moderator will look at it soon."); return true; }else{ Applicant c = new Applicant(this, (Player)sender); c.start(); list.put(((Player)sender), c); return true; } }else{ sender.sendMessage("Huh?!? Ur not a player :O"); return true; } }*/ return false; }
diff --git a/src/main/java/me/tehbeard/BeardAch/dataSource/SqlDataSource.java b/src/main/java/me/tehbeard/BeardAch/dataSource/SqlDataSource.java index d29fc62..dd416fb 100644 --- a/src/main/java/me/tehbeard/BeardAch/dataSource/SqlDataSource.java +++ b/src/main/java/me/tehbeard/BeardAch/dataSource/SqlDataSource.java @@ -1,236 +1,242 @@ package me.tehbeard.BeardAch.dataSource; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.util.HashMap; import java.util.HashSet; import java.util.Map.Entry; import java.util.Properties; import org.bukkit.Bukkit; import me.tehbeard.BeardAch.BeardAch; import me.tehbeard.BeardAch.achievement.Achievement; import me.tehbeard.BeardAch.achievement.AchievementPlayerLink; public class SqlDataSource extends AbstractDataSource{ private HashMap<String,HashSet<AchievementPlayerLink>> writeCache = new HashMap<String,HashSet<AchievementPlayerLink>>(); Connection conn; //protected static PreparedStatement prepGetPlayerStat; protected static PreparedStatement prepGetAllPlayerAch; protected static PreparedStatement prepAddPlayerAch; protected void createConnection(){ String conUrl = String.format("jdbc:mysql://%s/%s", BeardAch.self.getConfig().getString("ach.database.host"), BeardAch.self.getConfig().getString("ach.database.database")); BeardAch.printCon("Configuring...."); Properties conStr = new Properties(); conStr.put("user",BeardAch.self.getConfig().getString("ach.database.username","")); conStr.put("password",BeardAch.self.getConfig().getString("ach.database.password","")); BeardAch.printCon("Connecting...."); try { conn = DriverManager.getConnection(conUrl,conStr); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } protected void checkAndBuildTable(){ try{ BeardAch.printCon("Checking for storage table"); ResultSet rs = conn.getMetaData().getTables(null, null, "achievements", null); if (!rs.next()) { BeardAch.printCon("Achievements table not found, creating table"); - PreparedStatement ps = conn.prepareStatement("CREATE TABLE IF NOT EXISTS `achievements` ( `player` varchar(32) NOT NULL, `achievement` varchar(255) NOT NULL, `timestamp` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, UNIQUE KEY `player` (`player`)) ENGINE=InnoDB DEFAULT CHARSET=latin1;"); + PreparedStatement ps = conn.prepareStatement( + "CREATE TABLE IF NOT EXISTS `achievements` " + + "( `player` varchar(32) NOT NULL, " + + "`achievement` varchar(255) NOT NULL, " + + "`timestamp` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP," + + " KEY `player` (`player`)) " + + "ENGINE=InnoDB DEFAULT CHARSET=latin1;"); ps.executeUpdate(); ps.close(); BeardAch.printCon("created storage table"); } else { BeardAch.printCon("Table found"); } rs.close(); BeardAch.printCon("Checking for meta table"); rs = conn.getMetaData().getTables(null, null, "ach_map", null); if (!rs.next()) { BeardAch.printCon("meta table not found, creating table"); PreparedStatement ps = conn.prepareStatement("CREATE TABLE IF NOT EXISTS `ach_map` (`slug` char(255) NOT NULL,`name` char(255) NOT NULL,`description` char(255) NOT NULL,UNIQUE KEY `slug` (`slug`)) ENGINE=InnoDB DEFAULT CHARSET=latin1;"); ps.executeUpdate(); ps.close(); BeardAch.printCon("created meta table"); } else { BeardAch.printCon("Table found"); } rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } protected void prepareStatements(){ BeardAch.printDebugCon("Preparing statements"); try{ prepGetAllPlayerAch = conn.prepareStatement("SELECT `achievement`,`timestamp` FROM `achievements` WHERE player=?"); prepAddPlayerAch = conn.prepareStatement("INSERT INTO `achievements` (`player` ,`achievement`,`timestamp`) values (?,?,?)",Statement.RETURN_GENERATED_KEYS); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public SqlDataSource() { try { Class.forName("com.mysql.jdbc.Driver"); createConnection(); checkAndBuildTable(); prepareStatements(); Bukkit.getScheduler().scheduleSyncRepeatingTask(BeardAch.self, new Runnable(){ public void run() { Runnable r = new SqlFlusher(writeCache); writeCache = new HashMap<String,HashSet<AchievementPlayerLink>>(); Bukkit.getScheduler().scheduleAsyncDelayedTask(BeardAch.self, r); } }, 2400L, 2400L); BeardAch.printCon("Initaised MySQL Data Provider."); } catch (ClassNotFoundException e) { BeardAch.printCon("MySQL Library not found!"); } } public HashSet<AchievementPlayerLink> getPlayersAchievements(String player) { try { prepGetAllPlayerAch.setString(1, player); ResultSet rs = prepGetAllPlayerAch.executeQuery(); HashSet<AchievementPlayerLink> c = new HashSet<AchievementPlayerLink>(); while(rs.next()){ c.add(new AchievementPlayerLink(rs.getString(1),rs.getTimestamp(2))); } rs.close(); if(writeCache.containsKey(player)){ c.addAll(writeCache.get(player)); } return c; } catch (SQLException e) { e.printStackTrace(); } return null; } public void setPlayersAchievements(String player, String achievements) { if(!writeCache.containsKey(player)){ writeCache.put(player, new HashSet<AchievementPlayerLink>()); } writeCache.get(player).add(new AchievementPlayerLink(achievements,new Timestamp((new java.util.Date()).getTime()))); } class SqlFlusher implements Runnable { private HashMap<String, HashSet<AchievementPlayerLink>> write; SqlFlusher(HashMap<String, HashSet<AchievementPlayerLink>> writeCache){ write = writeCache; } public void run() { BeardAch.printCon("Flushing to database"); try { //if connection is closed, attempt to rebuild connection for( Entry<String, HashSet<AchievementPlayerLink>> es :write.entrySet()){ prepAddPlayerAch.setString(1, es.getKey()); for(AchievementPlayerLink val : es.getValue()){ prepAddPlayerAch.setString(2,val.getSlug()); prepAddPlayerAch.setTimestamp(3,val.getDate()); prepAddPlayerAch.addBatch(); } } prepAddPlayerAch.executeBatch(); prepAddPlayerAch.clearBatch(); BeardAch.printCon("Flushed to database"); } catch (SQLException e) { BeardAch.printCon("Connection Could not be established, attempting to reconnect..."); createConnection(); prepareStatements(); } } } public void flush() { (new SqlFlusher(writeCache)).run(); writeCache = new HashMap<String,HashSet<AchievementPlayerLink>>(); } public void clearAchievements(String player) { // TODO Auto-generated method stub } public void dumpFancy() { // TODO Auto-generated method stub try { conn.prepareStatement("DELETE FROM `ach_map`").execute(); PreparedStatement fancyStat = conn.prepareStatement("INSERT INTO `ach_map` values (?,?,?)"); fancyStat.clearBatch(); for(Achievement ach : BeardAch.self.getAchievementManager().getAchievementsList()){ fancyStat.setString(1, ach.getSlug()); fancyStat.setString(2, ach.getName()); fancyStat.setString(3, ach.getDescrip()); fancyStat.addBatch(); } fancyStat.executeBatch(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
true
true
protected void checkAndBuildTable(){ try{ BeardAch.printCon("Checking for storage table"); ResultSet rs = conn.getMetaData().getTables(null, null, "achievements", null); if (!rs.next()) { BeardAch.printCon("Achievements table not found, creating table"); PreparedStatement ps = conn.prepareStatement("CREATE TABLE IF NOT EXISTS `achievements` ( `player` varchar(32) NOT NULL, `achievement` varchar(255) NOT NULL, `timestamp` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, UNIQUE KEY `player` (`player`)) ENGINE=InnoDB DEFAULT CHARSET=latin1;"); ps.executeUpdate(); ps.close(); BeardAch.printCon("created storage table"); } else { BeardAch.printCon("Table found"); } rs.close(); BeardAch.printCon("Checking for meta table"); rs = conn.getMetaData().getTables(null, null, "ach_map", null); if (!rs.next()) { BeardAch.printCon("meta table not found, creating table"); PreparedStatement ps = conn.prepareStatement("CREATE TABLE IF NOT EXISTS `ach_map` (`slug` char(255) NOT NULL,`name` char(255) NOT NULL,`description` char(255) NOT NULL,UNIQUE KEY `slug` (`slug`)) ENGINE=InnoDB DEFAULT CHARSET=latin1;"); ps.executeUpdate(); ps.close(); BeardAch.printCon("created meta table"); } else { BeardAch.printCon("Table found"); } rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
protected void checkAndBuildTable(){ try{ BeardAch.printCon("Checking for storage table"); ResultSet rs = conn.getMetaData().getTables(null, null, "achievements", null); if (!rs.next()) { BeardAch.printCon("Achievements table not found, creating table"); PreparedStatement ps = conn.prepareStatement( "CREATE TABLE IF NOT EXISTS `achievements` " + "( `player` varchar(32) NOT NULL, " + "`achievement` varchar(255) NOT NULL, " + "`timestamp` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP," + " KEY `player` (`player`)) " + "ENGINE=InnoDB DEFAULT CHARSET=latin1;"); ps.executeUpdate(); ps.close(); BeardAch.printCon("created storage table"); } else { BeardAch.printCon("Table found"); } rs.close(); BeardAch.printCon("Checking for meta table"); rs = conn.getMetaData().getTables(null, null, "ach_map", null); if (!rs.next()) { BeardAch.printCon("meta table not found, creating table"); PreparedStatement ps = conn.prepareStatement("CREATE TABLE IF NOT EXISTS `ach_map` (`slug` char(255) NOT NULL,`name` char(255) NOT NULL,`description` char(255) NOT NULL,UNIQUE KEY `slug` (`slug`)) ENGINE=InnoDB DEFAULT CHARSET=latin1;"); ps.executeUpdate(); ps.close(); BeardAch.printCon("created meta table"); } else { BeardAch.printCon("Table found"); } rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
diff --git a/src/com/example/helloworld/ViewExpenseActivity.java b/src/com/example/helloworld/ViewExpenseActivity.java index 649215c..1270cb9 100644 --- a/src/com/example/helloworld/ViewExpenseActivity.java +++ b/src/com/example/helloworld/ViewExpenseActivity.java @@ -1,167 +1,167 @@ package com.example.helloworld; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import com.example.helloworld.AddExpenseActivity.DatePickerFragment; import android.os.Bundle; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.view.Menu; import android.view.View; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; public class ViewExpenseActivity extends Activity { private String id; private String date; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_view_expense); Intent intent = getIntent(); ArrayList<String> selectedItem = intent.getExtras().getStringArrayList( "selectedExpense"); String description = selectedItem.get(2); String cost = selectedItem.get(1); String type = selectedItem.get(4); date = selectedItem.get(0); id = selectedItem.get(3); EditText edit_description = (EditText) findViewById(R.id.editText_Description); edit_description.setText(description); EditText edit_cost = (EditText) findViewById(R.id.editText_cost); edit_cost.setText(cost); TextView edit_date = (TextView) findViewById(R.id.text_date); edit_date.setText(date); Spinner edit_spinner = (Spinner) findViewById(R.id.spinner_expense_types); edit_spinner.setSelection(getTypeIndex(type)); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.view_expense, menu); return true; } private int getTypeIndex(String type) { int typeIndex = -1; if (type.equalsIgnoreCase("Food")) typeIndex = 0; else if (type.equalsIgnoreCase("Groceries")) typeIndex = 1; else if (type.equalsIgnoreCase("Transportation")) typeIndex = 2; else if (type.equalsIgnoreCase("Utilities")) typeIndex = 3; else if (type.equalsIgnoreCase("Home")) typeIndex = 4; else if (type.equalsIgnoreCase("Gift")) typeIndex = 5; else if (type.equalsIgnoreCase("Miscellaneous")) typeIndex = 6; return typeIndex; } @SuppressWarnings("deprecation") public void deleteEntry(View view) { SQLiteDatabase db = MainActivity.dbHelper.getReadableDatabase(); ExpenseDao expenseObj = new ExpenseDao(db); int deletedCount = expenseObj.delete(id); if (deletedCount > 0) { // Pop-up message confirming that expense was deleted successfully AlertDialog alertDialog_deleted = new AlertDialog.Builder(this) .create(); alertDialog_deleted.setTitle("Delete successful"); alertDialog_deleted.setMessage("Expense was deleted!"); alertDialog_deleted.setButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { finishActivity(); } }); alertDialog_deleted.show(); } } @SuppressWarnings("deprecation") public void updateEntry(View view) { EditText editText = (EditText) findViewById(R.id.editText_cost); String cost_string = editText.getText().toString(); Double cost = 0.0; if(cost_string.length() > 1) { cost = Double.parseDouble(cost_string); } editText = (EditText) findViewById(R.id.editText_Description); String description = editText.getText().toString(); Spinner spinner = (Spinner) findViewById(R.id.spinner_expense_types); String type = spinner.getSelectedItem().toString(); TextView text_date = (TextView) findViewById(R.id.text_date); date = text_date.getText().toString(); - SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); + SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yy"); Date d = null; try { String text_date_string = text_date.getText().toString(); d = (Date) sdf.parse(text_date_string); } catch (ParseException e) { e.printStackTrace(); } Expense expense = new Expense(); expense.setCost(cost); expense.setLocation(description); expense.setDate(d); expense.setType(type); expense.setId(Long.parseLong(id)); SQLiteDatabase db = MainActivity.dbHelper.getWritableDatabase(); ExpenseDao expenseObj = new ExpenseDao(db); expenseObj.update(expense); // Pop-up message confirming that expense was updated successfully AlertDialog alertDialog_saved = new AlertDialog.Builder(this) .create(); alertDialog_saved.setTitle("Update successful"); alertDialog_saved.setMessage("Expense changes were saved!"); alertDialog_saved.setButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { finishActivity(); } }); alertDialog_saved.show(); } @SuppressLint("NewApi") public void showDatePicker(View v) { DialogFragment newFragment = new DatePickerFragment(); newFragment.show(getFragmentManager(), "datePicker"); } private void finishActivity() { Intent intent = new Intent(getApplicationContext(), MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); this.finish(); } }
true
true
public void updateEntry(View view) { EditText editText = (EditText) findViewById(R.id.editText_cost); String cost_string = editText.getText().toString(); Double cost = 0.0; if(cost_string.length() > 1) { cost = Double.parseDouble(cost_string); } editText = (EditText) findViewById(R.id.editText_Description); String description = editText.getText().toString(); Spinner spinner = (Spinner) findViewById(R.id.spinner_expense_types); String type = spinner.getSelectedItem().toString(); TextView text_date = (TextView) findViewById(R.id.text_date); date = text_date.getText().toString(); SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); Date d = null; try { String text_date_string = text_date.getText().toString(); d = (Date) sdf.parse(text_date_string); } catch (ParseException e) { e.printStackTrace(); } Expense expense = new Expense(); expense.setCost(cost); expense.setLocation(description); expense.setDate(d); expense.setType(type); expense.setId(Long.parseLong(id)); SQLiteDatabase db = MainActivity.dbHelper.getWritableDatabase(); ExpenseDao expenseObj = new ExpenseDao(db); expenseObj.update(expense); // Pop-up message confirming that expense was updated successfully AlertDialog alertDialog_saved = new AlertDialog.Builder(this) .create(); alertDialog_saved.setTitle("Update successful"); alertDialog_saved.setMessage("Expense changes were saved!"); alertDialog_saved.setButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { finishActivity(); } }); alertDialog_saved.show(); }
public void updateEntry(View view) { EditText editText = (EditText) findViewById(R.id.editText_cost); String cost_string = editText.getText().toString(); Double cost = 0.0; if(cost_string.length() > 1) { cost = Double.parseDouble(cost_string); } editText = (EditText) findViewById(R.id.editText_Description); String description = editText.getText().toString(); Spinner spinner = (Spinner) findViewById(R.id.spinner_expense_types); String type = spinner.getSelectedItem().toString(); TextView text_date = (TextView) findViewById(R.id.text_date); date = text_date.getText().toString(); SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yy"); Date d = null; try { String text_date_string = text_date.getText().toString(); d = (Date) sdf.parse(text_date_string); } catch (ParseException e) { e.printStackTrace(); } Expense expense = new Expense(); expense.setCost(cost); expense.setLocation(description); expense.setDate(d); expense.setType(type); expense.setId(Long.parseLong(id)); SQLiteDatabase db = MainActivity.dbHelper.getWritableDatabase(); ExpenseDao expenseObj = new ExpenseDao(db); expenseObj.update(expense); // Pop-up message confirming that expense was updated successfully AlertDialog alertDialog_saved = new AlertDialog.Builder(this) .create(); alertDialog_saved.setTitle("Update successful"); alertDialog_saved.setMessage("Expense changes were saved!"); alertDialog_saved.setButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { finishActivity(); } }); alertDialog_saved.show(); }
diff --git a/src/com/skocken/rclibrary/caller/HTTPCaller.java b/src/com/skocken/rclibrary/caller/HTTPCaller.java index 58a853f..9ae9cff 100644 --- a/src/com/skocken/rclibrary/caller/HTTPCaller.java +++ b/src/com/skocken/rclibrary/caller/HTTPCaller.java @@ -1,116 +1,116 @@ /** * */ package com.skocken.rclibrary.caller; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Scanner; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.conn.ssl.X509HostnameVerifier; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; import org.apache.http.protocol.HTTP; import android.os.Build; import android.util.Log; import com.skocken.rclibrary.RCPreference; /** * @author Stan Kocken ([email protected]) * */ public class HTTPCaller { /** Used locally to tag Logs */ private static final String TAG = HTTPCaller.class.getSimpleName(); public static String loadFromUrl(String url) { try { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) { HttpParams httpParameters = new BasicHttpParams(); HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8); HttpProtocolParams.setHttpElementCharset(httpParameters, HTTP.UTF_8); HttpClient httpclient = new DefaultHttpClient(httpParameters); // Set verifier HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier); SchemeRegistry registry = new SchemeRegistry(); SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory(); socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier); registry.register(new Scheme("https", socketFactory, 443)); httpclient.getParams().setParameter("http.protocol.content-charset", HTTP.UTF_8); HttpGet httpUriRequest = new HttpGet(url); HttpResponse httpResponse = httpclient.execute(httpUriRequest); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { InputStream ips = httpResponse.getEntity().getContent(); BufferedReader buf = new BufferedReader(new InputStreamReader(ips, "UTF-8")); StringBuilder sb = new StringBuilder(); String s; while (true) { s = buf.readLine(); if (s == null || s.length() == 0) { break; } sb.append(s); } buf.close(); ips.close(); s = sb.toString(); return s; } } else { try { // do this wherever you are wanting to POST HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); // once you set the output to true, you don't really need to set the request method to post, but I'm doing it anyway conn.setRequestMethod("GET"); // build the string to store the response text from the server StringBuilder sb = new StringBuilder(); // start listening to the stream Scanner inStream = new Scanner(conn.getInputStream()); // process the stream and store it in StringBuilder while (inStream.hasNextLine()) { sb.append(inStream.nextLine()); } return sb.toString(); } catch (MalformedURLException ex) { - if (RCPreference.sDebugMode) { + if (RCPreference.isDebug()) { Log.v(TAG, "RCLibrary : MalformedURLException", ex); } } catch (IOException ex) { - if (RCPreference.sDebugMode) { + if (RCPreference.isDebug()) { Log.v(TAG, "RCLibrary : IOException", ex); } } } } catch (Exception ex) { - if (RCPreference.sDebugMode) { + if (RCPreference.isDebug()) { Log.v(TAG, "RCLibrary : Exception", ex); } } return null; } }
false
true
public static String loadFromUrl(String url) { try { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) { HttpParams httpParameters = new BasicHttpParams(); HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8); HttpProtocolParams.setHttpElementCharset(httpParameters, HTTP.UTF_8); HttpClient httpclient = new DefaultHttpClient(httpParameters); // Set verifier HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier); SchemeRegistry registry = new SchemeRegistry(); SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory(); socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier); registry.register(new Scheme("https", socketFactory, 443)); httpclient.getParams().setParameter("http.protocol.content-charset", HTTP.UTF_8); HttpGet httpUriRequest = new HttpGet(url); HttpResponse httpResponse = httpclient.execute(httpUriRequest); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { InputStream ips = httpResponse.getEntity().getContent(); BufferedReader buf = new BufferedReader(new InputStreamReader(ips, "UTF-8")); StringBuilder sb = new StringBuilder(); String s; while (true) { s = buf.readLine(); if (s == null || s.length() == 0) { break; } sb.append(s); } buf.close(); ips.close(); s = sb.toString(); return s; } } else { try { // do this wherever you are wanting to POST HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); // once you set the output to true, you don't really need to set the request method to post, but I'm doing it anyway conn.setRequestMethod("GET"); // build the string to store the response text from the server StringBuilder sb = new StringBuilder(); // start listening to the stream Scanner inStream = new Scanner(conn.getInputStream()); // process the stream and store it in StringBuilder while (inStream.hasNextLine()) { sb.append(inStream.nextLine()); } return sb.toString(); } catch (MalformedURLException ex) { if (RCPreference.sDebugMode) { Log.v(TAG, "RCLibrary : MalformedURLException", ex); } } catch (IOException ex) { if (RCPreference.sDebugMode) { Log.v(TAG, "RCLibrary : IOException", ex); } } } } catch (Exception ex) { if (RCPreference.sDebugMode) { Log.v(TAG, "RCLibrary : Exception", ex); } } return null; }
public static String loadFromUrl(String url) { try { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) { HttpParams httpParameters = new BasicHttpParams(); HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8); HttpProtocolParams.setHttpElementCharset(httpParameters, HTTP.UTF_8); HttpClient httpclient = new DefaultHttpClient(httpParameters); // Set verifier HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier); SchemeRegistry registry = new SchemeRegistry(); SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory(); socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier); registry.register(new Scheme("https", socketFactory, 443)); httpclient.getParams().setParameter("http.protocol.content-charset", HTTP.UTF_8); HttpGet httpUriRequest = new HttpGet(url); HttpResponse httpResponse = httpclient.execute(httpUriRequest); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { InputStream ips = httpResponse.getEntity().getContent(); BufferedReader buf = new BufferedReader(new InputStreamReader(ips, "UTF-8")); StringBuilder sb = new StringBuilder(); String s; while (true) { s = buf.readLine(); if (s == null || s.length() == 0) { break; } sb.append(s); } buf.close(); ips.close(); s = sb.toString(); return s; } } else { try { // do this wherever you are wanting to POST HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); // once you set the output to true, you don't really need to set the request method to post, but I'm doing it anyway conn.setRequestMethod("GET"); // build the string to store the response text from the server StringBuilder sb = new StringBuilder(); // start listening to the stream Scanner inStream = new Scanner(conn.getInputStream()); // process the stream and store it in StringBuilder while (inStream.hasNextLine()) { sb.append(inStream.nextLine()); } return sb.toString(); } catch (MalformedURLException ex) { if (RCPreference.isDebug()) { Log.v(TAG, "RCLibrary : MalformedURLException", ex); } } catch (IOException ex) { if (RCPreference.isDebug()) { Log.v(TAG, "RCLibrary : IOException", ex); } } } } catch (Exception ex) { if (RCPreference.isDebug()) { Log.v(TAG, "RCLibrary : Exception", ex); } } return null; }
diff --git a/src/main/java/uk/co/bssd/jmx/ProcessManagementBean.java b/src/main/java/uk/co/bssd/jmx/ProcessManagementBean.java index fb0b5d5..ac6d904 100644 --- a/src/main/java/uk/co/bssd/jmx/ProcessManagementBean.java +++ b/src/main/java/uk/co/bssd/jmx/ProcessManagementBean.java @@ -1,57 +1,57 @@ package uk.co.bssd.jmx; import java.io.IOException; import java.lang.management.ManagementFactory; import javax.management.MBeanServerConnection; import com.sun.management.OperatingSystemMXBean; @SuppressWarnings("restriction") public class ProcessManagementBean { private final OperatingSystemMXBean operatingSystemBean; private final int availableProcessors; private long lastSystemTime; private long lastProcessCpuTime; public ProcessManagementBean(MBeanServerConnection connection) { this.operatingSystemBean = operatingSystemBean(connection); this.availableProcessors = this.operatingSystemBean .getAvailableProcessors(); this.lastSystemTime = System.nanoTime(); this.lastProcessCpuTime = this.operatingSystemBean.getProcessCpuTime(); } public double cpuUsage() { long systemTime = System.nanoTime(); long processCpuTime = this.operatingSystemBean.getProcessCpuTime(); - double cpuUsage = (processCpuTime - this.lastProcessCpuTime) + double cpuUsage = (100 * (processCpuTime - this.lastProcessCpuTime)) / (systemTime - this.lastSystemTime); lastSystemTime = systemTime; lastProcessCpuTime = processCpuTime; return cpuUsage / this.availableProcessors; } private OperatingSystemMXBean operatingSystemBean( MBeanServerConnection connection) { return platformBean(connection, ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME, OperatingSystemMXBean.class); } private <T> T platformBean(MBeanServerConnection connection, String beanName, Class<T> clazz) { try { return ManagementFactory.newPlatformMXBeanProxy(connection, beanName, clazz); } catch (IOException e) { throw new RuntimeException("Unable to get OperatingSystemMXBean", e); } } }
true
true
public double cpuUsage() { long systemTime = System.nanoTime(); long processCpuTime = this.operatingSystemBean.getProcessCpuTime(); double cpuUsage = (processCpuTime - this.lastProcessCpuTime) / (systemTime - this.lastSystemTime); lastSystemTime = systemTime; lastProcessCpuTime = processCpuTime; return cpuUsage / this.availableProcessors; }
public double cpuUsage() { long systemTime = System.nanoTime(); long processCpuTime = this.operatingSystemBean.getProcessCpuTime(); double cpuUsage = (100 * (processCpuTime - this.lastProcessCpuTime)) / (systemTime - this.lastSystemTime); lastSystemTime = systemTime; lastProcessCpuTime = processCpuTime; return cpuUsage / this.availableProcessors; }
diff --git a/src/main/java/net/northfuse/resources/LineWrapperInputStream.java b/src/main/java/net/northfuse/resources/LineWrapperInputStream.java index 0d17167..296fe87 100644 --- a/src/main/java/net/northfuse/resources/LineWrapperInputStream.java +++ b/src/main/java/net/northfuse/resources/LineWrapperInputStream.java @@ -1,115 +1,115 @@ package net.northfuse.resources; import java.io.*; /** * @author tylers2 */ public class LineWrapperInputStream extends InputStream { private final InputStream is; public LineWrapperInputStream(InputStream is, String description) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line; ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter writer = new PrintWriter(baos); int lineNumber = 0; boolean inComment = false; while ((line = reader.readLine()) != null) { if (inComment) { - writer.println(" d " + description + ":" + (++lineNumber) + " " + line); + writer.println(" " + description + ":" + (++lineNumber) + " " + line); } else { - writer.println("/*d " + description + ":" + (++lineNumber) + " */" + line); + writer.println("/* " + description + ":" + (++lineNumber) + " */" + line); } if (!inComment) { int commentIndex = line.lastIndexOf("/*"); if (commentIndex > -1) { if (commentIndex > 0) { //is the comment start inside of a string? if (countOccurences(line.substring(0, commentIndex), "\"") % 2 == 1) { continue; } } if (!line.substring(commentIndex).contains("*/")) { inComment = true; } } } else { int commentIndex = line.lastIndexOf("*/"); if (commentIndex > -1) { if (!line.substring(commentIndex).contains("/*")) { inComment = false; } } } } writer.close(); //get rid of the last new line byte[] data = baos.toByteArray(); this.is = new ByteArrayInputStream(data, 0, data.length - 1); } private int countOccurences(String s, String pattern) { int count = 0; for (char c : s.toCharArray()) { if (c == pattern.charAt(0)) { count++; } } return count; } private int doCountOccurences(String s, String pattern, int count) { int index = s.indexOf(pattern); if (index == -1) { return count; } else { return doCountOccurences(s.substring(index + 1), pattern, count + 1); } } @Override public int read() throws IOException { return is.read(); } @Override public int read(byte[] b) throws IOException { return is.read(b); } @Override public int read(byte[] b, int off, int len) throws IOException { return is.read(b, off, len); } @Override public long skip(long n) throws IOException { return is.skip(n); } @Override public int available() throws IOException { return is.available(); } @Override public void close() throws IOException { is.close(); } @Override public void mark(int readlimit) { is.mark(readlimit); } @Override public void reset() throws IOException { is.reset(); } @Override public boolean markSupported() { return is.markSupported(); } }
false
true
public LineWrapperInputStream(InputStream is, String description) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line; ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter writer = new PrintWriter(baos); int lineNumber = 0; boolean inComment = false; while ((line = reader.readLine()) != null) { if (inComment) { writer.println(" d " + description + ":" + (++lineNumber) + " " + line); } else { writer.println("/*d " + description + ":" + (++lineNumber) + " */" + line); } if (!inComment) { int commentIndex = line.lastIndexOf("/*"); if (commentIndex > -1) { if (commentIndex > 0) { //is the comment start inside of a string? if (countOccurences(line.substring(0, commentIndex), "\"") % 2 == 1) { continue; } } if (!line.substring(commentIndex).contains("*/")) { inComment = true; } } } else { int commentIndex = line.lastIndexOf("*/"); if (commentIndex > -1) { if (!line.substring(commentIndex).contains("/*")) { inComment = false; } } } } writer.close(); //get rid of the last new line byte[] data = baos.toByteArray(); this.is = new ByteArrayInputStream(data, 0, data.length - 1); }
public LineWrapperInputStream(InputStream is, String description) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line; ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter writer = new PrintWriter(baos); int lineNumber = 0; boolean inComment = false; while ((line = reader.readLine()) != null) { if (inComment) { writer.println(" " + description + ":" + (++lineNumber) + " " + line); } else { writer.println("/* " + description + ":" + (++lineNumber) + " */" + line); } if (!inComment) { int commentIndex = line.lastIndexOf("/*"); if (commentIndex > -1) { if (commentIndex > 0) { //is the comment start inside of a string? if (countOccurences(line.substring(0, commentIndex), "\"") % 2 == 1) { continue; } } if (!line.substring(commentIndex).contains("*/")) { inComment = true; } } } else { int commentIndex = line.lastIndexOf("*/"); if (commentIndex > -1) { if (!line.substring(commentIndex).contains("/*")) { inComment = false; } } } } writer.close(); //get rid of the last new line byte[] data = baos.toByteArray(); this.is = new ByteArrayInputStream(data, 0, data.length - 1); }
diff --git a/src/com/loopj/android/http/AsyncHttpClient.java b/src/com/loopj/android/http/AsyncHttpClient.java index ae65e94..2060e90 100644 --- a/src/com/loopj/android/http/AsyncHttpClient.java +++ b/src/com/loopj/android/http/AsyncHttpClient.java @@ -1,476 +1,476 @@ /* Android Asynchronous Http Client Copyright (c) 2011 James Smith <[email protected]> http://loopj.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.loopj.android.http; import java.io.IOException; import java.io.InputStream; import java.lang.ref.WeakReference; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.WeakHashMap; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadPoolExecutor; import java.util.zip.GZIPInputStream; import org.apache.http.Header; import org.apache.http.HeaderElement; import org.apache.http.HttpEntity; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseInterceptor; import org.apache.http.HttpVersion; import org.apache.http.client.CookieStore; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.protocol.ClientContext; import org.apache.http.conn.params.ConnManagerParams; import org.apache.http.conn.params.ConnPerRouteBean; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.entity.HttpEntityWrapper; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpProtocolParams; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.SyncBasicHttpContext; import android.content.Context; /** * The AsyncHttpClient can be used to make asynchronous GET, POST, PUT and * DELETE HTTP requests in your Android applications. Requests can be made * with additional parameters by passing a {@link RequestParams} instance, * and responses can be handled by passing an anonymously overridden * {@link AsyncHttpResponseHandler} instance. * <p> * For example: * <p> * <pre> * AsyncHttpClient client = new AsyncHttpClient(); * client.get("http://www.google.com", new AsyncHttpResponseHandler() { * &#064;Override * public void onSuccess(String response) { * System.out.println(response); * } * }); * </pre> */ public class AsyncHttpClient { private static final String VERSION = "1.3.1"; private static final int DEFAULT_MAX_CONNECTIONS = 10; private static final int DEFAULT_SOCKET_TIMEOUT = 10 * 1000; private static final int DEFAULT_MAX_RETRIES = 5; private static final int DEFAULT_SOCKET_BUFFER_SIZE = 8192; private static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding"; private static final String ENCODING_GZIP = "gzip"; private static int maxConnections = DEFAULT_MAX_CONNECTIONS; private static int socketTimeout = DEFAULT_SOCKET_TIMEOUT; private final DefaultHttpClient httpClient; private final HttpContext httpContext; private ThreadPoolExecutor threadPool; private final Map<Context, List<WeakReference<Future<?>>>> requestMap; private final Map<String, String> clientHeaderMap; /** * Creates a new AsyncHttpClient. */ public AsyncHttpClient() { BasicHttpParams httpParams = new BasicHttpParams(); ConnManagerParams.setTimeout(httpParams, socketTimeout); ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections)); ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS); HttpConnectionParams.setSoTimeout(httpParams, socketTimeout); - HttpConnectionParams.setConnectionTimeout(httpParams, socketTimout); + HttpConnectionParams.setConnectionTimeout(httpParams, socketTimeout); HttpConnectionParams.setTcpNoDelay(httpParams, true); HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE); HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); HttpProtocolParams.setUserAgent(httpParams, String.format("android-async-http/%s (http://loopj.com/android-async-http)", VERSION)); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry); httpContext = new SyncBasicHttpContext(new BasicHttpContext()); httpClient = new DefaultHttpClient(cm, httpParams); httpClient.addRequestInterceptor(new HttpRequestInterceptor() { public void process(HttpRequest request, HttpContext context) { if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) { request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP); } for (String header : clientHeaderMap.keySet()) { request.addHeader(header, clientHeaderMap.get(header)); } } }); httpClient.addResponseInterceptor(new HttpResponseInterceptor() { public void process(HttpResponse response, HttpContext context) { final HttpEntity entity = response.getEntity(); final Header encoding = entity.getContentEncoding(); if (encoding != null) { for (HeaderElement element : encoding.getElements()) { if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) { response.setEntity(new InflatingEntity(response.getEntity())); break; } } } } }); httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES)); threadPool = (ThreadPoolExecutor)Executors.newCachedThreadPool(); requestMap = new WeakHashMap<Context, List<WeakReference<Future<?>>>>(); clientHeaderMap = new HashMap<String, String>(); } /** * Get the underlying HttpClient instance. This is useful for setting * additional fine-grained settings for requests by accessing the * client's ConnectionManager, HttpParams and SchemeRegistry. */ public HttpClient getHttpClient() { return this.httpClient; } /** * Sets an optional CookieStore to use when making requests * @param cookieStore The CookieStore implementation to use, usually an instance of {@link PersistentCookieStore} */ public void setCookieStore(CookieStore cookieStore) { httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); } /** * Overrides the threadpool implementation used when queuing/pooling * requests. By default, Executors.newCachedThreadPool() is used. * @param threadPool an instance of {@link ThreadPoolExecutor} to use for queuing/pooling requests. */ public void setThreadPool(ThreadPoolExecutor threadPool) { this.threadPool = threadPool; } /** * Sets the User-Agent header to be sent with each request. By default, * "Android Asynchronous Http Client/VERSION (http://loopj.com/android-async-http/)" is used. * @param userAgent the string to use in the User-Agent header. */ public void setUserAgent(String userAgent) { HttpProtocolParams.setUserAgent(this.httpClient.getParams(), userAgent); } /** * Sets the SSLSocketFactory to user when making requests. By default, * a new, default SSLSocketFactory is used. * @param sslSocketFactory the socket factory to use for https requests. */ public void setSSLSocketFactory(SSLSocketFactory sslSocketFactory) { this.httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", sslSocketFactory, 443)); } /** * Sets headers that will be added to all requests this client makes (before sending). * @param header the name of the header * @param value the contents of the header */ public void addHeader(String header, String value) { clientHeaderMap.put(header, value); } /** * Cancels any pending (or potentially active) requests associated with the * passed Context. * <p> * <b>Note:</b> This will only affect requests which were created with a non-null * android Context. This method is intended to be used in the onDestroy * method of your android activities to destroy all requests which are no * longer required. * * @param context the android Context instance associated to the request. * @param mayInterruptIfRunning specifies if active requests should be cancelled along with pending requests. */ public void cancelRequests(Context context, boolean mayInterruptIfRunning) { List<WeakReference<Future<?>>> requestList = requestMap.get(context); if(requestList != null) { for(WeakReference<Future<?>> requestRef : requestList) { Future<?> request = requestRef.get(); if(request != null) { request.cancel(mayInterruptIfRunning); } } } requestMap.remove(context); } // // HTTP GET Requests // /** * Perform a HTTP GET request, without any parameters. * @param url the URL to send the request to. * @param responseHandler the response handler instance that should handle the response. */ public void get(String url, AsyncHttpResponseHandler responseHandler) { get(null, url, null, responseHandler); } /** * Perform a HTTP GET request with parameters. * @param url the URL to send the request to. * @param params additional GET parameters to send with the request. * @param responseHandler the response handler instance that should handle the response. */ public void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) { get(null, url, params, responseHandler); } /** * Perform a HTTP GET request without any parameters and track the Android Context which initiated the request. * @param context the Android Context which initiated the request. * @param url the URL to send the request to. * @param responseHandler the response handler instance that should handle the response. */ public void get(Context context, String url, AsyncHttpResponseHandler responseHandler) { get(context, url, null, responseHandler); } /** * Perform a HTTP GET request and track the Android Context which initiated the request. * @param context the Android Context which initiated the request. * @param url the URL to send the request to. * @param params additional GET parameters to send with the request. * @param responseHandler the response handler instance that should handle the response. */ public void get(Context context, String url, RequestParams params, AsyncHttpResponseHandler responseHandler) { sendRequest(httpClient, httpContext, new HttpGet(getUrlWithQueryString(url, params)), null, responseHandler, context); } // // HTTP POST Requests // /** * Perform a HTTP POST request, without any parameters. * @param url the URL to send the request to. * @param responseHandler the response handler instance that should handle the response. */ public void post(String url, AsyncHttpResponseHandler responseHandler) { post(null, url, null, responseHandler); } /** * Perform a HTTP POST request with parameters. * @param url the URL to send the request to. * @param params additional POST parameters or files to send with the request. * @param responseHandler the response handler instance that should handle the response. */ public void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) { post(null, url, params, responseHandler); } /** * Perform a HTTP POST request and track the Android Context which initiated the request. * @param context the Android Context which initiated the request. * @param url the URL to send the request to. * @param params additional POST parameters or files to send with the request. * @param responseHandler the response handler instance that should handle the response. */ public void post(Context context, String url, RequestParams params, AsyncHttpResponseHandler responseHandler) { post(context, url, paramsToEntity(params), null, responseHandler); } /** * Perform a HTTP POST request and track the Android Context which initiated the request. * @param context the Android Context which initiated the request. * @param url the URL to send the request to. * @param entity a raw {@link HttpEntity} to send with the request, for example, use this to send string/json/xml payloads to a server by passing a {@link org.apache.http.entity.StringEntity}. * @param contentType the content type of the payload you are sending, for example application/json if sending a json payload. * @param responseHandler the response handler instance that should handle the response. */ public void post(Context context, String url, HttpEntity entity, String contentType, AsyncHttpResponseHandler responseHandler) { sendRequest(httpClient, httpContext, addEntityToRequestBase(new HttpPost(url), entity), contentType, responseHandler, context); } // // HTTP PUT Requests // /** * Perform a HTTP PUT request, without any parameters. * @param url the URL to send the request to. * @param responseHandler the response handler instance that should handle the response. */ public void put(String url, AsyncHttpResponseHandler responseHandler) { put(null, url, null, responseHandler); } /** * Perform a HTTP PUT request with parameters. * @param url the URL to send the request to. * @param params additional PUT parameters or files to send with the request. * @param responseHandler the response handler instance that should handle the response. */ public void put(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) { put(null, url, params, responseHandler); } /** * Perform a HTTP PUT request and track the Android Context which initiated the request. * @param context the Android Context which initiated the request. * @param url the URL to send the request to. * @param params additional PUT parameters or files to send with the request. * @param responseHandler the response handler instance that should handle the response. */ public void put(Context context, String url, RequestParams params, AsyncHttpResponseHandler responseHandler) { put(context, url, paramsToEntity(params), null, responseHandler); } /** * Perform a HTTP PUT request and track the Android Context which initiated the request. * @param context the Android Context which initiated the request. * @param url the URL to send the request to. * @param entity a raw {@link HttpEntity} to send with the request, for example, use this to send string/json/xml payloads to a server by passing a {@link org.apache.http.entity.StringEntity}. * @param contentType the content type of the payload you are sending, for example application/json if sending a json payload. * @param responseHandler the response handler instance that should handle the response. */ public void put(Context context, String url, HttpEntity entity, String contentType, AsyncHttpResponseHandler responseHandler) { sendRequest(httpClient, httpContext, addEntityToRequestBase(new HttpPut(url), entity), contentType, responseHandler, context); } // // HTTP DELETE Requests // /** * Perform a HTTP DELETE request. * @param url the URL to send the request to. * @param responseHandler the response handler instance that should handle the response. */ public void delete(String url, AsyncHttpResponseHandler responseHandler) { delete(null, url, responseHandler); } /** * Perform a HTTP DELETE request. * @param context the Android Context which initiated the request. * @param url the URL to send the request to. * @param responseHandler the response handler instance that should handle the response. */ public void delete(Context context, String url, AsyncHttpResponseHandler responseHandler) { final HttpDelete delete = new HttpDelete(url); sendRequest(httpClient, httpContext, delete, null, responseHandler, context); } // Private stuff private void sendRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, AsyncHttpResponseHandler responseHandler, Context context) { if(contentType != null) { uriRequest.addHeader("Content-Type", contentType); } Future<?> request = threadPool.submit(new AsyncHttpRequest(client, httpContext, uriRequest, responseHandler)); if(context != null) { // Add request to request map List<WeakReference<Future<?>>> requestList = requestMap.get(context); if(requestList == null) { requestList = new LinkedList<WeakReference<Future<?>>>(); requestMap.put(context, requestList); } requestList.add(new WeakReference<Future<?>>(request)); // TODO: Remove dead weakrefs from requestLists? } } private String getUrlWithQueryString(String url, RequestParams params) { if(params != null) { String paramString = params.getParamString(); url += "?" + paramString; } return url; } private HttpEntity paramsToEntity(RequestParams params) { HttpEntity entity = null; if(params != null) { entity = params.getEntity(); } return entity; } private HttpEntityEnclosingRequestBase addEntityToRequestBase(HttpEntityEnclosingRequestBase requestBase, HttpEntity entity) { if(entity != null){ requestBase.setEntity(entity); } return requestBase; } private static class InflatingEntity extends HttpEntityWrapper { public InflatingEntity(HttpEntity wrapped) { super(wrapped); } @Override public InputStream getContent() throws IOException { return new GZIPInputStream(wrappedEntity.getContent()); } @Override public long getContentLength() { return -1; } } }
true
true
public AsyncHttpClient() { BasicHttpParams httpParams = new BasicHttpParams(); ConnManagerParams.setTimeout(httpParams, socketTimeout); ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections)); ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS); HttpConnectionParams.setSoTimeout(httpParams, socketTimeout); HttpConnectionParams.setConnectionTimeout(httpParams, socketTimout); HttpConnectionParams.setTcpNoDelay(httpParams, true); HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE); HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); HttpProtocolParams.setUserAgent(httpParams, String.format("android-async-http/%s (http://loopj.com/android-async-http)", VERSION)); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry); httpContext = new SyncBasicHttpContext(new BasicHttpContext()); httpClient = new DefaultHttpClient(cm, httpParams); httpClient.addRequestInterceptor(new HttpRequestInterceptor() { public void process(HttpRequest request, HttpContext context) { if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) { request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP); } for (String header : clientHeaderMap.keySet()) { request.addHeader(header, clientHeaderMap.get(header)); } } }); httpClient.addResponseInterceptor(new HttpResponseInterceptor() { public void process(HttpResponse response, HttpContext context) { final HttpEntity entity = response.getEntity(); final Header encoding = entity.getContentEncoding(); if (encoding != null) { for (HeaderElement element : encoding.getElements()) { if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) { response.setEntity(new InflatingEntity(response.getEntity())); break; } } } } }); httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES)); threadPool = (ThreadPoolExecutor)Executors.newCachedThreadPool(); requestMap = new WeakHashMap<Context, List<WeakReference<Future<?>>>>(); clientHeaderMap = new HashMap<String, String>(); }
public AsyncHttpClient() { BasicHttpParams httpParams = new BasicHttpParams(); ConnManagerParams.setTimeout(httpParams, socketTimeout); ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections)); ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS); HttpConnectionParams.setSoTimeout(httpParams, socketTimeout); HttpConnectionParams.setConnectionTimeout(httpParams, socketTimeout); HttpConnectionParams.setTcpNoDelay(httpParams, true); HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE); HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); HttpProtocolParams.setUserAgent(httpParams, String.format("android-async-http/%s (http://loopj.com/android-async-http)", VERSION)); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry); httpContext = new SyncBasicHttpContext(new BasicHttpContext()); httpClient = new DefaultHttpClient(cm, httpParams); httpClient.addRequestInterceptor(new HttpRequestInterceptor() { public void process(HttpRequest request, HttpContext context) { if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) { request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP); } for (String header : clientHeaderMap.keySet()) { request.addHeader(header, clientHeaderMap.get(header)); } } }); httpClient.addResponseInterceptor(new HttpResponseInterceptor() { public void process(HttpResponse response, HttpContext context) { final HttpEntity entity = response.getEntity(); final Header encoding = entity.getContentEncoding(); if (encoding != null) { for (HeaderElement element : encoding.getElements()) { if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) { response.setEntity(new InflatingEntity(response.getEntity())); break; } } } } }); httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES)); threadPool = (ThreadPoolExecutor)Executors.newCachedThreadPool(); requestMap = new WeakHashMap<Context, List<WeakReference<Future<?>>>>(); clientHeaderMap = new HashMap<String, String>(); }
diff --git a/src/main/java/org/primefaces/extensions/component/qrcode/QRCodeRenderer.java b/src/main/java/org/primefaces/extensions/component/qrcode/QRCodeRenderer.java index cc0aaeea..8ec65028 100644 --- a/src/main/java/org/primefaces/extensions/component/qrcode/QRCodeRenderer.java +++ b/src/main/java/org/primefaces/extensions/component/qrcode/QRCodeRenderer.java @@ -1,76 +1,73 @@ /* * Copyright 2011 PrimeFaces Extensions. * * 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. * * $Id$ */ package org.primefaces.extensions.component.qrcode; import org.primefaces.extensions.component.tooltip.*; import java.io.IOException; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import org.primefaces.extensions.renderkit.widget.WidgetRenderer; import org.primefaces.renderkit.CoreRenderer; /** * Renderer for the {@link Tooltip} component. * * @author Mauricio Fenoglio / last modified by $Author$ * @version $Revision$ * @since 1.2.0 */ public class QRCodeRenderer extends CoreRenderer { @Override public void encodeEnd(final FacesContext context, final UIComponent component) throws IOException { ResponseWriter writer = context.getResponseWriter(); QRCode qrCode = (QRCode) component; encodeMarkup(context, qrCode); encodeScript(context, qrCode); } protected void encodeScript(final FacesContext context, final QRCode qrCode) throws IOException { ResponseWriter writer = context.getResponseWriter(); String clientId = qrCode.getClientId(context); startScript(writer, clientId); - writer.write("$(function() {"); - writer.write("PrimeFacesExt.cw('QRCode', '" + qrCode.resolveWidgetVar() + "',{"); - WidgetRenderer.renderOptions(clientId, writer, qrCode); - writer.write("});});"); + WidgetRenderer.renderWidgetScript(context, clientId, writer, qrCode, false); endScript(writer); } private void encodeMarkup(FacesContext context, QRCode qrCode) throws IOException { ResponseWriter writer = context.getResponseWriter(); String clientId = qrCode.getClientId(context); writer.startElement("span", null); writer.writeAttribute("id", clientId, null); writer.endElement("span"); } @Override public void encodeChildren(final FacesContext context, final UIComponent component) throws IOException { //do nothing } @Override public boolean getRendersChildren() { return true; } }
true
true
protected void encodeScript(final FacesContext context, final QRCode qrCode) throws IOException { ResponseWriter writer = context.getResponseWriter(); String clientId = qrCode.getClientId(context); startScript(writer, clientId); writer.write("$(function() {"); writer.write("PrimeFacesExt.cw('QRCode', '" + qrCode.resolveWidgetVar() + "',{"); WidgetRenderer.renderOptions(clientId, writer, qrCode); writer.write("});});"); endScript(writer); }
protected void encodeScript(final FacesContext context, final QRCode qrCode) throws IOException { ResponseWriter writer = context.getResponseWriter(); String clientId = qrCode.getClientId(context); startScript(writer, clientId); WidgetRenderer.renderWidgetScript(context, clientId, writer, qrCode, false); endScript(writer); }
diff --git a/src/main/java/me/cmastudios/plugins/WarhubModChat/WarhubModChatListener.java b/src/main/java/me/cmastudios/plugins/WarhubModChat/WarhubModChatListener.java index 05945f9..8b4c278 100644 --- a/src/main/java/me/cmastudios/plugins/WarhubModChat/WarhubModChatListener.java +++ b/src/main/java/me/cmastudios/plugins/WarhubModChat/WarhubModChatListener.java @@ -1,272 +1,271 @@ package me.cmastudios.plugins.WarhubModChat; import java.util.ArrayList; import java.util.List; import me.cmastudios.plugins.WarhubModChat.util.Config; import me.cmastudios.plugins.WarhubModChat.util.Message; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.player.PlayerChatEvent; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.inventory.ItemStack; public class WarhubModChatListener implements Listener { public boolean nukerEnabled = false; public static WarhubModChat plugin; public WarhubModChatListener(WarhubModChat instance) { plugin = instance; } @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerChat(final PlayerChatEvent event) { Player player = event.getPlayer(); if (plugin.mutedplrs.containsKey(player.getName())) { event.setCancelled(true); player.sendMessage(ChatColor.RED + "You are muted."); return; } /* * Anti-spam removed due to bukkit built in anti spam */ event.setMessage(Capslock(player, event.getMessage())); ArrayList<Player> plrs = new ArrayList<Player>(); for (Player plr : plugin.getServer().getOnlinePlayers()) { if (plugin.ignores.containsKey(plr)) plrs.add(plr); } for (Player plr : plrs) { event.getRecipients().remove(plr); } if (event.getMessage().contains(ChatColor.COLOR_CHAR + "") && !player.hasPermission("warhub.moderator")) { event.setMessage(event.getMessage().replaceAll( ChatColor.COLOR_CHAR + "[0-9a-zA-Z]", "")); } if (plugin.channels.containsKey(event.getPlayer())) { if (DynmapManager.getDynmapCommonAPI() != null) DynmapManager.getDynmapCommonAPI() .setDisableChatToWebProcessing(true); if (plugin.channels.get(event.getPlayer()).equalsIgnoreCase("mod")) { event.setCancelled(true); sendToMods(Message .colorizeText(Config.config.getString("modchat-format")) .replace("%player", event.getPlayer().getDisplayName()) .replace("%message", event.getMessage())); plugin.log.info("[MODCHAT] " + event.getPlayer().getDisplayName() + ": " + event.getMessage()); } if (plugin.channels.get(event.getPlayer()) .equalsIgnoreCase("alert")) { event.setCancelled(true); Bukkit.getServer().broadcastMessage( Message.colorizeText( Config.config.getString("alert-format")) .replace("%player", event.getPlayer().getDisplayName()) .replace("%message", event.getMessage())); if (DynmapManager.getDynmapCommonAPI() != null) DynmapManager.getDynmapCommonAPI().sendBroadcastToWeb( "Attention", event.getMessage()); } } else { if (DynmapManager.getDynmapCommonAPI() != null) DynmapManager.getDynmapCommonAPI() .setDisableChatToWebProcessing(false); } } @EventHandler(priority = EventPriority.LOW) public void onPlayerJoin(final PlayerJoinEvent event) { plugin.channels.remove(event.getPlayer()); plugin.ignores.remove(event.getPlayer()); /* * Removed IP-logging due to multi-alt griefers not being much of a * problem anymore */ } @EventHandler public void onBlockBreak(final BlockBreakEvent event) { if (nukerEnabled) { if (WarhubModChat.blockbreaks.get(event.getPlayer()) == null) WarhubModChat.blockbreaks.put(event.getPlayer(), 0); int breaks = WarhubModChat.blockbreaks.get(event.getPlayer()); breaks++; WarhubModChat.blockbreaks.put(event.getPlayer(), breaks); if (breaks > Config.config.getInt("blockspersecond")) { event.setCancelled(true); plugin.getServer().dispatchCommand( plugin.getServer().getConsoleSender(), "kick " + event.getPlayer().getName() + " Do not use nuker hacks!"); } } } @EventHandler public void onBlockPlace(final BlockPlaceEvent event) { if (nukerEnabled) { if (WarhubModChat.blockbreaks.get(event.getPlayer()) == null) WarhubModChat.blockbreaks.put(event.getPlayer(), 0); int breaks = WarhubModChat.blockbreaks.get(event.getPlayer()); breaks++; WarhubModChat.blockbreaks.put(event.getPlayer(), breaks); if (breaks > Config.config.getInt("blockspersecond")) { event.getBlock().breakNaturally(); event.setCancelled(true); plugin.getServer().dispatchCommand( plugin.getServer().getConsoleSender(), "kick " + event.getPlayer().getName() + " Do not use fastplace hacks!"); } } } @EventHandler public void onPlayerCommandPreprocess( final PlayerCommandPreprocessEvent event) { String command = event.getMessage(); /* * Allow use of TooManyItems features */ if (command.startsWith("/toggledownfall")) { event.setCancelled(true); if (!event.getPlayer().hasPermission("essentials.weather")) { event.getPlayer().sendMessage( ChatColor.RED + "You don't have permission."); return; } if (event.getPlayer().getWorld().hasStorm()) { event.getPlayer().getWorld().setStorm(false); } else { event.getPlayer().getWorld().setStorm(true); } } if (command.startsWith("/time set")) { event.setCancelled(true); if (!event.getPlayer().hasPermission("essentials.time.set")) { event.getPlayer().sendMessage( ChatColor.RED + "You don't have permission."); return; } int ticks; try { ticks = Integer.parseInt(command.split(" ")[2]); event.getPlayer().getWorld().setTime(ticks); } catch (Exception e) { event.getPlayer().sendMessage(e.toString()); } } if (command.startsWith("/give")) { if (event.getPlayer().hasPermission("essentials.give")) return; event.setCancelled(true); if (!event.getPlayer().hasPermission("essentials.item")) { event.getPlayer().sendMessage( ChatColor.RED + "You don't have permission."); return; } try { - String player = command.split(" ")[1]; - if (Config.config.getBoolean("debug")) System.out.println("'"+player+"'"); + Player player = Bukkit.getPlayer(command.split(" ")[1]); int item = Integer.parseInt(command.split(" ")[2]); int amount = Integer.parseInt(command.split(" ")[3]); short data = Short.parseShort(command.split(" ")[4]); - if (event.getPlayer().getName().toLowerCase() != player.toLowerCase()) { + if (event.getPlayer() != player) { event.getPlayer().sendMessage( ChatColor.RED + "You may only give items to yourself"); return; } event.getPlayer().getInventory() .addItem(new ItemStack(item, amount, data)); } catch (Exception e) { event.getPlayer().sendMessage(e.toString()); } } } private String Capslock(Player player, String message) { int countChars = 0; int countCharsCaps = 0; if (!player.hasPermission("warhub.moderator")) { countChars = message.length(); if ((countChars > 0) && (countChars > 8)) { for (int i = 0; i < countChars; i++) { char c = message.charAt(i); String ch = Character.toString(c); if (ch.matches("[A-Z]")) { countCharsCaps++; } } if (100 / countChars * countCharsCaps >= 40) { // Message has too many capital letters message = message.toLowerCase(); plugin.warnings.put(player.getName(), getWarnings(player) + 1); if (getWarnings(player) % 50 == 0) { plugin.getServer().dispatchCommand( plugin.getServer().getConsoleSender(), "kick " + player.getName() + " Do not type in caps!"); plugin.getServer().dispatchCommand( plugin.getServer().getConsoleSender(), "tempban " + player.getName() + " 20m"); } else if (getWarnings(player) % 5 == 0) { plugin.getServer().dispatchCommand( plugin.getServer().getConsoleSender(), "kick " + player.getName() + " Do not type in caps!"); } else { player.sendMessage(ChatColor.YELLOW + "Do not type in all caps [" + getWarnings(player) + " Violations]"); sendToMods(ChatColor.DARK_RED + "[WHChat] " + ChatColor.WHITE + player.getDisplayName() + ChatColor.YELLOW + " all caps'd [" + getWarnings(player) + " Violations]"); } } } } return message; } private int getWarnings(Player key) { if (plugin.warnings.get(key.getName()) != null) { return plugin.warnings.get(key.getName()); } else { plugin.warnings.put(key.getName(), 0); } return 0; } private void sendToMods(String message) { List<Player> sendto = new ArrayList<Player>(); for (Player p : Bukkit.getServer().getOnlinePlayers()) { if (p.hasPermission("warhub.moderator")) { sendto.add(p); } } for (Player p : sendto) { p.sendMessage(message); } } }
false
true
public void onPlayerCommandPreprocess( final PlayerCommandPreprocessEvent event) { String command = event.getMessage(); /* * Allow use of TooManyItems features */ if (command.startsWith("/toggledownfall")) { event.setCancelled(true); if (!event.getPlayer().hasPermission("essentials.weather")) { event.getPlayer().sendMessage( ChatColor.RED + "You don't have permission."); return; } if (event.getPlayer().getWorld().hasStorm()) { event.getPlayer().getWorld().setStorm(false); } else { event.getPlayer().getWorld().setStorm(true); } } if (command.startsWith("/time set")) { event.setCancelled(true); if (!event.getPlayer().hasPermission("essentials.time.set")) { event.getPlayer().sendMessage( ChatColor.RED + "You don't have permission."); return; } int ticks; try { ticks = Integer.parseInt(command.split(" ")[2]); event.getPlayer().getWorld().setTime(ticks); } catch (Exception e) { event.getPlayer().sendMessage(e.toString()); } } if (command.startsWith("/give")) { if (event.getPlayer().hasPermission("essentials.give")) return; event.setCancelled(true); if (!event.getPlayer().hasPermission("essentials.item")) { event.getPlayer().sendMessage( ChatColor.RED + "You don't have permission."); return; } try { String player = command.split(" ")[1]; if (Config.config.getBoolean("debug")) System.out.println("'"+player+"'"); int item = Integer.parseInt(command.split(" ")[2]); int amount = Integer.parseInt(command.split(" ")[3]); short data = Short.parseShort(command.split(" ")[4]); if (event.getPlayer().getName().toLowerCase() != player.toLowerCase()) { event.getPlayer().sendMessage( ChatColor.RED + "You may only give items to yourself"); return; } event.getPlayer().getInventory() .addItem(new ItemStack(item, amount, data)); } catch (Exception e) { event.getPlayer().sendMessage(e.toString()); } } }
public void onPlayerCommandPreprocess( final PlayerCommandPreprocessEvent event) { String command = event.getMessage(); /* * Allow use of TooManyItems features */ if (command.startsWith("/toggledownfall")) { event.setCancelled(true); if (!event.getPlayer().hasPermission("essentials.weather")) { event.getPlayer().sendMessage( ChatColor.RED + "You don't have permission."); return; } if (event.getPlayer().getWorld().hasStorm()) { event.getPlayer().getWorld().setStorm(false); } else { event.getPlayer().getWorld().setStorm(true); } } if (command.startsWith("/time set")) { event.setCancelled(true); if (!event.getPlayer().hasPermission("essentials.time.set")) { event.getPlayer().sendMessage( ChatColor.RED + "You don't have permission."); return; } int ticks; try { ticks = Integer.parseInt(command.split(" ")[2]); event.getPlayer().getWorld().setTime(ticks); } catch (Exception e) { event.getPlayer().sendMessage(e.toString()); } } if (command.startsWith("/give")) { if (event.getPlayer().hasPermission("essentials.give")) return; event.setCancelled(true); if (!event.getPlayer().hasPermission("essentials.item")) { event.getPlayer().sendMessage( ChatColor.RED + "You don't have permission."); return; } try { Player player = Bukkit.getPlayer(command.split(" ")[1]); int item = Integer.parseInt(command.split(" ")[2]); int amount = Integer.parseInt(command.split(" ")[3]); short data = Short.parseShort(command.split(" ")[4]); if (event.getPlayer() != player) { event.getPlayer().sendMessage( ChatColor.RED + "You may only give items to yourself"); return; } event.getPlayer().getInventory() .addItem(new ItemStack(item, amount, data)); } catch (Exception e) { event.getPlayer().sendMessage(e.toString()); } } }
diff --git a/src/com/gushuley/utils/scheduler/dom/SchedulerContext.java b/src/com/gushuley/utils/scheduler/dom/SchedulerContext.java index 3c36520..f6296bf 100644 --- a/src/com/gushuley/utils/scheduler/dom/SchedulerContext.java +++ b/src/com/gushuley/utils/scheduler/dom/SchedulerContext.java @@ -1,37 +1,37 @@ package com.gushuley.utils.scheduler.dom; import com.gushuley.utils.Tools; import com.gushuley.utils.orm.impl.GenericContext; public class SchedulerContext extends GenericContext { public SchedulerContext(String scheduleDbJdni, String scheduler, String dbScheme) { this.scheduleDbJdni = scheduleDbJdni; this.scheduler = scheduler; this.dbScheme = dbScheme; registerMapper(JobDone.class, JobDoneMapper.class); registerMapper(JobDef.class, JobDefMapper.class); } private final String scheduleDbJdni; private final String scheduler; private final String dbScheme; public String getDbScheme() { if (Tools.isEmpty(dbScheme)) { - return dbScheme; + return ""; } else if (!dbScheme.trim().endsWith(".")) { return dbScheme + "."; } else { return dbScheme; } } public String getScheduler() { return scheduler; } public String getScheduleDbJdni() { return scheduleDbJdni; } }
true
true
public String getDbScheme() { if (Tools.isEmpty(dbScheme)) { return dbScheme; } else if (!dbScheme.trim().endsWith(".")) { return dbScheme + "."; } else { return dbScheme; } }
public String getDbScheme() { if (Tools.isEmpty(dbScheme)) { return ""; } else if (!dbScheme.trim().endsWith(".")) { return dbScheme + "."; } else { return dbScheme; } }
diff --git a/src/main/java/org/collectionspace/chain/controller/ChainRequest.java b/src/main/java/org/collectionspace/chain/controller/ChainRequest.java index cc3ac360..e531006d 100644 --- a/src/main/java/org/collectionspace/chain/controller/ChainRequest.java +++ b/src/main/java/org/collectionspace/chain/controller/ChainRequest.java @@ -1,136 +1,123 @@ package org.collectionspace.chain.controller; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.collectionspace.chain.util.BadRequestException; public class ChainRequest { private final static String SCHEMA_REF = "/objects/schema"; private final static String STORE_REF = "/objects"; private static final String usage="You must structure the requests like so: \n" + "GET "+SCHEMA_REF+"/%path-to-file-with-name% \n" + "GET "+STORE_REF+"/%path-to-file-with-name% \n" + "POST "+STORE_REF+"/%path-to-file-with-name% - note that data in body must be JSON \n"; private HttpServletRequest req; private HttpServletResponse res; private boolean is_get; private RequestType type; private String rest,body=null; private boolean create_not_overwrite=false,found=false; private void perhapsStartsWith(String what,RequestType rq,String path) throws BadRequestException { if(!path.startsWith(what)) return; // Nope, it doesn't // Yes it does type=rq; rest=path.substring(what.length()); if(rest.startsWith("/")) rest=rest.substring(1); // Capture body if(!is_get) { try { body=IOUtils.toString(req.getReader()); } catch (IOException e) { throw new BadRequestException("Cannot capture request body"); } } found=true; } public String getStoreURL(String which) { return STORE_REF+"/"+which; } /** Wrapper for requests for chain * * @param req the servlet request * @param res the servlet response * @throws BadRequestException cannot build valid chain request from servlet request */ public ChainRequest(HttpServletRequest req,HttpServletResponse res) throws BadRequestException { this.req=req; this.res=res; String path = req.getPathInfo(); // Regular URLs if(!found) perhapsStartsWith(SCHEMA_REF,RequestType.SCHEMA,path); if(!found) perhapsStartsWith(STORE_REF,RequestType.STORE,path); if(type==RequestType.STORE && "".equals(rest)) { // Blank means list type=RequestType.LIST; } String method=req.getMethod(); // Allow method to be overridden by params for testing - String p_method=req.getParameter("method"); - if(!StringUtils.isBlank(p_method)) { - method=p_method; - } is_get="GET".equals(method); if("POST".equals(method)) { create_not_overwrite=true; } // Mmm. Perhaps it's a non-get request with stuff in parameters. - if(!"GET".equals(method)) { - String qp_path=req.getParameter("storage"); - if(qp_path!=null && qp_path.startsWith(STORE_REF)) { - rest=qp_path.substring(STORE_REF.length()); - type=RequestType.STORE; - body=req.getParameter("json_str"); - return; - } - } if(!found) throw new BadRequestException("Invalid path "+path); if(path==null || "".equals(path)) throw new BadRequestException(usage); } /** What overall type is the request? ie controller selection. * * @return the type */ public RequestType getType() { return type; } /** What's the trailing path of the request? * * @return the trailing path, ie after controller selection. */ public String getPathTail() { return rest; } /** What's the request body? Either the real body, or the fake one from the query parameter. * * @return the body */ public String getBody() { return body; } /** Returns a printwriter for some JSON, having set up mime-type, etc, correctly. * * @return * @throws IOException */ public PrintWriter getJSONWriter() throws IOException { // Set response type to JSON res.setCharacterEncoding("UTF-8"); res.setContentType("application/json"); // Return JSON return res.getWriter(); } /** Method/params indicate data should be created at path, not updated * * @return */ public boolean isCreateNotOverwrite() { return create_not_overwrite; } }
false
true
public ChainRequest(HttpServletRequest req,HttpServletResponse res) throws BadRequestException { this.req=req; this.res=res; String path = req.getPathInfo(); // Regular URLs if(!found) perhapsStartsWith(SCHEMA_REF,RequestType.SCHEMA,path); if(!found) perhapsStartsWith(STORE_REF,RequestType.STORE,path); if(type==RequestType.STORE && "".equals(rest)) { // Blank means list type=RequestType.LIST; } String method=req.getMethod(); // Allow method to be overridden by params for testing String p_method=req.getParameter("method"); if(!StringUtils.isBlank(p_method)) { method=p_method; } is_get="GET".equals(method); if("POST".equals(method)) { create_not_overwrite=true; } // Mmm. Perhaps it's a non-get request with stuff in parameters. if(!"GET".equals(method)) { String qp_path=req.getParameter("storage"); if(qp_path!=null && qp_path.startsWith(STORE_REF)) { rest=qp_path.substring(STORE_REF.length()); type=RequestType.STORE; body=req.getParameter("json_str"); return; } } if(!found) throw new BadRequestException("Invalid path "+path); if(path==null || "".equals(path)) throw new BadRequestException(usage); }
public ChainRequest(HttpServletRequest req,HttpServletResponse res) throws BadRequestException { this.req=req; this.res=res; String path = req.getPathInfo(); // Regular URLs if(!found) perhapsStartsWith(SCHEMA_REF,RequestType.SCHEMA,path); if(!found) perhapsStartsWith(STORE_REF,RequestType.STORE,path); if(type==RequestType.STORE && "".equals(rest)) { // Blank means list type=RequestType.LIST; } String method=req.getMethod(); // Allow method to be overridden by params for testing is_get="GET".equals(method); if("POST".equals(method)) { create_not_overwrite=true; } // Mmm. Perhaps it's a non-get request with stuff in parameters. if(!found) throw new BadRequestException("Invalid path "+path); if(path==null || "".equals(path)) throw new BadRequestException(usage); }
diff --git a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/impl/raptor/Raptor.java b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/impl/raptor/Raptor.java index ca64720e2..2693e1620 100644 --- a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/impl/raptor/Raptor.java +++ b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/impl/raptor/Raptor.java @@ -1,759 +1,762 @@ /* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 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.opentripplanner.routing.impl.raptor; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.opentripplanner.common.geometry.DistanceLibrary; import org.opentripplanner.common.geometry.SphericalDistanceLibrary; import org.opentripplanner.common.model.T2; import org.opentripplanner.common.pqueue.BinHeap; import org.opentripplanner.common.pqueue.OTPPriorityQueue; import org.opentripplanner.common.pqueue.OTPPriorityQueueFactory; import org.opentripplanner.routing.algorithm.GenericDijkstra; import org.opentripplanner.routing.algorithm.strategies.TransitLocalStreetService; import org.opentripplanner.routing.core.RoutingRequest; import org.opentripplanner.routing.core.ServiceDay; import org.opentripplanner.routing.core.State; import org.opentripplanner.routing.core.StateEditor; import org.opentripplanner.routing.core.TraverseModeSet; import org.opentripplanner.routing.edgetype.Board; import org.opentripplanner.routing.edgetype.PatternAlight; import org.opentripplanner.routing.edgetype.PatternBoard; import org.opentripplanner.routing.edgetype.PatternDwell; import org.opentripplanner.routing.edgetype.PatternHop; import org.opentripplanner.routing.edgetype.PreAlightEdge; import org.opentripplanner.routing.edgetype.PreBoardEdge; import org.opentripplanner.routing.graph.Edge; import org.opentripplanner.routing.graph.Graph; import org.opentripplanner.routing.graph.Vertex; import org.opentripplanner.routing.impl.SkipNonTransferEdgeStrategy; import org.opentripplanner.routing.pathparser.BasicPathParser; import org.opentripplanner.routing.pathparser.PathParser; import org.opentripplanner.routing.services.GraphService; import org.opentripplanner.routing.services.PathService; import org.opentripplanner.routing.spt.GraphPath; import org.opentripplanner.routing.spt.MultiShortestPathTree; import org.opentripplanner.routing.spt.ShortestPathTree; import org.opentripplanner.routing.spt.ShortestPathTreeFactory; import org.opentripplanner.routing.vertextype.TransitStop; import org.springframework.beans.factory.annotation.Autowired; public class Raptor implements PathService { static final double MAX_TRANSIT_SPEED = 25; @Autowired private GraphService graphService; private DistanceLibrary distanceLibrary = SphericalDistanceLibrary.getInstance(); private List<ServiceDay> cachedServiceDays; private RaptorData cachedRaptorData; @Override public List<GraphPath> getPaths(RoutingRequest options) { if (options.rctx == null) { options.setRoutingContext(graphService.getGraph(options.getRouterId())); options.rctx.pathParsers = new PathParser[1]; options.rctx.pathParsers[0] = new BasicPathParser(); } Graph graph = graphService.getGraph(options.getRouterId()); RaptorData data = graph.getService(RaptorDataService.class).getData(); /* this does not actually affect speed either way (perhaps unfortunately) options.setAlightSlack(120); options.setBoardSlack(120); options.setTransferSlack(240); */ RoutingRequest walkOptions = options.clone(); walkOptions.rctx.pathParsers = new PathParser[0]; TraverseModeSet modes = options.getModes().clone(); modes.setTransit(false); walkOptions.setModes(modes); RaptorPathSet routeSet = new RaptorPathSet(data.stops.length); options.maxTransfers += 2; for (int i = 0; i < options.getMaxTransfers() + 2; ++i) { round(data, options, walkOptions, routeSet, i); /* * if (routeSet.getTargetStates().size() >= options.getNumItineraries()) break; */ } if (routeSet.getTargetStates().isEmpty()) { System.out.println("RAPTOR found no paths (try retrying?)"); } List<GraphPath> paths = new ArrayList<GraphPath>(); for (RaptorState targetState : routeSet.getTargetStates()) { // reconstruct path ArrayList<RaptorState> states = new ArrayList<RaptorState>(); RaptorState cur = targetState; while (cur != null) { states.add(cur); cur = cur.parent; } // states is in reverse order of time State state = new State(options); for (int i = states.size() - 1; i >= 0; --i) { cur = states.get(i); if (cur.walkPath != null) { GraphPath path = new GraphPath(cur.walkPath, true); for (Edge e : path.edges) { State oldState = state; state = e.traverse(state); if (state == null) { e.traverse(oldState); } } } else { // so, cur is at this point at a transit stop; we have a route to board for (Edge e : state.getVertex().getOutgoing()) { if (e instanceof PreBoardEdge) { state = e.traverse(state); } } PatternBoard board = cur.route.boards[cur.boardStopSequence][cur.patternIndex]; State oldState = state; state = board.traverse(state); if (state == null) { state = board.traverse(oldState); } // now traverse the hops and dwells until we find the alight we're looking for HOP: while (true) { for (Edge e : state.getVertex().getOutgoing()) { if (e instanceof PatternDwell) { state = e.traverse(state); } else if (e instanceof PatternHop) { state = e.traverse(state); for (Edge e2 : state.getVertex().getOutgoing()) { if (e2 instanceof PatternAlight) { for (Edge e3 : e2.getToVertex().getOutgoing()) { if (e3 instanceof PreAlightEdge) { if (data.raptorStopsForStopId.get(((TransitStop) e3 .getToVertex()).getStopId()) == cur.stop) { state = e2.traverse(state); state = e3.traverse(state); break HOP; } } } } } } } } } } paths.add(new GraphPath(state, true)); } return paths; } /** * Prune raptor data to include only routes and boardings which have trips today. * Doesn't actually improve speed */ private RaptorData pruneDataForServiceDays(Graph graph, ArrayList<ServiceDay> serviceDays) { if (serviceDays.equals(cachedServiceDays)) return cachedRaptorData; //you are here: need to reduce list of boards RaptorData data = graph.getService(RaptorDataService.class).getData(); RaptorData pruned = new RaptorData(); pruned.raptorStopsForStopId = data.raptorStopsForStopId; pruned.stops = data.stops; pruned.routes = new ArrayList<RaptorRoute>(); pruned.routesForStop = new List[pruned.stops.length]; for (RaptorRoute route : data.routes) { ArrayList<Integer> keep = new ArrayList<Integer>(); for (int i = 0; i < route.boards[0].length; ++i) { Edge board = route.boards[0][i]; int serviceId; if (board instanceof PatternBoard) { serviceId = ((PatternBoard) board).getPattern().getServiceId(); } else if (board instanceof Board) { serviceId = ((Board) board).getServiceId(); } else { System.out.println("Unexpected nonboard among boards"); continue; } for (ServiceDay day : serviceDays) { if (day.serviceIdRunning(serviceId)) { keep.add(i); break; } } } if (keep.isEmpty()) continue; int nPatterns = keep.size(); RaptorRoute prunedRoute = new RaptorRoute(route.getNStops(), nPatterns); for (int stop = 0; stop < route.getNStops() - 1; ++stop) { for (int pattern = 0; pattern < nPatterns; ++pattern) { prunedRoute.boards[stop][pattern] = route.boards[stop][keep.get(pattern)]; } } pruned.routes.add(route); for (RaptorStop stop : route.stops) { List<RaptorRoute> routes = pruned.routesForStop[stop.index]; if (routes == null) { routes = new ArrayList<RaptorRoute>(); pruned.routesForStop[stop.index] = routes; } routes.add(route); } } for (RaptorStop stop : data.stops) { if (pruned.routesForStop[stop.index] == null) { pruned.routesForStop[stop.index] = Collections.emptyList(); } } cachedServiceDays = serviceDays; cachedRaptorData = pruned; return pruned; } private void round(RaptorData data, RoutingRequest options, RoutingRequest walkOptions, final RaptorPathSet cur, int nBoardings) { Set<RaptorStop> visitedLastRound = cur.visitedLastRound; Set<RaptorRoute> routesToVisit = new HashSet<RaptorRoute>(); for (RaptorStop stop : visitedLastRound) { for (RaptorRoute route : data.routesForStop[stop.index]) { routesToVisit.add(route); } } cur.visitedLastRound = new HashSet<RaptorStop>(); // RoutingContext rctx = walkOptions.rctx; List<RaptorState>[] statesByStop = cur.getStates(); /* * RaptorPathSet cur = new RaptorPathSet(prev.getNStops()); List<RaptorState>[] statesByStop * = prev.getStates(); for (int stop = 0; stop < statesByStop.length; ++stop) { * * //The first stage of round k sets τk (p) = τk−1 (p) f or all stops p: this sets an * //upper bound on the earliest arrival time at p with at most k trips. if * (statesByStop[stop] != null) { System.out.println("filling in for " + stop + ": " + * statesByStop[stop].size()); } cur.addStates(stop, statesByStop[stop]); } */ /* * Consider a route r, and let T (r) = (t0 , t1 , . . . , t|T (r)|−1 ) be the sequence of * trips that follow route r, from earliest to latest. When processing route r, we consider * journeys where the last (k’th) trip taken is in route r. Let et(r, pi ) be the earliest * trip in route r that one can catch at stop pi , i. e., the earliest trip t such that τdep * (t, pi ) ≥ τk−1 (pi ). (Note that this trip may not exist, in which case et(r, pi ) is * undefined.) To process the route, we visit its stops in order until we find a stop pi * such that et(r, pi ) is defined. This is when we can “hop on” the route. Let the * corresponding trip t be the current trip for k. We keep traversing the route. For each * subsequent stop pj , we can update τk (pj ) using this trip. To reconstruct the journey, * we set a parent pointer to the stop at which t was boarded. Moreover, we may need to * update the current trip for k: at each stop pi along r it may be possible to catch an * earlier trip (because a quicker path to pi has been found in a previous round). Thus, we * have to check if τk−1 (pi ) < τarr (t, pi ) and update t by recomputing et(r, pi ). */ int boardSlack = nBoardings == 1 ? options.getBoardSlack() : (options.getTransferSlack() - options.getAlightSlack()); List<RaptorState> createdStates = new ArrayList<RaptorState>(); System.out.println("Round " + nBoardings); final double distanceToNearestTransitStop = options.rctx.target .getDistanceToNearestTransitStop(); for (RaptorRoute route : routesToVisit) { List<RaptorState> boardStates = new ArrayList<RaptorState>(); // not really states boolean started = false; for (int stopNo = 0; stopNo < route.getNStops(); ++stopNo) { // find the current time at this stop RaptorStop stop = route.stops[stopNo]; if (!started && !visitedLastRound.contains(stop)) continue; started = true; List<RaptorState> states = statesByStop[stop.index]; List<RaptorState> newStates = new ArrayList<RaptorState>(); if (states == null) { states = new ArrayList<RaptorState>(); statesByStop[stop.index] = states; } // this checks the case of continuing on the current trips. CONTINUE: for (RaptorState boardState : boardStates) { RaptorState newState = new RaptorState(); ServiceDay sd = boardState.serviceDay; int alightTime = route.getAlightTime(boardState.patternIndex, boardState.tripIndex, stopNo); newState.arrivalTime = (int) sd.time(alightTime); //add in slack newState.arrivalTime += options.getAlightSlack(); newState.boardStop = boardState.boardStop; newState.boardStopSequence = boardState.boardStopSequence; newState.route = route; newState.patternIndex = boardState.patternIndex; newState.tripIndex = boardState.tripIndex; newState.nBoardings = boardState.nBoardings; newState.walkDistance = boardState.walkDistance; newState.parent = boardState.parent; newState.stop = stop; // todo: waiting time, which presently is not handled for (RaptorState oldState : states) { if (eDominates(oldState, newState)) { continue CONTINUE; } } for (RaptorState oldState : newStates) { if (oldState != newState && eDominates(oldState, newState)) { continue CONTINUE; } } Iterator<RaptorState> it = states.iterator(); while(it.hasNext()) { RaptorState oldState = it.next(); if (eDominates(newState, oldState)) { it.remove(); } } it = newStates.iterator(); while(it.hasNext()) { RaptorState oldState = it.next(); if (eDominates(newState, oldState)) { it.remove(); } } cur.visitedLastRound.add(stop); cur.visitedEver.add(stop); newStates.add(newState); StopNearTarget nearTarget = cur.stopsNearTarget.get(stop); if (nearTarget != null) { RaptorState bound = new RaptorState(); bound.arrivalTime = newState.arrivalTime + nearTarget.time; bound.walkDistance = newState.walkDistance + nearTarget.walkDistance; if (bound.walkDistance <= options.maxWalkDistance) { bound.nBoardings = newState.nBoardings; bound.stop = stop; for (RaptorState oldBound : cur.boundingStates) { if (eDominates(oldBound, bound)) { continue CONTINUE; } } cur.boundingStates.add(bound); } } } if (newStates.size() > 10) { // System.out.println("HERE: " + newStates.size()); } if (stopNo < route.getNStops() - 1) { if (stop.stopVertex.isLocal() && nBoardings > 1) { // cannot transfer at a local stop continue; } // try boarding here TRYBOARD: for (RaptorState oldState : states) { if (oldState.nBoardings != nBoardings - 1) continue; if (oldState.route == route) continue; // we got here via this route, so no reason to transfer RaptorBoardSpec boardSpec = route.getTripIndex(options, oldState.arrivalTime + boardSlack, stopNo); if (boardSpec == null) continue; RaptorState boardState = new RaptorState(); boardState.nBoardings = nBoardings; boardState.boardStop = stop; boardState.boardStopSequence = stopNo; boardState.arrivalTime = boardSpec.departureTime; boardState.patternIndex = boardSpec.patternIndex; boardState.tripIndex = boardSpec.tripIndex; boardState.parent = oldState; boardState.serviceDay = boardSpec.serviceDay; boardState.route = route; boardState.walkDistance = oldState.walkDistance; for (RaptorState state : newStates) { if (eDominates(state, boardState)) { continue TRYBOARD; } } for (RaptorState state : states) { if (state != oldState && eDominates(state, boardState)) { continue TRYBOARD; } } boardStates.add(boardState); } } createdStates.addAll(newStates); states.addAll(newStates); } } /* * finally, the third stage of round k considers foot- paths. For each foot-path (pi , pj ) * ∈ F it sets τk (pj ) = min{τk (pj ), τk (pi ) + (pi , pj )}. Note that since F is * transitive, we always find the fastest walking path, if one exists. */ ShortestPathTree spt; GenericDijkstra dijkstra = new GenericDijkstra(walkOptions); if (nBoardings == 0) { State start = new MaxWalkState(options.rctx.origin, walkOptions); spt = dijkstra.getShortestPathTree(start); // also, compute an initial spt from the target so that we can find out what transit // stops are nearby and what // the time is to them, so that we can start target bounding earlier RoutingRequest reversedWalkOptions = walkOptions.clone(); reversedWalkOptions.setArriveBy(true); GenericDijkstra destDijkstra = new GenericDijkstra(reversedWalkOptions); start = new MaxWalkState(options.rctx.target, reversedWalkOptions); ShortestPathTree targetSpt = destDijkstra.getShortestPathTree(start); for (State state : targetSpt.getAllStates()) { final Vertex vertex = state.getVertex(); if (!(vertex instanceof TransitStop)) continue; RaptorStop stop = data.raptorStopsForStopId.get(((TransitStop) vertex).getStopId()); if (stop == null) { // we have found a stop is totally unused, so skip it continue; } cur.addStopNearTarget(stop, state.getWalkDistance(), (int) state.getElapsedTime()); } } else { if (options.rctx.graph.getService(TransitLocalStreetService.class) != null) dijkstra.setSkipEdgeStrategy(new SkipNonTransferEdgeStrategy(options)); final List<State> startPoints = new ArrayList<State>(); /* RegionData regionData = data.regionData; List<Integer> destinationRegions = regionData.getRegionsForVertex(options.rctx.target); List<double[]> minWalks = new ArrayList<double[]>(2); for (int destinationRegion : destinationRegions) { minWalks.add(regionData.minWalk[destinationRegion]); } */ STARTWALK: for (RaptorState state : createdStates) { if (false) { double maxWalk = options.getMaxWalkDistance() - state.walkDistance - distanceToNearestTransitStop; CHECK: for (T2<Double, RaptorStop> nearby : data.nearbyStops[state.stop.index]) { double distance = nearby.getFirst(); RaptorStop stop = nearby.getSecond(); if (distance > maxWalk) { // System.out.println("SKIPPED STATE: " + // state.stop.stopVertex.getName()); // this is technically wrong because these distances are not exact continue STARTWALK; } double minWalk = distance + state.walkDistance; int minArrive = (int) (state.arrivalTime + distance / options.getSpeedUpperBound()); if (statesByStop[stop.index] == null) { break CHECK; // we have never visited this stop, and we ought to } for (RaptorState other : statesByStop[stop.index]) { if (other.nBoardings == nBoardings - 1 && (other.walkDistance > minWalk || other.arrivalTime > minArrive)) { break CHECK; } } } } // bounding states // this reduces the number of initial vertices // and the state space size Vertex stopVertex = state.stop.stopVertex; Vertex dest = options.rctx.target; double minWalk = distanceToNearestTransitStop; double targetDistance = distanceLibrary.fastDistance(dest.getCoordinate(), stopVertex.getCoordinate()); double minTime = (targetDistance - minWalk) / MAX_TRANSIT_SPEED + minWalk / options.getSpeedUpperBound(); if (targetDistance + state.walkDistance > options.getMaxWalkDistance()) { // can't walk to destination, so we can't alight at a local vertex if (state.stop.stopVertex.isLocal()) continue; //and must account for another boarding minTime += boardSlack; } //this checks the precomputed table of walk distances by regions to see //to get a tigher bound on the best posible walk distance to the destination //it (a) causes weird intermitten planner failures, (b) does not make //much of a difference /* double minWalk = Double.MAX_VALUE; int index = stopVertex.getIndex(); int fromRegion = regionData.regionForVertex[index]; if (fromRegion == -1) { minWalk = distanceToNearestTransitStop; //System.out.println("unexpected missing minwalk for " + stopVertex); } else { for (double[] byRegion : minWalks) { double distanceFromThisRegion = byRegion[fromRegion]; if (minWalk > distanceFromThisRegion) { minWalk = distanceFromThisRegion; } } } if (minWalk == Double.MAX_VALUE) { //I don't believe you System.out.println("WRONG"); } */ state.arrivalTime += minTime; state.walkDistance += minWalk; for (RaptorState bound : cur.boundingStates) { + if (bound == state) { + break; //do not eliminate bounding states + } if (eDominates(bound, state)) { state.arrivalTime -= minTime; state.walkDistance -= minWalk; continue STARTWALK; } } state.arrivalTime -= minTime; state.walkDistance -= minWalk; //this bit of code was a test to see if drastically bounding the number of //states explored would help; it does, but this code way overprunes. /* * if (!cur.boundingStates.isEmpty()) { boolean found = false; OUTER: for * (RaptorState bound : cur.boundingStates) { for (RaptorRoute route : * routesForStop[bound.stop.index]) { for (RaptorStop stop : route.stops) { if (stop * == state.stop) { found = true; break OUTER; } } } } if (!found) continue; } */ // end bounding states if (minWalk + state.walkDistance > options.getMaxWalkDistance()) { continue; } StateEditor dijkstraState = new MaxWalkState.MaxWalkStateEditor(walkOptions, stopVertex); dijkstraState.setNumBoardings(state.nBoardings); dijkstraState.setWalkDistance(state.walkDistance); dijkstraState.setTime(state.arrivalTime); dijkstraState.setExtension("raptorParent", state); dijkstraState.setOptions(walkOptions); dijkstraState.incrementWeight(state.arrivalTime - options.dateTime); startPoints.add(dijkstraState.makeState()); } if (startPoints.size() == 0) { System.out.println("warning: no walk in round " + nBoardings); return; } System.out.println("walk starts: " + startPoints.size() + " / " + cur.visitedEver.size()); dijkstra.setPriorityQueueFactory(new PrefilledPriorityQueueFactory(startPoints.subList( 1, startPoints.size()))); dijkstra.setShortestPathTreeFactory(new ShortestPathTreeFactory() { @Override public ShortestPathTree create(RoutingRequest options) { ShortestPathTree result; if (cur.spt == null) { result = new MultiShortestPathTree(options); } else { result = cur.spt; } for (State state : startPoints.subList(1, startPoints.size())) { result.add(state); } return result; } }); //TODO: include existing bounding states final TargetBound bounder = new TargetBound(options.rctx.target, cur.dijkstraBoundingStates); dijkstra.setSearchTerminationStrategy(bounder); dijkstra.setSkipTraverseResultStrategy(bounder); spt = dijkstra.getShortestPathTree(startPoints.get(0)); if (!bounder.bounders.isEmpty()) { cur.dijkstraBoundingStates = bounder.bounders; } if (cur.spt == null) cur.spt = spt; } final List<? extends State> targetStates = spt.getStates(walkOptions.rctx.target); if (targetStates != null) { TARGET: for (State targetState : targetStates) { RaptorState state = new RaptorState(); RaptorState parent = (RaptorState) targetState.getExtension("raptorParent"); state.parent = parent; state.walkDistance = targetState.getWalkDistance(); state.arrivalTime = (int) targetState.getTime(); if (parent != null) { state.nBoardings = parent.nBoardings; state.waitingTime = parent.waitingTime; } state.walkPath = targetState; for (RaptorState oldState : cur.getTargetStates()) { if (eDominates(oldState, state)) { continue TARGET; } } cur.addTargetState(state); System.out.println("TARGET: " + state); } } SPTSTATE: for (State state : spt.getAllStates()) { final Vertex vertex = state.getVertex(); if (!(vertex instanceof TransitStop)) continue; RaptorStop stop = data.raptorStopsForStopId.get(((TransitStop) vertex).getStopId()); if (stop == null) { // we have found a stop is totally unused, so skip it continue; } List<RaptorState> states = statesByStop[stop.index]; if (states == null) { states = new ArrayList<RaptorState>(); statesByStop[stop.index] = states; } double minWalk = distanceToNearestTransitStop; RaptorState baseState = (RaptorState) state.getExtension("raptorParent"); RaptorState newState = new RaptorState(); if (baseState != null) { newState.nBoardings = baseState.nBoardings; } newState.walkDistance = state.getWalkDistance(); newState.arrivalTime = (int) state.getTime(); newState.walkPath = state; newState.parent = baseState; newState.stop = stop; for (RaptorState oldState : states) { if (eDominates(oldState, newState)) { continue SPTSTATE; } } double targetDistance = distanceLibrary.fastDistance( options.rctx.target.getCoordinate(), vertex.getCoordinate()); double minTime = (targetDistance - minWalk) / MAX_TRANSIT_SPEED + minWalk / options.getSpeedUpperBound(); if (targetDistance > options.maxWalkDistance - state.getWalkDistance()) minTime += boardSlack; // target state bounding for (RaptorState oldState : cur.getTargetStates()) { // newstate would have to take some transit and then walk to the destination. if (oldState.arrivalTime <= newState.arrivalTime + minTime && oldState.walkDistance <= newState.walkDistance + minWalk) // todo waiting time? continue SPTSTATE; // newstate will arrive way too late (this is a hack) if ((oldState.arrivalTime - options.dateTime) * 3 <= (newState.arrivalTime + minTime - options.dateTime)) continue SPTSTATE; } cur.visitedLastRound.add(stop); cur.visitedEver.add(stop); states.add(newState); } // fill in for (int stop = 0; stop < statesByStop.length; ++stop) { cur.setStates(stop, statesByStop[stop]); } } class PrefilledPriorityQueueFactory implements OTPPriorityQueueFactory { private List<State> startPoints; public PrefilledPriorityQueueFactory(List<State> startPoints) { this.startPoints = startPoints; } @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public <T> OTPPriorityQueue<T> create(int maxSize) { BinHeap heap = new BinHeap<T>(); for (State state : startPoints) { heap.insert(state, 0); } return heap; } } private boolean eDominates(RaptorState state, RaptorState oldState) { // todo: epsilon dominance? return state.nBoardings <= oldState.nBoardings && state.waitingTime <= oldState.waitingTime && state.walkDistance <= oldState.walkDistance && state.arrivalTime <= oldState.arrivalTime /* * && (state.nBoardings < oldState.nBoardings || state.waitingTime < oldState.waitingTime || * state.walkDistance < oldState.walkDistance || state.arrivalTime < oldState.arrivalTime); */; } }
true
true
private void round(RaptorData data, RoutingRequest options, RoutingRequest walkOptions, final RaptorPathSet cur, int nBoardings) { Set<RaptorStop> visitedLastRound = cur.visitedLastRound; Set<RaptorRoute> routesToVisit = new HashSet<RaptorRoute>(); for (RaptorStop stop : visitedLastRound) { for (RaptorRoute route : data.routesForStop[stop.index]) { routesToVisit.add(route); } } cur.visitedLastRound = new HashSet<RaptorStop>(); // RoutingContext rctx = walkOptions.rctx; List<RaptorState>[] statesByStop = cur.getStates(); /* * RaptorPathSet cur = new RaptorPathSet(prev.getNStops()); List<RaptorState>[] statesByStop * = prev.getStates(); for (int stop = 0; stop < statesByStop.length; ++stop) { * * //The first stage of round k sets τk (p) = τk−1 (p) f or all stops p: this sets an * //upper bound on the earliest arrival time at p with at most k trips. if * (statesByStop[stop] != null) { System.out.println("filling in for " + stop + ": " + * statesByStop[stop].size()); } cur.addStates(stop, statesByStop[stop]); } */ /* * Consider a route r, and let T (r) = (t0 , t1 , . . . , t|T (r)|−1 ) be the sequence of * trips that follow route r, from earliest to latest. When processing route r, we consider * journeys where the last (k’th) trip taken is in route r. Let et(r, pi ) be the earliest * trip in route r that one can catch at stop pi , i. e., the earliest trip t such that τdep * (t, pi ) ≥ τk−1 (pi ). (Note that this trip may not exist, in which case et(r, pi ) is * undefined.) To process the route, we visit its stops in order until we find a stop pi * such that et(r, pi ) is defined. This is when we can “hop on” the route. Let the * corresponding trip t be the current trip for k. We keep traversing the route. For each * subsequent stop pj , we can update τk (pj ) using this trip. To reconstruct the journey, * we set a parent pointer to the stop at which t was boarded. Moreover, we may need to * update the current trip for k: at each stop pi along r it may be possible to catch an * earlier trip (because a quicker path to pi has been found in a previous round). Thus, we * have to check if τk−1 (pi ) < τarr (t, pi ) and update t by recomputing et(r, pi ). */ int boardSlack = nBoardings == 1 ? options.getBoardSlack() : (options.getTransferSlack() - options.getAlightSlack()); List<RaptorState> createdStates = new ArrayList<RaptorState>(); System.out.println("Round " + nBoardings); final double distanceToNearestTransitStop = options.rctx.target .getDistanceToNearestTransitStop(); for (RaptorRoute route : routesToVisit) { List<RaptorState> boardStates = new ArrayList<RaptorState>(); // not really states boolean started = false; for (int stopNo = 0; stopNo < route.getNStops(); ++stopNo) { // find the current time at this stop RaptorStop stop = route.stops[stopNo]; if (!started && !visitedLastRound.contains(stop)) continue; started = true; List<RaptorState> states = statesByStop[stop.index]; List<RaptorState> newStates = new ArrayList<RaptorState>(); if (states == null) { states = new ArrayList<RaptorState>(); statesByStop[stop.index] = states; } // this checks the case of continuing on the current trips. CONTINUE: for (RaptorState boardState : boardStates) { RaptorState newState = new RaptorState(); ServiceDay sd = boardState.serviceDay; int alightTime = route.getAlightTime(boardState.patternIndex, boardState.tripIndex, stopNo); newState.arrivalTime = (int) sd.time(alightTime); //add in slack newState.arrivalTime += options.getAlightSlack(); newState.boardStop = boardState.boardStop; newState.boardStopSequence = boardState.boardStopSequence; newState.route = route; newState.patternIndex = boardState.patternIndex; newState.tripIndex = boardState.tripIndex; newState.nBoardings = boardState.nBoardings; newState.walkDistance = boardState.walkDistance; newState.parent = boardState.parent; newState.stop = stop; // todo: waiting time, which presently is not handled for (RaptorState oldState : states) { if (eDominates(oldState, newState)) { continue CONTINUE; } } for (RaptorState oldState : newStates) { if (oldState != newState && eDominates(oldState, newState)) { continue CONTINUE; } } Iterator<RaptorState> it = states.iterator(); while(it.hasNext()) { RaptorState oldState = it.next(); if (eDominates(newState, oldState)) { it.remove(); } } it = newStates.iterator(); while(it.hasNext()) { RaptorState oldState = it.next(); if (eDominates(newState, oldState)) { it.remove(); } } cur.visitedLastRound.add(stop); cur.visitedEver.add(stop); newStates.add(newState); StopNearTarget nearTarget = cur.stopsNearTarget.get(stop); if (nearTarget != null) { RaptorState bound = new RaptorState(); bound.arrivalTime = newState.arrivalTime + nearTarget.time; bound.walkDistance = newState.walkDistance + nearTarget.walkDistance; if (bound.walkDistance <= options.maxWalkDistance) { bound.nBoardings = newState.nBoardings; bound.stop = stop; for (RaptorState oldBound : cur.boundingStates) { if (eDominates(oldBound, bound)) { continue CONTINUE; } } cur.boundingStates.add(bound); } } } if (newStates.size() > 10) { // System.out.println("HERE: " + newStates.size()); } if (stopNo < route.getNStops() - 1) { if (stop.stopVertex.isLocal() && nBoardings > 1) { // cannot transfer at a local stop continue; } // try boarding here TRYBOARD: for (RaptorState oldState : states) { if (oldState.nBoardings != nBoardings - 1) continue; if (oldState.route == route) continue; // we got here via this route, so no reason to transfer RaptorBoardSpec boardSpec = route.getTripIndex(options, oldState.arrivalTime + boardSlack, stopNo); if (boardSpec == null) continue; RaptorState boardState = new RaptorState(); boardState.nBoardings = nBoardings; boardState.boardStop = stop; boardState.boardStopSequence = stopNo; boardState.arrivalTime = boardSpec.departureTime; boardState.patternIndex = boardSpec.patternIndex; boardState.tripIndex = boardSpec.tripIndex; boardState.parent = oldState; boardState.serviceDay = boardSpec.serviceDay; boardState.route = route; boardState.walkDistance = oldState.walkDistance; for (RaptorState state : newStates) { if (eDominates(state, boardState)) { continue TRYBOARD; } } for (RaptorState state : states) { if (state != oldState && eDominates(state, boardState)) { continue TRYBOARD; } } boardStates.add(boardState); } } createdStates.addAll(newStates); states.addAll(newStates); } } /* * finally, the third stage of round k considers foot- paths. For each foot-path (pi , pj ) * ∈ F it sets τk (pj ) = min{τk (pj ), τk (pi ) + (pi , pj )}. Note that since F is * transitive, we always find the fastest walking path, if one exists. */ ShortestPathTree spt; GenericDijkstra dijkstra = new GenericDijkstra(walkOptions); if (nBoardings == 0) { State start = new MaxWalkState(options.rctx.origin, walkOptions); spt = dijkstra.getShortestPathTree(start); // also, compute an initial spt from the target so that we can find out what transit // stops are nearby and what // the time is to them, so that we can start target bounding earlier RoutingRequest reversedWalkOptions = walkOptions.clone(); reversedWalkOptions.setArriveBy(true); GenericDijkstra destDijkstra = new GenericDijkstra(reversedWalkOptions); start = new MaxWalkState(options.rctx.target, reversedWalkOptions); ShortestPathTree targetSpt = destDijkstra.getShortestPathTree(start); for (State state : targetSpt.getAllStates()) { final Vertex vertex = state.getVertex(); if (!(vertex instanceof TransitStop)) continue; RaptorStop stop = data.raptorStopsForStopId.get(((TransitStop) vertex).getStopId()); if (stop == null) { // we have found a stop is totally unused, so skip it continue; } cur.addStopNearTarget(stop, state.getWalkDistance(), (int) state.getElapsedTime()); } } else { if (options.rctx.graph.getService(TransitLocalStreetService.class) != null) dijkstra.setSkipEdgeStrategy(new SkipNonTransferEdgeStrategy(options)); final List<State> startPoints = new ArrayList<State>(); /* RegionData regionData = data.regionData; List<Integer> destinationRegions = regionData.getRegionsForVertex(options.rctx.target); List<double[]> minWalks = new ArrayList<double[]>(2); for (int destinationRegion : destinationRegions) { minWalks.add(regionData.minWalk[destinationRegion]); } */ STARTWALK: for (RaptorState state : createdStates) { if (false) { double maxWalk = options.getMaxWalkDistance() - state.walkDistance - distanceToNearestTransitStop; CHECK: for (T2<Double, RaptorStop> nearby : data.nearbyStops[state.stop.index]) { double distance = nearby.getFirst(); RaptorStop stop = nearby.getSecond(); if (distance > maxWalk) { // System.out.println("SKIPPED STATE: " + // state.stop.stopVertex.getName()); // this is technically wrong because these distances are not exact continue STARTWALK; } double minWalk = distance + state.walkDistance; int minArrive = (int) (state.arrivalTime + distance / options.getSpeedUpperBound()); if (statesByStop[stop.index] == null) { break CHECK; // we have never visited this stop, and we ought to } for (RaptorState other : statesByStop[stop.index]) { if (other.nBoardings == nBoardings - 1 && (other.walkDistance > minWalk || other.arrivalTime > minArrive)) { break CHECK; } } } } // bounding states // this reduces the number of initial vertices // and the state space size Vertex stopVertex = state.stop.stopVertex; Vertex dest = options.rctx.target; double minWalk = distanceToNearestTransitStop; double targetDistance = distanceLibrary.fastDistance(dest.getCoordinate(), stopVertex.getCoordinate()); double minTime = (targetDistance - minWalk) / MAX_TRANSIT_SPEED + minWalk / options.getSpeedUpperBound(); if (targetDistance + state.walkDistance > options.getMaxWalkDistance()) { // can't walk to destination, so we can't alight at a local vertex if (state.stop.stopVertex.isLocal()) continue; //and must account for another boarding minTime += boardSlack; } //this checks the precomputed table of walk distances by regions to see //to get a tigher bound on the best posible walk distance to the destination //it (a) causes weird intermitten planner failures, (b) does not make //much of a difference /* double minWalk = Double.MAX_VALUE; int index = stopVertex.getIndex(); int fromRegion = regionData.regionForVertex[index]; if (fromRegion == -1) { minWalk = distanceToNearestTransitStop; //System.out.println("unexpected missing minwalk for " + stopVertex); } else { for (double[] byRegion : minWalks) { double distanceFromThisRegion = byRegion[fromRegion]; if (minWalk > distanceFromThisRegion) { minWalk = distanceFromThisRegion; } } } if (minWalk == Double.MAX_VALUE) { //I don't believe you System.out.println("WRONG"); } */ state.arrivalTime += minTime; state.walkDistance += minWalk; for (RaptorState bound : cur.boundingStates) { if (eDominates(bound, state)) { state.arrivalTime -= minTime; state.walkDistance -= minWalk; continue STARTWALK; } } state.arrivalTime -= minTime; state.walkDistance -= minWalk; //this bit of code was a test to see if drastically bounding the number of //states explored would help; it does, but this code way overprunes. /* * if (!cur.boundingStates.isEmpty()) { boolean found = false; OUTER: for * (RaptorState bound : cur.boundingStates) { for (RaptorRoute route : * routesForStop[bound.stop.index]) { for (RaptorStop stop : route.stops) { if (stop * == state.stop) { found = true; break OUTER; } } } } if (!found) continue; } */ // end bounding states if (minWalk + state.walkDistance > options.getMaxWalkDistance()) { continue; } StateEditor dijkstraState = new MaxWalkState.MaxWalkStateEditor(walkOptions, stopVertex); dijkstraState.setNumBoardings(state.nBoardings); dijkstraState.setWalkDistance(state.walkDistance); dijkstraState.setTime(state.arrivalTime); dijkstraState.setExtension("raptorParent", state); dijkstraState.setOptions(walkOptions); dijkstraState.incrementWeight(state.arrivalTime - options.dateTime); startPoints.add(dijkstraState.makeState()); } if (startPoints.size() == 0) { System.out.println("warning: no walk in round " + nBoardings); return; } System.out.println("walk starts: " + startPoints.size() + " / " + cur.visitedEver.size()); dijkstra.setPriorityQueueFactory(new PrefilledPriorityQueueFactory(startPoints.subList( 1, startPoints.size()))); dijkstra.setShortestPathTreeFactory(new ShortestPathTreeFactory() { @Override public ShortestPathTree create(RoutingRequest options) { ShortestPathTree result; if (cur.spt == null) { result = new MultiShortestPathTree(options); } else { result = cur.spt; } for (State state : startPoints.subList(1, startPoints.size())) { result.add(state); } return result; } }); //TODO: include existing bounding states final TargetBound bounder = new TargetBound(options.rctx.target, cur.dijkstraBoundingStates); dijkstra.setSearchTerminationStrategy(bounder); dijkstra.setSkipTraverseResultStrategy(bounder); spt = dijkstra.getShortestPathTree(startPoints.get(0)); if (!bounder.bounders.isEmpty()) { cur.dijkstraBoundingStates = bounder.bounders; } if (cur.spt == null) cur.spt = spt; } final List<? extends State> targetStates = spt.getStates(walkOptions.rctx.target); if (targetStates != null) { TARGET: for (State targetState : targetStates) { RaptorState state = new RaptorState(); RaptorState parent = (RaptorState) targetState.getExtension("raptorParent"); state.parent = parent; state.walkDistance = targetState.getWalkDistance(); state.arrivalTime = (int) targetState.getTime(); if (parent != null) { state.nBoardings = parent.nBoardings; state.waitingTime = parent.waitingTime; } state.walkPath = targetState; for (RaptorState oldState : cur.getTargetStates()) { if (eDominates(oldState, state)) { continue TARGET; } } cur.addTargetState(state); System.out.println("TARGET: " + state); } } SPTSTATE: for (State state : spt.getAllStates()) { final Vertex vertex = state.getVertex(); if (!(vertex instanceof TransitStop)) continue; RaptorStop stop = data.raptorStopsForStopId.get(((TransitStop) vertex).getStopId()); if (stop == null) { // we have found a stop is totally unused, so skip it continue; } List<RaptorState> states = statesByStop[stop.index]; if (states == null) { states = new ArrayList<RaptorState>(); statesByStop[stop.index] = states; } double minWalk = distanceToNearestTransitStop; RaptorState baseState = (RaptorState) state.getExtension("raptorParent"); RaptorState newState = new RaptorState(); if (baseState != null) { newState.nBoardings = baseState.nBoardings; } newState.walkDistance = state.getWalkDistance(); newState.arrivalTime = (int) state.getTime(); newState.walkPath = state; newState.parent = baseState; newState.stop = stop; for (RaptorState oldState : states) { if (eDominates(oldState, newState)) { continue SPTSTATE; } } double targetDistance = distanceLibrary.fastDistance( options.rctx.target.getCoordinate(), vertex.getCoordinate()); double minTime = (targetDistance - minWalk) / MAX_TRANSIT_SPEED + minWalk / options.getSpeedUpperBound(); if (targetDistance > options.maxWalkDistance - state.getWalkDistance()) minTime += boardSlack; // target state bounding for (RaptorState oldState : cur.getTargetStates()) { // newstate would have to take some transit and then walk to the destination. if (oldState.arrivalTime <= newState.arrivalTime + minTime && oldState.walkDistance <= newState.walkDistance + minWalk) // todo waiting time? continue SPTSTATE; // newstate will arrive way too late (this is a hack) if ((oldState.arrivalTime - options.dateTime) * 3 <= (newState.arrivalTime + minTime - options.dateTime)) continue SPTSTATE; } cur.visitedLastRound.add(stop); cur.visitedEver.add(stop); states.add(newState); } // fill in for (int stop = 0; stop < statesByStop.length; ++stop) { cur.setStates(stop, statesByStop[stop]); } }
private void round(RaptorData data, RoutingRequest options, RoutingRequest walkOptions, final RaptorPathSet cur, int nBoardings) { Set<RaptorStop> visitedLastRound = cur.visitedLastRound; Set<RaptorRoute> routesToVisit = new HashSet<RaptorRoute>(); for (RaptorStop stop : visitedLastRound) { for (RaptorRoute route : data.routesForStop[stop.index]) { routesToVisit.add(route); } } cur.visitedLastRound = new HashSet<RaptorStop>(); // RoutingContext rctx = walkOptions.rctx; List<RaptorState>[] statesByStop = cur.getStates(); /* * RaptorPathSet cur = new RaptorPathSet(prev.getNStops()); List<RaptorState>[] statesByStop * = prev.getStates(); for (int stop = 0; stop < statesByStop.length; ++stop) { * * //The first stage of round k sets τk (p) = τk−1 (p) f or all stops p: this sets an * //upper bound on the earliest arrival time at p with at most k trips. if * (statesByStop[stop] != null) { System.out.println("filling in for " + stop + ": " + * statesByStop[stop].size()); } cur.addStates(stop, statesByStop[stop]); } */ /* * Consider a route r, and let T (r) = (t0 , t1 , . . . , t|T (r)|−1 ) be the sequence of * trips that follow route r, from earliest to latest. When processing route r, we consider * journeys where the last (k’th) trip taken is in route r. Let et(r, pi ) be the earliest * trip in route r that one can catch at stop pi , i. e., the earliest trip t such that τdep * (t, pi ) ≥ τk−1 (pi ). (Note that this trip may not exist, in which case et(r, pi ) is * undefined.) To process the route, we visit its stops in order until we find a stop pi * such that et(r, pi ) is defined. This is when we can “hop on” the route. Let the * corresponding trip t be the current trip for k. We keep traversing the route. For each * subsequent stop pj , we can update τk (pj ) using this trip. To reconstruct the journey, * we set a parent pointer to the stop at which t was boarded. Moreover, we may need to * update the current trip for k: at each stop pi along r it may be possible to catch an * earlier trip (because a quicker path to pi has been found in a previous round). Thus, we * have to check if τk−1 (pi ) < τarr (t, pi ) and update t by recomputing et(r, pi ). */ int boardSlack = nBoardings == 1 ? options.getBoardSlack() : (options.getTransferSlack() - options.getAlightSlack()); List<RaptorState> createdStates = new ArrayList<RaptorState>(); System.out.println("Round " + nBoardings); final double distanceToNearestTransitStop = options.rctx.target .getDistanceToNearestTransitStop(); for (RaptorRoute route : routesToVisit) { List<RaptorState> boardStates = new ArrayList<RaptorState>(); // not really states boolean started = false; for (int stopNo = 0; stopNo < route.getNStops(); ++stopNo) { // find the current time at this stop RaptorStop stop = route.stops[stopNo]; if (!started && !visitedLastRound.contains(stop)) continue; started = true; List<RaptorState> states = statesByStop[stop.index]; List<RaptorState> newStates = new ArrayList<RaptorState>(); if (states == null) { states = new ArrayList<RaptorState>(); statesByStop[stop.index] = states; } // this checks the case of continuing on the current trips. CONTINUE: for (RaptorState boardState : boardStates) { RaptorState newState = new RaptorState(); ServiceDay sd = boardState.serviceDay; int alightTime = route.getAlightTime(boardState.patternIndex, boardState.tripIndex, stopNo); newState.arrivalTime = (int) sd.time(alightTime); //add in slack newState.arrivalTime += options.getAlightSlack(); newState.boardStop = boardState.boardStop; newState.boardStopSequence = boardState.boardStopSequence; newState.route = route; newState.patternIndex = boardState.patternIndex; newState.tripIndex = boardState.tripIndex; newState.nBoardings = boardState.nBoardings; newState.walkDistance = boardState.walkDistance; newState.parent = boardState.parent; newState.stop = stop; // todo: waiting time, which presently is not handled for (RaptorState oldState : states) { if (eDominates(oldState, newState)) { continue CONTINUE; } } for (RaptorState oldState : newStates) { if (oldState != newState && eDominates(oldState, newState)) { continue CONTINUE; } } Iterator<RaptorState> it = states.iterator(); while(it.hasNext()) { RaptorState oldState = it.next(); if (eDominates(newState, oldState)) { it.remove(); } } it = newStates.iterator(); while(it.hasNext()) { RaptorState oldState = it.next(); if (eDominates(newState, oldState)) { it.remove(); } } cur.visitedLastRound.add(stop); cur.visitedEver.add(stop); newStates.add(newState); StopNearTarget nearTarget = cur.stopsNearTarget.get(stop); if (nearTarget != null) { RaptorState bound = new RaptorState(); bound.arrivalTime = newState.arrivalTime + nearTarget.time; bound.walkDistance = newState.walkDistance + nearTarget.walkDistance; if (bound.walkDistance <= options.maxWalkDistance) { bound.nBoardings = newState.nBoardings; bound.stop = stop; for (RaptorState oldBound : cur.boundingStates) { if (eDominates(oldBound, bound)) { continue CONTINUE; } } cur.boundingStates.add(bound); } } } if (newStates.size() > 10) { // System.out.println("HERE: " + newStates.size()); } if (stopNo < route.getNStops() - 1) { if (stop.stopVertex.isLocal() && nBoardings > 1) { // cannot transfer at a local stop continue; } // try boarding here TRYBOARD: for (RaptorState oldState : states) { if (oldState.nBoardings != nBoardings - 1) continue; if (oldState.route == route) continue; // we got here via this route, so no reason to transfer RaptorBoardSpec boardSpec = route.getTripIndex(options, oldState.arrivalTime + boardSlack, stopNo); if (boardSpec == null) continue; RaptorState boardState = new RaptorState(); boardState.nBoardings = nBoardings; boardState.boardStop = stop; boardState.boardStopSequence = stopNo; boardState.arrivalTime = boardSpec.departureTime; boardState.patternIndex = boardSpec.patternIndex; boardState.tripIndex = boardSpec.tripIndex; boardState.parent = oldState; boardState.serviceDay = boardSpec.serviceDay; boardState.route = route; boardState.walkDistance = oldState.walkDistance; for (RaptorState state : newStates) { if (eDominates(state, boardState)) { continue TRYBOARD; } } for (RaptorState state : states) { if (state != oldState && eDominates(state, boardState)) { continue TRYBOARD; } } boardStates.add(boardState); } } createdStates.addAll(newStates); states.addAll(newStates); } } /* * finally, the third stage of round k considers foot- paths. For each foot-path (pi , pj ) * ∈ F it sets τk (pj ) = min{τk (pj ), τk (pi ) + (pi , pj )}. Note that since F is * transitive, we always find the fastest walking path, if one exists. */ ShortestPathTree spt; GenericDijkstra dijkstra = new GenericDijkstra(walkOptions); if (nBoardings == 0) { State start = new MaxWalkState(options.rctx.origin, walkOptions); spt = dijkstra.getShortestPathTree(start); // also, compute an initial spt from the target so that we can find out what transit // stops are nearby and what // the time is to them, so that we can start target bounding earlier RoutingRequest reversedWalkOptions = walkOptions.clone(); reversedWalkOptions.setArriveBy(true); GenericDijkstra destDijkstra = new GenericDijkstra(reversedWalkOptions); start = new MaxWalkState(options.rctx.target, reversedWalkOptions); ShortestPathTree targetSpt = destDijkstra.getShortestPathTree(start); for (State state : targetSpt.getAllStates()) { final Vertex vertex = state.getVertex(); if (!(vertex instanceof TransitStop)) continue; RaptorStop stop = data.raptorStopsForStopId.get(((TransitStop) vertex).getStopId()); if (stop == null) { // we have found a stop is totally unused, so skip it continue; } cur.addStopNearTarget(stop, state.getWalkDistance(), (int) state.getElapsedTime()); } } else { if (options.rctx.graph.getService(TransitLocalStreetService.class) != null) dijkstra.setSkipEdgeStrategy(new SkipNonTransferEdgeStrategy(options)); final List<State> startPoints = new ArrayList<State>(); /* RegionData regionData = data.regionData; List<Integer> destinationRegions = regionData.getRegionsForVertex(options.rctx.target); List<double[]> minWalks = new ArrayList<double[]>(2); for (int destinationRegion : destinationRegions) { minWalks.add(regionData.minWalk[destinationRegion]); } */ STARTWALK: for (RaptorState state : createdStates) { if (false) { double maxWalk = options.getMaxWalkDistance() - state.walkDistance - distanceToNearestTransitStop; CHECK: for (T2<Double, RaptorStop> nearby : data.nearbyStops[state.stop.index]) { double distance = nearby.getFirst(); RaptorStop stop = nearby.getSecond(); if (distance > maxWalk) { // System.out.println("SKIPPED STATE: " + // state.stop.stopVertex.getName()); // this is technically wrong because these distances are not exact continue STARTWALK; } double minWalk = distance + state.walkDistance; int minArrive = (int) (state.arrivalTime + distance / options.getSpeedUpperBound()); if (statesByStop[stop.index] == null) { break CHECK; // we have never visited this stop, and we ought to } for (RaptorState other : statesByStop[stop.index]) { if (other.nBoardings == nBoardings - 1 && (other.walkDistance > minWalk || other.arrivalTime > minArrive)) { break CHECK; } } } } // bounding states // this reduces the number of initial vertices // and the state space size Vertex stopVertex = state.stop.stopVertex; Vertex dest = options.rctx.target; double minWalk = distanceToNearestTransitStop; double targetDistance = distanceLibrary.fastDistance(dest.getCoordinate(), stopVertex.getCoordinate()); double minTime = (targetDistance - minWalk) / MAX_TRANSIT_SPEED + minWalk / options.getSpeedUpperBound(); if (targetDistance + state.walkDistance > options.getMaxWalkDistance()) { // can't walk to destination, so we can't alight at a local vertex if (state.stop.stopVertex.isLocal()) continue; //and must account for another boarding minTime += boardSlack; } //this checks the precomputed table of walk distances by regions to see //to get a tigher bound on the best posible walk distance to the destination //it (a) causes weird intermitten planner failures, (b) does not make //much of a difference /* double minWalk = Double.MAX_VALUE; int index = stopVertex.getIndex(); int fromRegion = regionData.regionForVertex[index]; if (fromRegion == -1) { minWalk = distanceToNearestTransitStop; //System.out.println("unexpected missing minwalk for " + stopVertex); } else { for (double[] byRegion : minWalks) { double distanceFromThisRegion = byRegion[fromRegion]; if (minWalk > distanceFromThisRegion) { minWalk = distanceFromThisRegion; } } } if (minWalk == Double.MAX_VALUE) { //I don't believe you System.out.println("WRONG"); } */ state.arrivalTime += minTime; state.walkDistance += minWalk; for (RaptorState bound : cur.boundingStates) { if (bound == state) { break; //do not eliminate bounding states } if (eDominates(bound, state)) { state.arrivalTime -= minTime; state.walkDistance -= minWalk; continue STARTWALK; } } state.arrivalTime -= minTime; state.walkDistance -= minWalk; //this bit of code was a test to see if drastically bounding the number of //states explored would help; it does, but this code way overprunes. /* * if (!cur.boundingStates.isEmpty()) { boolean found = false; OUTER: for * (RaptorState bound : cur.boundingStates) { for (RaptorRoute route : * routesForStop[bound.stop.index]) { for (RaptorStop stop : route.stops) { if (stop * == state.stop) { found = true; break OUTER; } } } } if (!found) continue; } */ // end bounding states if (minWalk + state.walkDistance > options.getMaxWalkDistance()) { continue; } StateEditor dijkstraState = new MaxWalkState.MaxWalkStateEditor(walkOptions, stopVertex); dijkstraState.setNumBoardings(state.nBoardings); dijkstraState.setWalkDistance(state.walkDistance); dijkstraState.setTime(state.arrivalTime); dijkstraState.setExtension("raptorParent", state); dijkstraState.setOptions(walkOptions); dijkstraState.incrementWeight(state.arrivalTime - options.dateTime); startPoints.add(dijkstraState.makeState()); } if (startPoints.size() == 0) { System.out.println("warning: no walk in round " + nBoardings); return; } System.out.println("walk starts: " + startPoints.size() + " / " + cur.visitedEver.size()); dijkstra.setPriorityQueueFactory(new PrefilledPriorityQueueFactory(startPoints.subList( 1, startPoints.size()))); dijkstra.setShortestPathTreeFactory(new ShortestPathTreeFactory() { @Override public ShortestPathTree create(RoutingRequest options) { ShortestPathTree result; if (cur.spt == null) { result = new MultiShortestPathTree(options); } else { result = cur.spt; } for (State state : startPoints.subList(1, startPoints.size())) { result.add(state); } return result; } }); //TODO: include existing bounding states final TargetBound bounder = new TargetBound(options.rctx.target, cur.dijkstraBoundingStates); dijkstra.setSearchTerminationStrategy(bounder); dijkstra.setSkipTraverseResultStrategy(bounder); spt = dijkstra.getShortestPathTree(startPoints.get(0)); if (!bounder.bounders.isEmpty()) { cur.dijkstraBoundingStates = bounder.bounders; } if (cur.spt == null) cur.spt = spt; } final List<? extends State> targetStates = spt.getStates(walkOptions.rctx.target); if (targetStates != null) { TARGET: for (State targetState : targetStates) { RaptorState state = new RaptorState(); RaptorState parent = (RaptorState) targetState.getExtension("raptorParent"); state.parent = parent; state.walkDistance = targetState.getWalkDistance(); state.arrivalTime = (int) targetState.getTime(); if (parent != null) { state.nBoardings = parent.nBoardings; state.waitingTime = parent.waitingTime; } state.walkPath = targetState; for (RaptorState oldState : cur.getTargetStates()) { if (eDominates(oldState, state)) { continue TARGET; } } cur.addTargetState(state); System.out.println("TARGET: " + state); } } SPTSTATE: for (State state : spt.getAllStates()) { final Vertex vertex = state.getVertex(); if (!(vertex instanceof TransitStop)) continue; RaptorStop stop = data.raptorStopsForStopId.get(((TransitStop) vertex).getStopId()); if (stop == null) { // we have found a stop is totally unused, so skip it continue; } List<RaptorState> states = statesByStop[stop.index]; if (states == null) { states = new ArrayList<RaptorState>(); statesByStop[stop.index] = states; } double minWalk = distanceToNearestTransitStop; RaptorState baseState = (RaptorState) state.getExtension("raptorParent"); RaptorState newState = new RaptorState(); if (baseState != null) { newState.nBoardings = baseState.nBoardings; } newState.walkDistance = state.getWalkDistance(); newState.arrivalTime = (int) state.getTime(); newState.walkPath = state; newState.parent = baseState; newState.stop = stop; for (RaptorState oldState : states) { if (eDominates(oldState, newState)) { continue SPTSTATE; } } double targetDistance = distanceLibrary.fastDistance( options.rctx.target.getCoordinate(), vertex.getCoordinate()); double minTime = (targetDistance - minWalk) / MAX_TRANSIT_SPEED + minWalk / options.getSpeedUpperBound(); if (targetDistance > options.maxWalkDistance - state.getWalkDistance()) minTime += boardSlack; // target state bounding for (RaptorState oldState : cur.getTargetStates()) { // newstate would have to take some transit and then walk to the destination. if (oldState.arrivalTime <= newState.arrivalTime + minTime && oldState.walkDistance <= newState.walkDistance + minWalk) // todo waiting time? continue SPTSTATE; // newstate will arrive way too late (this is a hack) if ((oldState.arrivalTime - options.dateTime) * 3 <= (newState.arrivalTime + minTime - options.dateTime)) continue SPTSTATE; } cur.visitedLastRound.add(stop); cur.visitedEver.add(stop); states.add(newState); } // fill in for (int stop = 0; stop < statesByStop.length; ++stop) { cur.setStates(stop, statesByStop[stop]); } }
diff --git a/sgs-client/src/main/java/com/sun/sgs/client/simple/SimpleClient.java b/sgs-client/src/main/java/com/sun/sgs/client/simple/SimpleClient.java index 42a2256..686fc6a 100644 --- a/sgs-client/src/main/java/com/sun/sgs/client/simple/SimpleClient.java +++ b/sgs-client/src/main/java/com/sun/sgs/client/simple/SimpleClient.java @@ -1,750 +1,759 @@ /* * Copyright (c) 2007-2008, Sun Microsystems, Inc. * * 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 Sun Microsystems, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.sun.sgs.client.simple; import java.io.IOException; import java.math.BigInteger; import java.net.PasswordAuthentication; import java.nio.ByteBuffer; import java.util.Properties; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import java.util.logging.Logger; import com.sun.sgs.client.ClientChannel; import com.sun.sgs.client.ClientChannelListener; import com.sun.sgs.client.ServerSession; import com.sun.sgs.client.ServerSessionListener; import com.sun.sgs.impl.client.comm.ClientConnection; import com.sun.sgs.impl.client.comm.ClientConnectionListener; import com.sun.sgs.impl.client.comm.ClientConnector; import com.sun.sgs.impl.sharedutil.LoggerWrapper; import com.sun.sgs.impl.sharedutil.MessageBuffer; import com.sun.sgs.protocol.simple.SimpleSgsProtocol; /** * An implementation of {@link ServerSession} that clients can use to manage * logging in and communicating with the server. A {@code SimpleClient} * is used to establish (or re-establish) a login session with the server, * send messages to the server, and log out. * <p> * A {@code SimpleClient} is constructed with a {@link * SimpleClientListener} which receives connection-related events as well * as messages from the server application. * <p> * If the server session associated with a simple client becomes * disconnected, then its {@link #send send} method will throw * {@code IllegalStateException}. A disconnected * client can use the {@link #login login} method to log in again. */ public class SimpleClient implements ServerSession { /** The logger for this class. */ private static final LoggerWrapper logger = new LoggerWrapper(Logger.getLogger(SimpleClient.class.getName())); /** * The listener for the {@code ClientConnection} the session * is communicating on. If our login attempt is redirected to * another host, we will use a different listener for the connection * to the new host. */ private ClientConnectionListener connListener; /** The listener for this simple client. */ private final SimpleClientListener clientListener; /** * The current {@code ClientConnection}, if connected, or * {@code} null if disconnected. */ private volatile ClientConnection clientConnection = null; /** The password authentication used for the initial client * login attempt. If the client receives a LOGIN_REDIRECT * message, we don't want the user (typing at a keyboard) * to have to supply their login information again. */ PasswordAuthentication authentication = null; /** * Indicates that either a connection or disconnection attempt * is in progress. */ private volatile boolean connectionStateChanging = false; /** Indicates whether this client is logged in. */ private volatile boolean loggedIn = false; /** Reconnection key. TODO reconnect not implemented */ @SuppressWarnings("unused") private byte[] reconnectKey; /** The map of channels this client is a member of, keyed by channel ID */ private final ConcurrentHashMap<BigInteger, SimpleClientChannel> channels = new ConcurrentHashMap<BigInteger, SimpleClientChannel>(); /** * Creates an instance of this class with the specified listener. Once * this client is logged in (by using the {@link #login login} method), * the specified listener receives connection-related events, receives * messages from the server, and also receives notification of each * channel the client is joined to. If this client becomes disconnected * for any reason, it may use the {@code login} method to log in * again. * * @param listener a listener that will receive events for this client */ public SimpleClient(SimpleClientListener listener) { if (listener == null) { throw new NullPointerException( "The SimpleClientListener argument must not be null"); } connListener = new SimpleClientConnectionListener(); this.clientListener = listener; } /** * Initiates a login session with the server. A session is established * asynchronously with the server as follows: * * <p>First, this client attempts to establish a connection with the * server. If the client fails to establish a connection, then the * client listener's {@link SimpleClientListener#disconnected * disconnected} method is invoked with a {@code String} indicating the * reason for the failure. * * <p>If a connection with the server is successfully established, this * client's {@link PasswordAuthentication login credential} * is obtained by invoking its {@link SimpleClientListener listener}'s * {@link SimpleClientListener#getPasswordAuthentication * getPasswordAuthentication} method with a login prompt. * * <p>Next, this client sends a login request to the server. If the * login request is malformed, the client listener's {@link * SimpleClientListener#disconnected disconnected} method is invoked * with a {@code String} indicating the reason for the failure or * {@code null} if no reason can be determined. * * <p>If the client's login credential (as obtained above) is * verified, then the client listener's {@link * SimpleClientListener#loggedIn loggedIn} method is invoked. If, * however, the login fails due to a login authentication failure or * some other failure on the server while processing the login request, * the client listener's {@link SimpleClientListener#loginFailed * loginFailed} method is invoked with a {@code String} indicating the * reason for the failure. * * <p>If this client is disconnected for any reason (including login * failure), this method may be used again to log in. * <p> * The supported connection properties are: * <table summary="Shows property keys and associated values"> * <tr><th>Key</th> * <th>Description of Associated Value</th></tr> * <tr><td>{@code host}</td> * <td>SGS host address <b>(required)</b></td></tr> * <tr><td>{@code port}</td> * <td>SGS port <b>(required)</b></td></tr> * </table> * * @param props the connection properties to use in creating the * client's session * * @throws IOException if a synchronous IO error occurs * @throws IllegalStateException if this session is already connected * or connecting * @throws SecurityException if the caller does not have permission * to connect to the remote endpoint */ public void login(Properties props) throws IOException { synchronized (this) { if (connectionStateChanging || clientConnection != null) { RuntimeException re = new IllegalStateException( "Session already connected or connecting"); logger.logThrow(Level.FINE, re, re.getMessage()); throw re; } connectionStateChanging = true; } ClientConnector connector = ClientConnector.create(props); connector.connect(connListener); } /* -- Implement ServerSession -- */ /** * {@inheritDoc} */ public boolean isConnected() { return (clientConnection != null); } /** * {@inheritDoc} */ public void logout(boolean force) { synchronized (this) { if (connectionStateChanging || clientConnection == null) { RuntimeException re = new IllegalStateException("Client not connected"); logger.logThrow(Level.FINE, re, re.getMessage()); throw re; } connectionStateChanging = true; } if (force) { try { loggedIn = false; clientConnection.disconnect(); } catch (IOException e) { logger.logThrow(Level.FINE, e, "During forced logout:"); // ignore } } else { try { ByteBuffer msg = ByteBuffer.wrap( new byte[] { SimpleSgsProtocol.LOGOUT_REQUEST }); sendRaw(msg.asReadOnlyBuffer()); } catch (IOException e) { logger.logThrow(Level.FINE, e, "During graceful logout:"); try { loggedIn = false; clientConnection.disconnect(); } catch (IOException e2) { logger.logThrow(Level.FINE, e2, "During forced logout:"); // ignore } } } } /** * {@inheritDoc} */ public void send(ByteBuffer message) throws IOException { checkConnected(); ByteBuffer msg = ByteBuffer.allocate(1 + message.remaining()); msg.put(SimpleSgsProtocol.SESSION_MESSAGE) .put(message) .flip(); sendRaw(msg); } /** * Sends raw data to the underlying connection. * * @param buf the data to send * @throws IOException if an IO problem occurs */ private void sendRaw(ByteBuffer buf) throws IOException { clientConnection.sendMessage(buf); } /** * Throws an exception if this client is not connected. * * @throws IllegalStateException if this client is not connected */ private void checkConnected() { if (!isConnected()) { RuntimeException re = new IllegalStateException("Client not connected"); logger.logThrow(Level.FINE, re, re.getMessage()); throw re; } } /** * Throws an exception if this client is not logged in. * * @throws IllegalStateException if this client is not logged in */ private void checkLoggedIn() { if (! loggedIn) { RuntimeException re = new IllegalStateException("Client not logged in"); logger.logThrow(Level.FINE, re, re.getMessage()); throw re; } } /** * Receives callbacks on the associated {@code ClientConnection}. */ final class SimpleClientConnectionListener implements ClientConnectionListener { /** Indicates whether this listener expects a disconnect message. */ private volatile boolean expectingDisconnect = false; /** Indicates whether the disconnected callback should not be * invoked. */ private volatile boolean suppressDisconnectedCallback = false; /** Indicates whether this listener has been disabled because * of an automatic login redirect to another host and port. * We need to disconnect our previous connection, but we don't * want to tell the client listener. We'll accept no messages * when we're in this state. */ private volatile boolean redirect = false; /* -- Implement ClientConnectionListener -- */ /** * {@inheritDoc} */ public void connected(ClientConnection connection) { logger.log(Level.FINER, "Connected"); synchronized (SimpleClient.this) { connectionStateChanging = false; clientConnection = connection; } // First time through, we haven't authenticated yet. // We don't want to have to reauthenticate for each login // redirect. if (authentication == null) { authentication = clientListener.getPasswordAuthentication(); } if (authentication == null) { logout(true); throw new NullPointerException( "The returned PasswordAuthentication must not be null"); } String user = authentication.getUserName(); String pass = new String(authentication.getPassword()); MessageBuffer msg = new MessageBuffer(2 + MessageBuffer.getSize(user) + MessageBuffer.getSize(pass)); msg.putByte(SimpleSgsProtocol.LOGIN_REQUEST). putByte(SimpleSgsProtocol.VERSION). putString(user). putString(pass); try { sendRaw(ByteBuffer.wrap(msg.getBuffer()).asReadOnlyBuffer()); } catch (IOException e) { logger.logThrow(Level.FINE, e, "During login request:"); logout(true); } } /** * {@inheritDoc} */ public void disconnected(boolean graceful, byte[] message) { if (redirect) { // This listener has been redirected, and this callback // should be ignored. In particular, we don't want to // change the clientConnection state (this could be a // real problem if the disconnected callback was delayed // to after the connected callback from the automatic // login redirect), and we don't want to notify the // client listener of the redirect. return; } synchronized (SimpleClient.this) { if (clientConnection == null && (! connectionStateChanging)) { // Someone else beat us here return; } clientConnection = null; connectionStateChanging = false; } String reason = null; if (message != null) { MessageBuffer msg = new MessageBuffer(message); reason = msg.getString(); } for (SimpleClientChannel channel : channels.values()) { try { channel.left(); } catch (RuntimeException e) { logger.logThrow(Level.FINE, e, "During leftChannel ({0}) on disconnect:", channel.getName()); // ignore the exception } } channels.clear(); // TBI implement graceful disconnect. // For now, look at the boolean we set when expecting // disconnect if (! suppressDisconnectedCallback) { clientListener.disconnected(expectingDisconnect, reason); } suppressDisconnectedCallback = false; expectingDisconnect = false; } /** * {@inheritDoc} */ public void receivedMessage(byte[] message) { try { MessageBuffer msg = new MessageBuffer(message); if (logger.isLoggable(Level.FINER)) { String logMessage = String.format( "Message length:%d", message.length); logger.log(Level.FINER, logMessage); } handleApplicationMessage(msg); } catch (IOException e) { logger.logThrow(Level.FINER, e, e.getMessage()); if (isConnected()) { try { clientConnection.disconnect(); } catch (IOException e2) { logger.logThrow(Level.FINEST, e2, "Disconnect failed after {0}", e.getMessage()); // Ignore } } } } /** * Processes an application message. * * @param msg the message to process * @throws IOException if an IO problem occurs */ private void handleApplicationMessage(MessageBuffer msg) throws IOException { byte command = msg.getByte(); switch (command) { case SimpleSgsProtocol.LOGIN_SUCCESS: logger.log(Level.FINER, "Logged in"); reconnectKey = msg.getBytes(msg.limit() - msg.position()); loggedIn = true; clientListener.loggedIn(); break; case SimpleSgsProtocol.LOGIN_FAILURE: { String reason = msg.getString(); logger.log(Level.FINER, "Login failed: {0}", reason); suppressDisconnectedCallback = true; try { clientConnection.disconnect(); } catch (IOException e) { if (logger.isLoggable(Level.FINE)) { logger.logThrow(Level.FINE, e, "Disconnecting after login failure throws"); } // ignore } clientListener.loginFailed(reason); break; } case SimpleSgsProtocol.LOGIN_REDIRECT: { String host = msg.getString(); int port = msg.getInt(); logger.log(Level.FINER, "Login redirect: {0}:{1}", host, port); // Disconnect our current connection, and connect to the // new host and port ClientConnection oldConnection = clientConnection; synchronized (SimpleClient.this) { clientConnection = null; connectionStateChanging = true; } try { oldConnection.disconnect(); } catch (IOException e) { if (logger.isLoggable(Level.FINE)) { logger.logThrow(Level.FINE, e, "Disconnecting after login redirect throws"); } // ignore } redirect = true; Properties props = new Properties(); props.setProperty("host", host); props.setProperty("port", String.valueOf(port)); ClientConnector connector = ClientConnector.create(props); // We use a new listener so we don't have to worry about // "redirect" being incorrect. connListener = new SimpleClientConnectionListener(); // This eventually causes connected to be called connector.connect(connListener); break; } case SimpleSgsProtocol.SESSION_MESSAGE: { logger.log(Level.FINEST, "Direct receive"); checkLoggedIn(); byte[] msgBytes = msg.getBytes(msg.limit() - msg.position()); ByteBuffer buf = ByteBuffer.wrap(msgBytes); - clientListener.receivedMessage(buf.asReadOnlyBuffer()); + try { + clientListener.receivedMessage(buf.asReadOnlyBuffer()); + } catch (RuntimeException e) { + if (logger.isLoggable(Level.WARNING)) { + logger.logThrow( + Level.WARNING, e, + "SimpleClientListener.receivedMessage callback " + + "throws"); + } + } break; } case SimpleSgsProtocol.RECONNECT_SUCCESS: logger.log(Level.FINER, "Reconnected"); loggedIn = true; reconnectKey = msg.getBytes(msg.limit() - msg.position()); clientListener.reconnected(); break; case SimpleSgsProtocol.RECONNECT_FAILURE: try { String reason = msg.getString(); logger.log(Level.FINER, "Reconnect failed: {0}", reason); clientConnection.disconnect(); } catch (IOException e) { if (logger.isLoggable(Level.FINE)) { logger.logThrow(Level.FINE, e, "Disconnecting a failed reconnect throws"); } // ignore } break; case SimpleSgsProtocol.LOGOUT_SUCCESS: logger.log(Level.FINER, "Logged out gracefully"); expectingDisconnect = true; loggedIn = false; try { clientConnection.disconnect(); } catch (IOException e) { if (logger.isLoggable(Level.FINE)) { logger.logThrow(Level.FINE, e, "Disconnecting after graceful logout throws"); } // ignore } break; case SimpleSgsProtocol.CHANNEL_JOIN: { logger.log(Level.FINER, "Channel join"); checkLoggedIn(); String channelName = msg.getString(); byte[] channelIdBytes = msg.getBytes(msg.limit() - msg.position()); BigInteger channelId = new BigInteger(1, channelIdBytes); SimpleClientChannel channel = new SimpleClientChannel(channelName, channelId); if (channels.putIfAbsent(channelId, channel) == null) { channel.joined(); } else { logger.log(Level.WARNING, "Cannot join channel {0}: already a member", channelName); } break; } case SimpleSgsProtocol.CHANNEL_LEAVE: { logger.log(Level.FINER, "Channel leave"); checkLoggedIn(); byte[] channelIdBytes = msg.getBytes(msg.limit() - msg.position()); BigInteger channelId = new BigInteger(1, channelIdBytes); SimpleClientChannel channel = channels.remove(channelId); if (channel != null) { channel.left(); } else { logger.log(Level.WARNING, "Cannot leave channel {0}: not a member", channelId); } break; } case SimpleSgsProtocol.CHANNEL_MESSAGE: logger.log(Level.FINEST, "Channel recv"); checkLoggedIn(); BigInteger channelId = new BigInteger(1, msg.getBytes(msg.getShort())); SimpleClientChannel channel = channels.get(channelId); if (channel == null) { logger.log(Level.WARNING, "Ignore message on channel {0}: not a member", channelId); return; } byte[] msgBytes = msg.getBytes(msg.limit() - msg.position()); ByteBuffer buf = ByteBuffer.wrap(msgBytes); channel.receivedMessage(buf.asReadOnlyBuffer()); break; default: throw new IOException( String.format("Unknown session opcode: 0x%02X", command)); } } /** * {@inheritDoc} */ public void reconnected(byte[] message) { RuntimeException re = new UnsupportedOperationException( "Not supported by SimpleClient"); logger.logThrow(Level.WARNING, re, re.getMessage()); throw re; } /** * {@inheritDoc} */ public void reconnecting(byte[] message) { RuntimeException re = new UnsupportedOperationException( "Not supported by SimpleClient"); logger.logThrow(Level.WARNING, re, re.getMessage()); throw re; } /** * {@inheritDoc} */ public ServerSessionListener sessionStarted(byte[] message) { RuntimeException re = new UnsupportedOperationException( "Not supported by SimpleClient"); logger.logThrow(Level.WARNING, re, re.getMessage()); throw re; } } /** * Simple ClientChannel implementation */ final class SimpleClientChannel implements ClientChannel { private final String channelName; private final BigInteger channelId; /** * The listener for this channel if the client is a member, * or null if the client is no longer a member of this channel. */ private volatile ClientChannelListener listener = null; private final AtomicBoolean isJoined = new AtomicBoolean(false); SimpleClientChannel(String name, BigInteger id) { this.channelName = name; this.channelId = id; } // Implement ClientChannel /** * {@inheritDoc} */ public String getName() { return channelName; } /** * {@inheritDoc} */ public void send(ByteBuffer message) throws IOException { if (! isJoined.get()) { throw new IllegalStateException( "Cannot send on unjoined channel " + channelName); } byte[] idBytes = channelId.toByteArray(); ByteBuffer msg = ByteBuffer.allocate(3 + idBytes.length + message.remaining()); msg.put(SimpleSgsProtocol.CHANNEL_MESSAGE) .putShort((short) idBytes.length) .put(idBytes) .put(message) .flip(); sendRaw(msg); } // Implementation details void joined() { if (! isJoined.compareAndSet(false, true)) { throw new IllegalStateException( "Already joined to channel " + channelName); } assert listener == null; try { listener = clientListener.joinedChannel(this); if (listener == null) { // FIXME: print a warning? throw new NullPointerException( "The returned ClientChannelListener must not be null"); } } catch (RuntimeException ex) { isJoined.set(false); throw ex; } } void left() { if (! isJoined.compareAndSet(true, false)) { throw new IllegalStateException( "Cannot leave unjoined channel " + channelName); } final ClientChannelListener l = this.listener; this.listener = null; l.leftChannel(this); } void receivedMessage(ByteBuffer message) { if (! isJoined.get()) { throw new IllegalStateException( "Cannot receive on unjoined channel " + channelName); } listener.receivedMessage(this, message); } } }
true
true
private void handleApplicationMessage(MessageBuffer msg) throws IOException { byte command = msg.getByte(); switch (command) { case SimpleSgsProtocol.LOGIN_SUCCESS: logger.log(Level.FINER, "Logged in"); reconnectKey = msg.getBytes(msg.limit() - msg.position()); loggedIn = true; clientListener.loggedIn(); break; case SimpleSgsProtocol.LOGIN_FAILURE: { String reason = msg.getString(); logger.log(Level.FINER, "Login failed: {0}", reason); suppressDisconnectedCallback = true; try { clientConnection.disconnect(); } catch (IOException e) { if (logger.isLoggable(Level.FINE)) { logger.logThrow(Level.FINE, e, "Disconnecting after login failure throws"); } // ignore } clientListener.loginFailed(reason); break; } case SimpleSgsProtocol.LOGIN_REDIRECT: { String host = msg.getString(); int port = msg.getInt(); logger.log(Level.FINER, "Login redirect: {0}:{1}", host, port); // Disconnect our current connection, and connect to the // new host and port ClientConnection oldConnection = clientConnection; synchronized (SimpleClient.this) { clientConnection = null; connectionStateChanging = true; } try { oldConnection.disconnect(); } catch (IOException e) { if (logger.isLoggable(Level.FINE)) { logger.logThrow(Level.FINE, e, "Disconnecting after login redirect throws"); } // ignore } redirect = true; Properties props = new Properties(); props.setProperty("host", host); props.setProperty("port", String.valueOf(port)); ClientConnector connector = ClientConnector.create(props); // We use a new listener so we don't have to worry about // "redirect" being incorrect. connListener = new SimpleClientConnectionListener(); // This eventually causes connected to be called connector.connect(connListener); break; } case SimpleSgsProtocol.SESSION_MESSAGE: { logger.log(Level.FINEST, "Direct receive"); checkLoggedIn(); byte[] msgBytes = msg.getBytes(msg.limit() - msg.position()); ByteBuffer buf = ByteBuffer.wrap(msgBytes); clientListener.receivedMessage(buf.asReadOnlyBuffer()); break; } case SimpleSgsProtocol.RECONNECT_SUCCESS: logger.log(Level.FINER, "Reconnected"); loggedIn = true; reconnectKey = msg.getBytes(msg.limit() - msg.position()); clientListener.reconnected(); break; case SimpleSgsProtocol.RECONNECT_FAILURE: try { String reason = msg.getString(); logger.log(Level.FINER, "Reconnect failed: {0}", reason); clientConnection.disconnect(); } catch (IOException e) { if (logger.isLoggable(Level.FINE)) { logger.logThrow(Level.FINE, e, "Disconnecting a failed reconnect throws"); } // ignore } break; case SimpleSgsProtocol.LOGOUT_SUCCESS: logger.log(Level.FINER, "Logged out gracefully"); expectingDisconnect = true; loggedIn = false; try { clientConnection.disconnect(); } catch (IOException e) { if (logger.isLoggable(Level.FINE)) { logger.logThrow(Level.FINE, e, "Disconnecting after graceful logout throws"); } // ignore } break; case SimpleSgsProtocol.CHANNEL_JOIN: { logger.log(Level.FINER, "Channel join"); checkLoggedIn(); String channelName = msg.getString(); byte[] channelIdBytes = msg.getBytes(msg.limit() - msg.position()); BigInteger channelId = new BigInteger(1, channelIdBytes); SimpleClientChannel channel = new SimpleClientChannel(channelName, channelId); if (channels.putIfAbsent(channelId, channel) == null) { channel.joined(); } else { logger.log(Level.WARNING, "Cannot join channel {0}: already a member", channelName); } break; } case SimpleSgsProtocol.CHANNEL_LEAVE: { logger.log(Level.FINER, "Channel leave"); checkLoggedIn(); byte[] channelIdBytes = msg.getBytes(msg.limit() - msg.position()); BigInteger channelId = new BigInteger(1, channelIdBytes); SimpleClientChannel channel = channels.remove(channelId); if (channel != null) { channel.left(); } else { logger.log(Level.WARNING, "Cannot leave channel {0}: not a member", channelId); } break; } case SimpleSgsProtocol.CHANNEL_MESSAGE: logger.log(Level.FINEST, "Channel recv"); checkLoggedIn(); BigInteger channelId = new BigInteger(1, msg.getBytes(msg.getShort())); SimpleClientChannel channel = channels.get(channelId); if (channel == null) { logger.log(Level.WARNING, "Ignore message on channel {0}: not a member", channelId); return; } byte[] msgBytes = msg.getBytes(msg.limit() - msg.position()); ByteBuffer buf = ByteBuffer.wrap(msgBytes); channel.receivedMessage(buf.asReadOnlyBuffer()); break; default: throw new IOException( String.format("Unknown session opcode: 0x%02X", command)); } }
private void handleApplicationMessage(MessageBuffer msg) throws IOException { byte command = msg.getByte(); switch (command) { case SimpleSgsProtocol.LOGIN_SUCCESS: logger.log(Level.FINER, "Logged in"); reconnectKey = msg.getBytes(msg.limit() - msg.position()); loggedIn = true; clientListener.loggedIn(); break; case SimpleSgsProtocol.LOGIN_FAILURE: { String reason = msg.getString(); logger.log(Level.FINER, "Login failed: {0}", reason); suppressDisconnectedCallback = true; try { clientConnection.disconnect(); } catch (IOException e) { if (logger.isLoggable(Level.FINE)) { logger.logThrow(Level.FINE, e, "Disconnecting after login failure throws"); } // ignore } clientListener.loginFailed(reason); break; } case SimpleSgsProtocol.LOGIN_REDIRECT: { String host = msg.getString(); int port = msg.getInt(); logger.log(Level.FINER, "Login redirect: {0}:{1}", host, port); // Disconnect our current connection, and connect to the // new host and port ClientConnection oldConnection = clientConnection; synchronized (SimpleClient.this) { clientConnection = null; connectionStateChanging = true; } try { oldConnection.disconnect(); } catch (IOException e) { if (logger.isLoggable(Level.FINE)) { logger.logThrow(Level.FINE, e, "Disconnecting after login redirect throws"); } // ignore } redirect = true; Properties props = new Properties(); props.setProperty("host", host); props.setProperty("port", String.valueOf(port)); ClientConnector connector = ClientConnector.create(props); // We use a new listener so we don't have to worry about // "redirect" being incorrect. connListener = new SimpleClientConnectionListener(); // This eventually causes connected to be called connector.connect(connListener); break; } case SimpleSgsProtocol.SESSION_MESSAGE: { logger.log(Level.FINEST, "Direct receive"); checkLoggedIn(); byte[] msgBytes = msg.getBytes(msg.limit() - msg.position()); ByteBuffer buf = ByteBuffer.wrap(msgBytes); try { clientListener.receivedMessage(buf.asReadOnlyBuffer()); } catch (RuntimeException e) { if (logger.isLoggable(Level.WARNING)) { logger.logThrow( Level.WARNING, e, "SimpleClientListener.receivedMessage callback " + "throws"); } } break; } case SimpleSgsProtocol.RECONNECT_SUCCESS: logger.log(Level.FINER, "Reconnected"); loggedIn = true; reconnectKey = msg.getBytes(msg.limit() - msg.position()); clientListener.reconnected(); break; case SimpleSgsProtocol.RECONNECT_FAILURE: try { String reason = msg.getString(); logger.log(Level.FINER, "Reconnect failed: {0}", reason); clientConnection.disconnect(); } catch (IOException e) { if (logger.isLoggable(Level.FINE)) { logger.logThrow(Level.FINE, e, "Disconnecting a failed reconnect throws"); } // ignore } break; case SimpleSgsProtocol.LOGOUT_SUCCESS: logger.log(Level.FINER, "Logged out gracefully"); expectingDisconnect = true; loggedIn = false; try { clientConnection.disconnect(); } catch (IOException e) { if (logger.isLoggable(Level.FINE)) { logger.logThrow(Level.FINE, e, "Disconnecting after graceful logout throws"); } // ignore } break; case SimpleSgsProtocol.CHANNEL_JOIN: { logger.log(Level.FINER, "Channel join"); checkLoggedIn(); String channelName = msg.getString(); byte[] channelIdBytes = msg.getBytes(msg.limit() - msg.position()); BigInteger channelId = new BigInteger(1, channelIdBytes); SimpleClientChannel channel = new SimpleClientChannel(channelName, channelId); if (channels.putIfAbsent(channelId, channel) == null) { channel.joined(); } else { logger.log(Level.WARNING, "Cannot join channel {0}: already a member", channelName); } break; } case SimpleSgsProtocol.CHANNEL_LEAVE: { logger.log(Level.FINER, "Channel leave"); checkLoggedIn(); byte[] channelIdBytes = msg.getBytes(msg.limit() - msg.position()); BigInteger channelId = new BigInteger(1, channelIdBytes); SimpleClientChannel channel = channels.remove(channelId); if (channel != null) { channel.left(); } else { logger.log(Level.WARNING, "Cannot leave channel {0}: not a member", channelId); } break; } case SimpleSgsProtocol.CHANNEL_MESSAGE: logger.log(Level.FINEST, "Channel recv"); checkLoggedIn(); BigInteger channelId = new BigInteger(1, msg.getBytes(msg.getShort())); SimpleClientChannel channel = channels.get(channelId); if (channel == null) { logger.log(Level.WARNING, "Ignore message on channel {0}: not a member", channelId); return; } byte[] msgBytes = msg.getBytes(msg.limit() - msg.position()); ByteBuffer buf = ByteBuffer.wrap(msgBytes); channel.receivedMessage(buf.asReadOnlyBuffer()); break; default: throw new IOException( String.format("Unknown session opcode: 0x%02X", command)); } }